restlet-2.0.14/0000775000175000017500000000000012001473210013722 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/0000775000175000017500000000000012001473202020273 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/pom.xml0000600000175000017500000000411512001473201021576 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.spring Restlet Extension - Spring Framework Integration with Spring Framework. cglib cglib-nodep 2.2 commons-logging commons-logging 1.1.1 org.springframework spring-asm 3.0.1.RELEASE org.springframework spring-beans 3.0.1.RELEASE org.springframework spring-context 3.0.1.RELEASE org.springframework spring-core 3.0.1.RELEASE org.springframework spring-expression 3.0.1.RELEASE org.springframework spring-web 3.0.1.RELEASE org.springframework spring-webmvc 3.0.1.RELEASE org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.spring/src/0000775000175000017500000000000012001473201021061 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/src/META-INF/0000775000175000017500000000000011757206452022244 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023675 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.spring/src/org/0000775000175000017500000000000011757206352021672 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/src/org/restlet/0000775000175000017500000000000011757206352023354 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/0000775000175000017500000000000011757206352024154 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/0000775000175000017500000000000011757206352025456 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringResource.java0000664000175000017500000001026411757206352031276 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.io.IOException; import java.io.InputStream; import org.restlet.representation.Representation; import org.springframework.core.io.AbstractResource; /** * Spring Resource based on a Restlet Representation. DON'T GET CONFUSED, * Spring's notion of Resource is different from Restlet's one, actually it's * closer to Restlet's Representations. * * @see Spring home page * @author Jerome Louvel */ public class SpringResource extends AbstractResource { /** The description. */ private final String description; /** Indicates if the representation has already been read. */ private volatile boolean read = false; /** The wrapped representation. */ private final Representation representation; /** * Constructor. * * @param representation * The description. */ public SpringResource(Representation representation) { this(representation, "Restlet Representation"); } /** * Constructor. * * @param representation * The description. * @param description * The description. */ public SpringResource(Representation representation, String description) { if (representation == null) { throw new IllegalArgumentException( "Representation must not be null"); } this.representation = representation; this.description = (description != null) ? description : ""; } /** * This implementation compares the underlying InputStream. */ @Override public boolean equals(Object obj) { return ((obj == this) || ((obj instanceof SpringResource) && ((SpringResource) obj).representation .equals(this.representation))); } /** * This implementation always returns true. */ @Override public boolean exists() { return true; } /** * Returns the description. * * @return The description. */ public String getDescription() { return this.description; } /** * This implementation throws IllegalStateException if attempting to read * the underlying stream multiple times. */ public InputStream getInputStream() throws IOException, IllegalStateException { if (this.read && this.representation.isTransient()) { throw new IllegalStateException( "Representation has already been read and is transient."); } this.read = true; return this.representation.getStream(); } /** * This implementation returns the hash code of the underlying InputStream. */ @Override public int hashCode() { return this.representation.hashCode(); } /** * This implementation always returns true. */ @Override public boolean isOpen() { return true; } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringHost.java0000664000175000017500000000724411757206352030430 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.util.Map; import org.restlet.Component; import org.restlet.Context; import org.restlet.resource.ServerResource; import org.restlet.routing.VirtualHost; /** * Virtual host that is easily configurable with Spring. Here is a usage * example: * *
 *     <bean id="virtualHost" class="org.restlet.ext.spring.SpringHost">
 *         <constructor-arg ref="component" />
 *         <property name="hostDomain"
 *                 value="mydomain.com|www.mydomain.com" />
 *         <property name="attachments">
 *             <map>
 *                 <entry key="/">
 *                     <ref bean="application" />
 *                 </entry>
 *             </map>
 *         </property>
 *     </bean>
 * 
* * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see Spring home page * @author Jerome Louvel */ public class SpringHost extends VirtualHost { /** * Constructor. * * @param component * The parent component. */ public SpringHost(Component component) { super(component.getContext()); } /** * Constructor. * * @param context * The parent context. */ public SpringHost(Context context) { super(context); } /** * Sets the map of routes to attach. The map keys are the URI templates and * the values can be either Restlet instances, {@link ServerResource} * subclasses (as {@link Class} instances or as qualified class names). * * @param routes * The map of routes to attach. */ public void setAttachments(Map routes) { SpringRouter.setAttachments(this, routes); } /** * Sets the default route to attach. The route can be either Restlet * instances, {@link ServerResource} subclasses (as {@link Class} instances * or as qualified class names). * * @param route * The default route to attach. */ public void setDefaultAttachment(Object route) { SpringRouter.setAttachment(this, "", route); } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringFinder.java0000664000175000017500000001476411757206352030727 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.resource.Finder; import org.restlet.resource.ServerResource; /** * Finder that is specialized for easier usage by Spring wiring services. The * idea is to create a singleton Spring bean based on that SpringFinder and * configure it using Spring's "lookup-method" element to return instances of a * "prototype" bean for {@link #create()}. Finally, attach the SpringFinder to * your Router. When the {@link #create()} method is invoked, a new instance of * your prototype bean will be created and returned. A sample XML for * "lookup-method": * *
 *      <bean id="myFinder" class="org.restlet.ext.spring.SpringFinder"> 
 *              <lookup-method name="create" bean="myResource"/> 
 *      </bean>
 *       
 *      <bean id="myResource" class="com.mycompany.rest.resource.MyResource" scope="prototype"> 
 *              <property name="aProperty" value="anotherOne"/> 
 *              <property name="oneMore" value="true"/>
 *      </bean>
 * 
* * Note that the Code Generation * Library (cglib) will be required in order to use the Spring's lookup * method mechanism.
*
* Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see Spring home page * @author Jerome Louvel */ public class SpringFinder extends Finder { /** * Constructor. */ public SpringFinder() { super(); } /** * Constructor. * * @param context * The parent context. */ public SpringFinder(Context context) { super(context); } /** * Constructor. * * @param context * The context. * @param targetClass * The target resource class. */ public SpringFinder(Context context, Class targetClass) { super(context, targetClass); } /** * Constructor. * * @param restlet * The parent Restlet. */ public SpringFinder(Restlet restlet) { super(restlet.getContext()); } /** * Creates a new instance of the {@link ServerResource} class designated by * the "targetClass" property. This method is intended to be configured as a * lookup method in Spring. * * @return The created resource or null. */ public ServerResource create() { ServerResource result = null; if (getTargetClass() != null) { try { // Invoke the default constructor result = (ServerResource) getTargetClass().newInstance(); } catch (Exception e) { getLogger() .log( Level.WARNING, "Exception while instantiating the target server resource.", e); } } return result; } /** * Calls the {@link #create()} method that can be configured as a lookup * method in Spring. */ @Override public ServerResource create(Class targetClass, Request request, Response response) { return create(request, response); } @Override public org.restlet.resource.ServerResource create(Request request, Response response) { return create(); } /** * Creates a new instance of the resource class designated by the * "targetClass" property. For easier Spring configuration, the default * target resource's constructor is invoked. The created instance must be * initialized by invoking the * {@link org.restlet.resource.Resource#init(Context, Request, Response)} * method on the resource. * * @return The created resource or null. */ @SuppressWarnings("deprecation") public org.restlet.resource.Resource createResource() { org.restlet.resource.Resource result = null; if (getTargetClass() != null) { try { // Invoke the default constructor result = (org.restlet.resource.Resource) getTargetClass() .newInstance(); } catch (Exception e) { getLogger() .log( Level.WARNING, "Exception while instantiating the target resource.", e); } } return result; } @SuppressWarnings("deprecation") @Override public org.restlet.resource.Resource createTarget(Request request, Response response) { org.restlet.resource.Resource result = createResource(); if (result != null) { result.init(getContext(), request, response); } return result; } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/package.html0000664000175000017500000000024311757206352027736 0ustar jamespagejamespage Integration with Spring Framework 3.0. @since Restlet 1.0 @see Spring Framework restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringContext.java0000664000175000017500000001411411757206352031131 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.util.ArrayList; import java.util.List; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.Method; import org.restlet.representation.Representation; import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.GenericApplicationContext; /** * Spring application context based on a Restlet context. Here is an example * illustrating the various ways to use this class: * *
 * SpringContext springContext = new SpringContext(getContext());
 * springContext.getPropertyConfigRefs().add("war://config/database.properties");
 * springContext.getXmlConfigRefs().add("war://config/applicationContext.xml");
 * springContext.getXmlConfigRefs().add(
 *         "file:///C/myApp/config/applicationContext.xml");
 * springContext.getXmlConfigRefs().add(
 *         "clap://thread/config/applicationContext.xml");
 * 
* * @author Jerome Louvel */ public class SpringContext extends GenericApplicationContext { /** The parent Restlet context. */ private volatile Context restletContext; /** * The modifiable list of configuration URIs for beans definitions via * property representations. */ private volatile List propertyConfigRefs; /** * The modifiable list of configuration URIs for beans definitions via XML * representations. */ private volatile List xmlConfigRefs; /** Indicates if the context has been already loaded. */ private volatile boolean loaded; /** * Constructor. * * @param restletContext * The parent Restlet context. */ public SpringContext(Context restletContext) { this.restletContext = restletContext; this.propertyConfigRefs = null; this.xmlConfigRefs = null; this.loaded = false; } /** * Returns the modifiable list of configuration URIs for beans definitions * via property representations. * * @return The modifiable list of configuration URIs. */ public List getPropertyConfigRefs() { // Lazy initialization with double-check. List p = this.propertyConfigRefs; if (p == null) { synchronized (this) { p = this.propertyConfigRefs; if (p == null) { this.propertyConfigRefs = p = new ArrayList(); } } } return p; } /** * Returns the parent Restlet context. * * @return The parent Restlet context. */ public Context getRestletContext() { return this.restletContext; } /** * Returns the modifiable list of configuration URIs for beans definitions * via XML representations. * * @return The modifiable list of configuration URIs. */ public List getXmlConfigRefs() { // Lazy initialization with double-check. List x = this.xmlConfigRefs; if (x == null) { synchronized (this) { x = this.xmlConfigRefs; if (x == null) { this.xmlConfigRefs = x = new ArrayList(); } } } return x; } @Override public void refresh() { // If this context hasn't been loaded yet, read all the configurations // registered if (!this.loaded) { Representation config = null; // First, read the bean definitions from properties representations PropertiesBeanDefinitionReader propReader = null; for (final String ref : getPropertyConfigRefs()) { config = getRestletContext().getClientDispatcher().handle( new Request(Method.GET, ref)).getEntity(); if (config != null) { propReader = new PropertiesBeanDefinitionReader(this); propReader.loadBeanDefinitions(new SpringResource(config)); } } // Then, read the bean definitions from XML representations XmlBeanDefinitionReader xmlReader = null; for (final String ref : getXmlConfigRefs()) { config = getRestletContext().getClientDispatcher().handle( new Request(Method.GET, ref)).getEntity(); if (config != null) { xmlReader = new XmlBeanDefinitionReader(this); xmlReader .setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); xmlReader.loadBeanDefinitions(new SpringResource(config)); } } } // Now load or refresh super.refresh(); } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringServer.java0000664000175000017500000000704111757206352030754 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.util.Enumeration; import java.util.Properties; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.Protocol; /** * Server that is easily configurable with Spring. Here is a usage example: * *
 * <bean id="server" class="org.restlet.ext.spring.SpringServer">
 *      <constructor-arg value="http" />
 *      <constructor-arg value="8111" />
 * </bean>
 * 
* * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see Spring home page * @author Jerome Louvel */ public class SpringServer extends org.restlet.Server { /** * Constructor. * * @param protocol * The server's protocol such as "HTTP" or "HTTPS". */ public SpringServer(String protocol) { super(new Context(), Protocol.valueOf(protocol), (Restlet) null); } /** * Constructor. * * @param protocol * The server's protocol such as "HTTP" or "HTTPS". * @param port * The port number. */ public SpringServer(String protocol, int port) { super(new Context(), Protocol.valueOf(protocol), port, (Restlet) null); } /** * Constructor. * * @param protocol * The server's protocol such as "HTTP" or "HTTPS". * @param address * The IP address. * @param port * The port number. */ public SpringServer(String protocol, String address, int port) { super(new Context(), Protocol.valueOf(protocol), address, port, null); } /** * Sets parameters on the server. * * @param parameters * Parameters to set on the server. */ public void setParameters(Properties parameters) { final Enumeration names = parameters.propertyNames(); while (names.hasMoreElements()) { final String name = (String) names.nextElement(); getContext().getParameters() .add(name, parameters.getProperty(name)); } } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringRouter.java0000664000175000017500000001413411757206352030767 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.util.Map; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.engine.Engine; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * Router that is easily configurable with Spring. Here is a usage example: * *
 * <bean class="org.restlet.ext.spring.SpringRouter">
 *     <constructor-arg ref="application" />
 * 
 *     <property name="attachments">
 *         <map>
 *             <entry key="/users/{user}"                  value="org.restlet.example.tutorial.UserResource" />
 *             <entry key="/users/{user}/orders"           value="org.restlet.example.tutorial.OrdersResource" />
 *             <entry key="/users/{user}/orders/{order}"   value="org.restlet.example.tutorial.OrderResource" />
 *         </map>
 *     </property>
 * </bean>
 * 
* * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see Spring home page * @author Jerome Louvel */ public class SpringRouter extends Router { /** * Attach a single route. * * @param router * The router to attach to. * @param path * The attachment URI path. * @param route * The route object to attach. */ @SuppressWarnings("deprecation") public static void setAttachment(Router router, String path, Object route) { Class resourceClass; if (route instanceof Restlet) { router.attach(path, (Restlet) route); } else if (route instanceof Class) { router.attach(path, (Class) route); } else if (route instanceof String) { try { resourceClass = Engine.loadClass((String) route); if (org.restlet.resource.Resource.class .isAssignableFrom(resourceClass)) { router.attach(path, resourceClass); } else if (org.restlet.resource.ServerResource.class .isAssignableFrom(resourceClass)) { router.attach(path, resourceClass); } else { router .getLogger() .warning( "Unknown class found in the mappings. Only subclasses of org.restlet.resource.Resource and ServerResource are allowed."); } } catch (ClassNotFoundException e) { router.getLogger().log(Level.WARNING, "Unable to set the router mappings", e); } } else { router .getLogger() .warning( "Unknown object found in the mappings. Only instances of Restlet and subclasses of org.restlet.resource.Resource and ServerResource are allowed."); } } /** * Sets the map of routes to attach. * * @param router * The router to attach to. * @param routes * The map of routes to attach */ public static void setAttachments(Router router, Map routes) { for (String key : routes.keySet()) { setAttachment(router, key, routes.get(key)); } } /** * Constructor. */ public SpringRouter() { super(); } /** * Constructor with a parent context. * * @param context * The parent context. */ public SpringRouter(Context context) { super(context); } /** * Constructor with a parent Restlet. * * @param parent * The parent Restlet. */ public SpringRouter(Restlet parent) { super(parent.getContext()); } /** * Sets the map of routes to attach. The map keys are the URI templates and * the values can be either Restlet instances, {@link ServerResource} * subclasses (as {@link Class} instances or as qualified class names). * * @param routes * The map of routes to attach. */ public void setAttachments(Map routes) { setAttachments(this, routes); } /** * Sets the default route to attach. The route can be either Restlet * instances, {@link ServerResource} subclasses (as {@link Class} instances * or as qualified class names). * * @param route * The default route to attach. */ public void setDefaultAttachment(Object route) { setAttachment(this, "", route); } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringComponent.java0000664000175000017500000001414411757206352031452 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.util.ArrayList; import java.util.List; import org.restlet.Client; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; /** * Component that is easily configurable from Spring. Here is a usage example: * *
 * <bean id="component"
 *         class="org.restlet.ext.spring.SpringComponent">
 *         <property name="clientsList">
 *                 <list>
 *                         <value>file</value>
 *                 </list>
 *         </property>
 *         <property name="server" ref="server" />
 *         <property name="defaultTarget" ref="application" />
 *         <property name="hosts">
 *                 <list>
 *                         <ref bean="virtualHost" />
 *                 </list>
 *         </property>
 * </bean>
 * 
 * <bean id="component.context"
 *         class="org.springframework.beans.factory.config.PropertyPathFactoryBean" />
 * 
 * <bean id="server" class="org.restlet.ext.spring.SpringServer">
 *         <constructor-arg value="http" />
 *         <constructor-arg value="8111" />
 *         <property name="parameters">
 *                 <props>
 *                         <prop key="key1">value1</prop>
 *                         <prop key="key2">value2</prop>
 *                 </props>
 *         </property>
 * </bean>
 * 
* * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see Spring home page * @author Jerome Louvel */ public class SpringComponent extends org.restlet.Component { /** * Adds a client to the list of connectors. The value can be either a * protocol name, a Protocol instance or a Client instance. * * @param clientInfo * The client info. */ public void setClient(Object clientInfo) { final List clients = new ArrayList(); clients.add(clientInfo); setClientsList(clients); } /** * Sets the list of clients, either as protocol names, Protocol instances or * Client instances. * * @param clients * The list of clients. */ public synchronized void setClientsList(List clients) { for (final Object client : clients) { if (client instanceof String) { getClients().add(Protocol.valueOf((String) client)); } else if (client instanceof Protocol) { getClients().add((Protocol) client); } else if (client instanceof Client) { getClients().add((Client) client); } else { getLogger() .warning( "Unknown object found in the clients list. Only instances of String, org.restlet.data.Protocol and org.restlet.Client are allowed."); } } } /** * Attaches a target Restlet to the default host. * * @param target * The target Restlet. */ public void setDefaultTarget(Restlet target) { getDefaultHost().attach(target); } /** * Adds a server to the list of connectors. The value can be either a * protocol name, a Protocol instance or a Server instance. * * @param serverInfo * The server info. */ public void setServer(Object serverInfo) { final List servers = new ArrayList(); servers.add(serverInfo); setServersList(servers); } /** * Sets the list of servers, either as protocol names, Protocol instances or * Server instances. * * @param serversInfo * The list of servers. */ public void setServersList(List serversInfo) { for (final Object serverInfo : serversInfo) { if (serverInfo instanceof String) { getServers().add(Protocol.valueOf((String) serverInfo)); } else if (serverInfo instanceof Protocol) { getServers().add((Protocol) serverInfo); } else if (serverInfo instanceof Server) { getServers().add((Server) serverInfo); } else { getLogger() .warning( "Unknown object found in the servers list. Only instances of String, org.restlet.data.Protocol and org.restlet.Server are allowed."); } } } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanFinder.java0000664000175000017500000001504111757206352031502 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import org.restlet.Context; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * An alternative to {@link SpringFinder} which uses Spring's BeanFactory * mechanism to load a prototype bean by name. * * If both a {@link BeanFactory} and a {@link ApplicationContext} are provided, * the bean will be looked up first in the application context and then in the * bean factory. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Rhett Sutphin */ public class SpringBeanFinder extends SpringFinder implements BeanFactoryAware, ApplicationContextAware { /** The parent application context. */ private volatile ApplicationContext applicationContext; /** The parent bean factory. */ private volatile BeanFactory beanFactory; /** The bean name. */ private volatile String beanName; /** The associated router. */ private volatile Router router; /** * Default constructor. */ public SpringBeanFinder() { } /** * Constructor. * * @param router * The associated router used to retrieve the context. * @param beanFactory * The Spring bean factory. * @param beanName * The bean name. */ public SpringBeanFinder(Router router, BeanFactory beanFactory, String beanName) { this.router = router; setBeanFactory(beanFactory); setBeanName(beanName); } @Override public ServerResource create() { final ServerResource resource = findBean(ServerResource.class); if (resource == null) { throw new ClassCastException(getBeanName() + " does not resolve to an instance of " + org.restlet.resource.ServerResource.class.getName()); } return resource; } @SuppressWarnings("deprecation") @Override public org.restlet.resource.Resource createResource() { return findBean(org.restlet.resource.Resource.class); } @SuppressWarnings({ "unchecked" }) private T findBean(Class expectedType) { if (getBeanFactory() == null && getApplicationContext() == null) { throw new IllegalStateException( "Either a beanFactory or an applicationContext is required for SpringBeanFinder."); } BeanFactory effectiveFactory = getApplicationContext(); if (effectiveFactory == null) effectiveFactory = getBeanFactory(); if (effectiveFactory.containsBean(getBeanName())) { if (expectedType.isAssignableFrom(effectiveFactory.getType(getBeanName()))) { return (T) effectiveFactory.getBean(getBeanName()); } else { return null; } } else { throw new IllegalStateException(String.format( "No bean named %s present.", getBeanName())); } } /** * Returns the parent application context. * * @return The parent context. */ public ApplicationContext getApplicationContext() { return applicationContext; } /** * Returns the parent bean factory. * * @return The parent bean factory. */ public BeanFactory getBeanFactory() { return this.beanFactory; } /** * Returns the bean name. * * @return The bean name. */ public String getBeanName() { return this.beanName; } @Override public Context getContext() { return (getRouter() == null) ? Context.getCurrent() : getRouter() .getContext(); } /** * Returns the associated router. * * @return The associated router. */ public Router getRouter() { return router; } /** * Returns the associated router. * * @return The associated router. * @deprecated Use {@link #getRouter()} instead */ @Deprecated public SpringBeanRouter getSpringBeanRouter() { return (SpringBeanRouter) router; } /** * Sets the parent application context * * @param applicationContext * The parent context. */ public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Sets the parent bean factory. * * @param beanFactory * The parent bean factory. */ public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } /** * Sets the bean name. * * @param beanName * The bean name. */ public void setBeanName(String beanName) { this.beanName = beanName; } /** * Sets the associated router. * * @param router * The associated router. */ public void setRouter(Router router) { this.router = router; } } restlet-2.0.14/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java0000664000175000017500000003346511757206352031565 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.spring; import java.util.Map; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.resource.Finder; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Restlet {@link Router} which behaves like Spring's * {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping}. It * takes every bean of type {@link org.restlet.resource.ServerResource} or * {@link Restlet} defined in a particular context and examines its aliases * (generally speaking, its name and id). If one of the aliases begins with a * forward slash, the resource will be attached to that URI. *

* Example: * *

 * <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" >
 *    <!-- Singleton instance of this class -->
 *    <bean name="router" class="org.restlet.ext.spring.SpringBeanRouter"/>
 * 
 *    <!-- Prototype beans for the resources -->
 *    <bean name="/studies" id="studiesResource" autowire="byName" scope="prototype" class="edu.northwestern.myapp.StudiesResource" >
 *       <property name="studyDao" ref="studyDao"/>
 *    </bean>
 * 
 *    <bean name="/studies/{study-identifier}/template" id="templateResource" autowire="byName" scope="prototype" class="edu.northwestern.myapp.TemplateResource" />
 * 
 *    <!-- Singleton bean for a restlet -->
 *    <bean name="/studies/{study-identifier}/files" id="filesResource" autowire="byName" class="edu.northwestern.myapp.MyDirectory" />
 * </beans>
 * 
* * This will route two resources and one restlet: "/studies", * "/studies/{study-identifier}/template", and * "/studies/{study-identifier}/files" to the corresponding beans. * N.b.: Resources must be scoped prototype, since a new instance must be * created for each request. Restlets may be singletons (this class will only * ever load one instance for each). * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Rhett Sutphin * @author James Maki */ public class SpringBeanRouter extends Router implements ApplicationContextAware, BeanFactoryPostProcessor { /** The Spring application context. */ private volatile ApplicationContext applicationContext; /** Supplemental explicit mappings. */ private Map attachments; /** If beans should be searched for higher up in the BeanFactory hierarchy. */ private volatile boolean findingInAncestors = true; /** * Constructor. */ public SpringBeanRouter() { super(); } /** * Constructor with a parent context. */ public SpringBeanRouter(Context context) { super(context); } /** * Constructor with a parent Restlet. */ public SpringBeanRouter(Restlet parent) { super(parent.getContext()); } /** * Attaches all the resources. * * @param beanFactory * The Spring bean factory. */ @SuppressWarnings("deprecation") private void attachAllResources(ListableBeanFactory beanFactory) { for (String beanName : getBeanNamesByType( org.restlet.resource.Resource.class, beanFactory)) { String uri = resolveUri(beanName, beanFactory); if (uri != null) attachResource(uri, beanName, beanFactory); } for (String beanName : getBeanNamesByType( org.restlet.resource.ServerResource.class, beanFactory)) { String uri = resolveUri(beanName, beanFactory); if (uri != null) attachResource(uri, beanName, beanFactory); } } /** * Attaches all the Restlet instances. * * @param beanFactory * The Spring bean factory. */ private void attachAllRestlets(ListableBeanFactory beanFactory) { for (String beanName : getBeanNamesByType(Restlet.class, beanFactory)) { String uri = resolveUri(beanName, beanFactory); if (uri != null) attachRestlet(uri, beanName, beanFactory); } } /** * Attaches the named resource bean at the given URI, creating a finder for * it via {@link #createFinder(BeanFactory, String)}. * * @param uri * The attachment URI. * @param beanName * The bean name. * @param beanFactory * The Spring bean factory. */ protected void attachResource(String uri, String beanName, BeanFactory beanFactory) { attach(uri, createFinder(beanFactory, beanName)); } /** * Attaches the named restlet bean directly at the given URI. * * @param uri * The attachment URI. * @param beanName * The bean name. * @param beanFactory * The Spring bean factory. */ protected void attachRestlet(String uri, String beanName, BeanFactory beanFactory) { attach(uri, (Restlet) beanFactory.getBean(beanName)); } /** * Creates an instance of {@link SpringBeanFinder}. This can be overridden * if necessary. * * @param beanFactory * The Spring bean factory. * @param beanName * The bean name. * @see #attachResource */ protected Finder createFinder(BeanFactory beanFactory, String beanName) { return new SpringBeanFinder(this, beanFactory, beanName); } /** * Returns supplemental explicit mappings * * @return Supplemental explicit mappings */ protected Map getAttachments() { return this.attachments; } /** * Returns the list of bean name for the given type. * * @param beanClass * The bean class to lookup. * @param beanFactory * The Spring bean factory. * @return The array of bean names. */ private String[] getBeanNamesByType(Class beanClass, ListableBeanFactory beanFactory) { return isFindingInAncestors() ? BeanFactoryUtils .beanNamesForTypeIncludingAncestors(beanFactory, beanClass, true, true) : beanFactory.getBeanNamesForType( beanClass, true, true); } /** * Indicates if the attachments contain a mapping for the given URI. * * @param name * The name to test. * @return True if the attachments contain a mapping for the given URI. */ private boolean isAvailableUri(String name) { return name.startsWith("/") && (getAttachments() == null || !getAttachments().containsKey( name)); } /** * Returns true if bean names will be searched for higher up in the * BeanFactory hierarchy. Default is true. * * @return True if bean names will be searched for higher up in the * BeanFactory hierarchy. * @deprecated Use {@link #isFindingInAncestors()} instead. */ @Deprecated public boolean isFindInAncestors() { return this.findingInAncestors; } /** * Returns true if bean names will be searched for higher up in the * BeanFactory hierarchy. Default is true. * * @return True if bean names will be searched for higher up in the * BeanFactory hierarchy. */ public boolean isFindingInAncestors() { return isFindInAncestors(); } /** * Attaches all {@link ServerResource} and {@link Restlet} beans found in * the surrounding bean factory for which {@link #resolveUri} finds a usable * URI. Also attaches everything explicitly routed in the attachments * property. * * @param beanFactory * The Spring bean factory. * @see #setAttachments */ @SuppressWarnings("deprecation") public void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory) throws BeansException { ListableBeanFactory source = this.applicationContext == null ? beanFactory : this.applicationContext; attachAllResources(source); attachAllRestlets(source); if (getAttachments() != null) { for (Map.Entry attachment : getAttachments() .entrySet()) { String uri = attachment.getKey(); String beanName = attachment.getValue(); Class beanType = source.getType(beanName); if (org.restlet.resource.Resource.class .isAssignableFrom(beanType)) { attachResource(uri, beanName, source); } else if (org.restlet.resource.ServerResource.class .isAssignableFrom(beanType)) { attachResource(uri, beanName, source); } else if (Restlet.class.isAssignableFrom(beanType)) { attachRestlet(uri, beanName, source); } else { throw new IllegalStateException( beanName + " is not routable. It must be either a Resource, a ServerResource or a Restlet."); } } } } /** * Uses this first alias for this bean that starts with '/' and is not * mapped in the explicit attachments to another bean. This mimics the * behavior of * {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping} * . * * @param beanName * The bean name to lookup in the bean factory aliases. * @param beanFactory * The Spring bean factory. * @return The alias URI. */ protected String resolveUri(String beanName, ListableBeanFactory beanFactory) { if (isAvailableUri(beanName)) { return beanName; } for (final String alias : beanFactory.getAliases(beanName)) { if (isAvailableUri(alias)) { return alias; } } return null; } /** * Sets the Spring application context. * * @param applicationContext * The context. */ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * Sets an explicit mapping of URI templates to bean IDs to use in addition * to the usual bean name mapping behavior. If a URI template appears in * both this mapping and as a bean name, the bean it is mapped to here is * the one that will be used. * * @param attachments * Supplemental explicit mappings. * @see SpringRouter */ public void setAttachments(Map attachments) { this.attachments = attachments; } /** * Sets if bean names will be searched for higher up in the BeanFactory * hierarchy. * * @param findingInAncestors * Search for beans higher up in the BeanFactory hierarchy. * @deprecated Use {@link #setFindingInAncestors(boolean)} instead. */ @Deprecated public void setFindInAncestors(boolean findingInAncestors) { this.findingInAncestors = findingInAncestors; } /** * Sets if bean names will be searched for higher up in the BeanFactory * hierarchy. * * @param findingInAncestors * Search for beans higher up in the BeanFactory hierarchy. */ public void setFindingInAncestors(boolean findingInAncestors) { setFindInAncestors(findingInAncestors); } } restlet-2.0.14/org.restlet.ext.jibx/0000775000175000017500000000000012001473142017730 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jibx/pom.xml0000600000175000017500000000154312001473142021236 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.jibx Restlet Extension - JiBX Integration with JiBX. org.jibx jibx-run 1.2.2 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.jibx/src/0000775000175000017500000000000012001473141020516 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jibx/src/META-INF/0000775000175000017500000000000011757206452021676 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jibx/src/META-INF/services/0000775000175000017500000000000011757206346023523 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jibx/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.jibx/src/META-INF/services/org.restlet.engine.converter.ConverterHelp0000664000175000017500000000004211757206346033743 0ustar jamespagejamespageorg.restlet.ext.jibx.JibxConverterrestlet-2.0.14/org.restlet.ext.jibx/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023327 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.jibx/src/org/0000775000175000017500000000000011757206346021327 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jibx/src/org/restlet/0000775000175000017500000000000011757206346023011 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jibx/src/org/restlet/ext/0000775000175000017500000000000011757206346023611 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jibx/src/org/restlet/ext/jibx/0000775000175000017500000000000011757206346024545 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jibx/src/org/restlet/ext/jibx/JibxRepresentation.java0000664000175000017500000002202611757206346031231 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jibx; import java.io.IOException; import java.io.Writer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IBindingFactory; import org.jibx.runtime.IMarshallable; import org.jibx.runtime.IMarshallingContext; import org.jibx.runtime.IUnmarshallingContext; import org.jibx.runtime.JiBXException; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.xml.sax.InputSource; /** * An XML representation based on JiBX that provides easy translation between * XML representations and Java objects with JiBX bindings. * * @param * The type to wrap. * @author Florian Schwarz * @see JiBX project */ public class JibxRepresentation extends WriterRepresentation { /** * Improves performance by caching contexts which are expensive to create. * (All binding factory instances are guaranteed to be thread safe and * reusable.) */ private final static ConcurrentMap bindingFactories = new ConcurrentHashMap(); /** * Get a cached binding factory. * * @param bindingName * The name of the binding to use. * @param bindingClass * Target class for binding. * @return A binding factory. * @throws JiBXException */ private static synchronized IBindingFactory getBindingFactory( String bindingName, Class bindingClass) throws JiBXException { // All binding factory instances are guaranteed to be thread safe and // reusable. IBindingFactory jibxBFact = bindingFactories.get(bindingName + bindingClass.toString()); if (jibxBFact == null) { if (bindingName == null) { jibxBFact = BindingDirectory.getFactory(bindingClass); } else { jibxBFact = BindingDirectory.getFactory(bindingName, bindingClass); } bindingFactories.put(bindingName + bindingClass.toString(), jibxBFact); } return jibxBFact; } /** Class for target binding. */ private volatile Class bindingClass; /** The binding name to use. */ private volatile String bindingName; /** The wrapped Java object. */ private volatile T object; /** The source XML representation. */ private volatile Representation xmlRepresentation; /** * Creates a JIBX representation from an existing Java object. This allows a * translation from a Java object to a XML representation. * * @param mediaType * The representation's media type (usually * MediaType.APPLICATION_XML or MediaType.TEXT_XML). * @param object * The Java object. */ public JibxRepresentation(MediaType mediaType, T object) { this(mediaType, object, null); } /** * Creates a JIBX representation from an existing Java object. This allows a * translation from a Java object to a XML representation. * * @param mediaType * The representation's media type (usually * MediaType.APPLICATION_XML or MediaType.TEXT_XML). * @param object * The Java object. * @param bindingName * The name of the JIBX binding to use. */ public JibxRepresentation(MediaType mediaType, T object, String bindingName) { super(mediaType); setCharacterSet(CharacterSet.UTF_8); this.object = object; this.bindingClass = object.getClass(); this.bindingName = bindingName; } /** * Creates a new JIBX representation, that can be used to convert the input * XML into a Java object. The XML is not validated. * * @param xmlRepresentation * The XML wrapped in a representation. * @param bindingClass * The Target Java class for binding. */ public JibxRepresentation(Representation xmlRepresentation, Class bindingClass) { this(xmlRepresentation, bindingClass, null); } /** * Creates a new JIBX representation, that can be used to convert the input * XML into a Java object. The XML is not validated. * * @param xmlRepresentation * The XML wrapped in a representation. * @param bindingClass * The Target Java class for binding. * @param bindingName * The name of the JIBX binding to use. */ public JibxRepresentation(Representation xmlRepresentation, Class bindingClass, String bindingName) { super(xmlRepresentation.getMediaType()); this.xmlRepresentation = xmlRepresentation; this.bindingClass = bindingClass; this.bindingName = bindingName; } /** * Returns the document encoding to use for marshalling. The default value * is UTF-8. * * @return The document encoding to use for marshalling. * @deprecated Use {@link #getCharacterSet()} instead. */ @Deprecated public String getEncoding() { return getCharacterSet().getName(); } /** * Returns the XML representation as a SAX input source. * * @return The SAX input source. * @deprecated */ @Deprecated public InputSource getInputSource() throws IOException { return new InputSource(this.xmlRepresentation.getReader()); } /** * Returns the wrapped Java object. * * @return The wrapped Java object. * @throws JiBXException * If unmarshalling XML with JIBX fails. * @throws IOException * If any error occurs attempting to get the stream of the * xmlRepresentation. */ @SuppressWarnings("unchecked") public T getObject() throws JiBXException, IOException { if ((this.object == null) && (this.xmlRepresentation != null)) { // Try to unmarshal the wrapped XML representation IBindingFactory jibxBFact = JibxRepresentation.getBindingFactory( this.bindingName, this.bindingClass); IUnmarshallingContext uctx = jibxBFact.createUnmarshallingContext(); return (T) uctx.unmarshalDocument( this.xmlRepresentation.getStream(), null); } return this.object; } /** * Sets the JiBX encoding. * * @param encoding * The JiBX encoding. * @deprecated Use {@link #setCharacterSet(CharacterSet)} instead. */ @Deprecated public void setEncoding(String encoding) { setCharacterSet(CharacterSet.valueOf(encoding)); } /** * Sets the wrapped Java object. * * @param object * The Java object to set. */ public void setObject(T object) { this.object = object; } /** * Marshals the document and writes the representation to a stream of * characters. * * @param writer * The writer to use when writing. * @throws IOException * If any error occurs attempting to write the stream. */ @Override public void write(Writer writer) throws IOException { try { IBindingFactory jibxBFact = JibxRepresentation.getBindingFactory( this.bindingName, this.bindingClass); IMarshallingContext mctx = jibxBFact.createMarshallingContext(); mctx.setOutput(writer); ((IMarshallable) getObject()).marshal(mctx); } catch (JiBXException e) { throw new IOException(e.getMessage()); } } } restlet-2.0.14/org.restlet.ext.jibx/src/org/restlet/ext/jibx/JibxConverter.java0000664000175000017500000001702411757206346030200 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jibx; import java.io.IOException; import java.util.List; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.JiBXException; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * A JiBX converter helper to convert from JiBX objects to JibxRepresentation * and vice versa. It only supports objects that are not bound several times * using several binding names. * * @author Thierry Boileau */ public class JibxConverter extends ConverterHelper { private static final VariantInfo VARIANT_APPLICATION_ALL_XML = new VariantInfo( MediaType.APPLICATION_ALL_XML); private static final VariantInfo VARIANT_APPLICATION_XML = new VariantInfo( MediaType.APPLICATION_XML); private static final VariantInfo VARIANT_TEXT_XML = new VariantInfo( MediaType.TEXT_XML); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_APPLICATION_ALL_XML.isCompatible(source) || VARIANT_APPLICATION_XML.isCompatible(source) || VARIANT_TEXT_XML.isCompatible(source)) { result = addObjectClass(result, JibxRepresentation.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (isJibxBoundClass(source) || JibxRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_APPLICATION_ALL_XML); result = addVariant(result, VARIANT_APPLICATION_XML); result = addVariant(result, VARIANT_TEXT_XML); } return result; } /** * Indicates if the class is bound by a Jibx factory. * * @param source * The class to test. * @return True if the class is bound by a Jibx factory. */ private boolean isJibxBoundClass(Class source) { boolean result = false; try { if ((source != null) && (BindingDirectory.getFactory(source) != null)) { result = true; } } catch (JiBXException e) { // This may be caused by the fact that the source class is bound // several times which requires the knowledge of the binding name. } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source != null && (source instanceof JibxRepresentation || isJibxBoundClass(source .getClass()))) { if (target == null) { result = 0.5F; } else if (MediaType.APPLICATION_ALL_XML.isCompatible(target .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_XML.isCompatible(target .getMediaType())) { result = 1.0F; } else if (MediaType.TEXT_XML.isCompatible(target.getMediaType())) { result = 1.0F; } else { // Allow for JiBX object to be used for JSON and other // representations result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (source != null) { if (source instanceof JibxRepresentation) { result = 1.0F; } else if (JibxRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (isJibxBoundClass(target) || JibxRepresentation.class.isAssignableFrom(source .getClass())) { result = 1.0F; } } return result; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (JibxRepresentation.class.isAssignableFrom(target)) { result = new JibxRepresentation(source, target); } else if (isJibxBoundClass(target)) { try { result = new JibxRepresentation(source, target).getObject(); } catch (JiBXException e) { throw new IOException( "Cannot convert the given representation to an object of this class using Jibx converter " + target + " due to " + e.getMessage()); } } else if (target == null) { if (source instanceof JibxRepresentation) { try { result = ((JibxRepresentation) source).getObject(); } catch (JiBXException e) { throw new IOException( "Cannot retrieve the wrapped object inside the JiBX representation due to " + e.getMessage()); } } } return target.cast(result); } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; if (isJibxBoundClass(source.getClass())) { result = new JibxRepresentation(target.getMediaType(), source); } else if (source instanceof JibxRepresentation) { result = (Representation) source; } return result; } @Override public void updatePreferences(List> preferences, Class entity) { if (isJibxBoundClass(entity) || JibxRepresentation.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_ALL_XML, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_XML, 1.0F); updatePreferences(preferences, MediaType.TEXT_XML, 1.0F); } } } restlet-2.0.14/org.restlet.ext.jibx/src/org/restlet/ext/jibx/package.html0000664000175000017500000000031511757206346027025 0ustar jamespagejamespage Integration with JiBX 1.2. JiBX is a framework for binding XML data to Java objects. @since Restlet 1.1 @see JiBX Web site restlet-2.0.14/pom.xml0000600000175000017500000001733612001473131015241 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 pom Restlet project Lightweight REST framework http://www.restlet.org 2005 http://restlet.tigris.org/svn/restlet/modules/ maven-central Central Maven repository http://repo1.maven.org/maven2/ maven2-java Java.net repository http://download.java.net/maven/2 maven1-java http://download.java.net/maven/1 legacy maven-restlet Restlet repository http://maven.restlet.org maven-db4o Db4o repository https://source.db4o.com/maven/ UTF-8 1.0.5 2.3.19 1.1.1 1.4.2 2.1 2.1.12 1.0-2 2.5 1.2.1 1.2 1.3.1 2.0.3 4.1.21 1.4 4.0.1 4.0.1 4.0.1 1.0 1.1.1 0.6 1.2.2 1.3 1.5 4.0.0 1.0 2.0 7.12.132 7.12.132 7.12.132 7.12.132 7.12.132 7.12.132 1.0 4.8.1 1.0 1.4.3 1.4.3 1.5.8 3.2.2 7.1.6.v20100715 7.1.6.v20100715 7.1.6.v20100715 7.1.6.v20100715 7.1.6.v20100715 7.1.6.v20100715 2.2 3.0.1.RELEASE 3.0.1.RELEASE 3.0.1.RELEASE 3.0.1.RELEASE 3.0.1.RELEASE 3.0.1.RELEASE 3.0.1.RELEASE 1.9.18-i 1.9.18-i 3.2.1 2.5 1.6.3 1.1 1.4 2.9.2 1.4.0 1.4.0 0.6 0.6 org.restlet.ext.ssl org.restlet.ext.odata org.restlet.ext.xml org.restlet.ext.javamail org.restlet.ext.jaxb org.restlet.ext.jaas org.restlet.ext.fileupload org.restlet.ext.xstream org.restlet.ext.gwt org.restlet.ext.simple org.restlet.ext.httpclient org.restlet.ext.jibx org.restlet.ext.jdbc org.restlet org.restlet.ext.rdf org.restlet.ext.jaxrs org.restlet.ext.atom org.restlet.example org.restlet.ext.jackson org.restlet.ext.slf4j org.restlet.ext.freemarker org.restlet.ext.netty org.restlet.ext.jetty org.restlet.ext.net org.restlet.ext.spring org.restlet.ext.crypto org.restlet.ext.grizzly org.restlet.ext.velocity org.restlet.ext.rome org.restlet.ext.wadl org.restlet.ext.json org.restlet.ext.lucene org.restlet.test Apache 2.0 license http://www.opensource.org/licenses/apache-2.0 LGPL 3.0 license http://www.opensource.org/licenses/lgpl-3.0 LGPL 2.1 license http://www.opensource.org/licenses/lgpl-2.1 CDDL 1.0 license http://www.opensource.org/licenses/cddl1 EPL 1.0 license http://www.opensource.org/licenses/eclipse-1.0 ${basedir}/src false ${basedir}/src **/* **/*.java **/package.html org.apache.maven.plugins maven-compiler-plugin 1.5 1.5 restlet-2.0.14/org.restlet.ext.javamail/0000775000175000017500000000000012001473134020561 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/pom.xml0000600000175000017500000000222112001473134022061 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.javamail Restlet Extension - JavaMail Integration with JavaMail. javax.activation activation 1.1.1 javax.mail mail 1.4.2 org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 restlet-2.0.14/org.restlet.ext.javamail/src/0000775000175000017500000000000012001473134021350 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/src/META-INF/0000775000175000017500000000000011757206450022524 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/src/META-INF/services/0000775000175000017500000000000011757206344024351 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/src/META-INF/services/org.restlet.engine.ClientHelper0000664000175000017500000000012211757206344032360 0ustar jamespagejamespageorg.restlet.ext.javamail.JavaMailClientHelper # SMTP, SMTPS, POP v3 and POPS v3 ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.javamail/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.javamail/src/META-INF/services/org.restlet.engine.converter.Converter0000664000175000017500000000005211757206344033761 0ustar jamespagejamespageorg.restlet.ext.javamail.JavaMailConverterrestlet-2.0.14/org.restlet.ext.javamail/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446024164 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.javamail/src/org/0000775000175000017500000000000011757206344022155 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/0000775000175000017500000000000011757206344023637 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/0000775000175000017500000000000011757206344024437 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/0000775000175000017500000000000011757206344026223 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/MailResolver.java0000664000175000017500000001102111757206344031465 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.javamail; import java.util.HashMap; import java.util.Map; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.util.Resolver; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Basic resolver that exposes several data from a given mail. Here is a list of * the keys available from this resolver and their corresponding value.
* * * * * * * * * * * * * * * * * * * * * *
KeyValue
mailIdMail identifier *
fromSender *
recipientsRecipients (comma separated string) *
subjectSubject *
messageMail text part *
*/ public class MailResolver extends Resolver { /** Mail identifier. */ private final String identifier; /** The variables to use when formatting. */ private Map map; /** * Constructor. * * @param identifier * Identifier of the mail. * */ public MailResolver(String identifier) { this(identifier, null); } /** * Constructor. * * @param identifier * Identifier of the mail. * @param mail * The mail. * */ public MailResolver(String identifier, Representation mail) { this.identifier = identifier; if (mail != null) { this.map = new HashMap(); DomRepresentation rep = null; if (mail instanceof DomRepresentation) { rep = (DomRepresentation) mail; } else { rep = new DomRepresentation(mail); } Node node = rep.getNode("/email/head/from/text()"); if (node != null) { add("from", node.getNodeValue()); } final NodeList nodes = rep.getNodes("/email/head/to/text()"); if ((nodes != null) && (nodes.getLength() > 0)) { final StringBuilder builder = new StringBuilder(nodes.item(0) .getNodeValue()); for (int i = 1; i < nodes.getLength(); i++) { builder.append(", ").append(nodes.item(i).getNodeValue()); } add("recipients", builder.toString()); } node = rep.getNode("/email/head/subject/text()"); if (node != null) { add("subject", node.getNodeValue()); } node = rep.getNode("/email/body/text()"); if (node != null) { add("message", node.getNodeValue()); } } } /** * Add a value. * * @param key * The key of the value. * @param value * The value. */ public void add(String key, String value) { this.map.put(key, value); } @Override public String resolve(String name) { String result = null; if ("mailId".equals(name)) { result = this.identifier; } else { final Object value = this.map.get(name); result = (value == null) ? null : value.toString(); } return result; } } restlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/JavaMailClientHelper.java0000664000175000017500000004642311757206344033062 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.javamail; import java.io.IOException; import java.util.Properties; import java.util.logging.Level; import javax.mail.FetchProfile; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.UIDFolder; import javax.mail.internet.AddressException; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.ClientHelper; import org.restlet.representation.Representation; import org.w3c.dom.DOMException; import com.sun.mail.pop3.POP3Folder; /** * Client connector to a mail server. This connector supports the SMTP, SMTP * with STARTTLS and SMTPS protocols to send emails, POP v3 and POPS v3 to * retrieved emails from a mail box.
*
* To send an email, send a POST request with a resource reference on a SMTP or * SMTPS URI and use an XML email as the entity. A SMTP URI has the following * syntax: smtp://host[:port]
*
* Use the * {@link Request#setChallengeResponse(org.restlet.data.ChallengeResponse)} * method to set the identified/login and secret/password. You will also need to * specify the {@link ChallengeScheme#SMTP_PLAIN} challenge scheme.
*
* Sample XML email:
* *
 * <?xml version="1.0" encoding="ISO-8859-1" ?>
 *  <email>
 *  <head>
 *  <subject>Account activation</subject>
 *  <from>support@restlet.org</from>
 *  <to>user@domain.com</to>
 *  <cc>log@restlet.org</cc>
 *  </head>
 *  <body><![CDATA[Your account was sucessfully created!]]></body>
 *  </email>
 * 
* * To receive the list of emails, send a GET request to a resource reference on * a POP or POPS URI, leaving the reference path empty. A POP URI has the * following syntax: pop://host[:port]
*
* Use the * {@link Request#setChallengeResponse(org.restlet.data.ChallengeResponse)} * method to set the identified/login and secret/password. You will also need to * specify the {@link ChallengeScheme#POP_BASIC} or the * {@link ChallengeScheme#POP_DIGEST} challenge scheme.
*
* Sample XML list of emails:
* *
 * <?xml version="1.0" encoding="ISO-8859-1" ?>
 * <emails>
 *    <email href="/1234"/>
 *    <email href="/5678"/>
 *    <email href="/9012"/>
 *    <email href="/3456"/>
 * </emails>
 * 
* * To retrieve an individual email, just add the href attribute at the end of * the POP URI, such as: pop://host/1234
*
* Here is the list of parameters that are supported. They should be set in the * Client's context before it is started: * * * * * * * * * * * * * * * * * * * * * * * * * *
Parameter nameValue typeDefault valueDescription
startTlsbooleanfalseIf true, the SMTP connector will attempt to start a TLS tunnel, right * after the SMTP connection is established.
debugbooleanfalseIf true, the connector will generate JavaMail debug messages.
representationMessageClassStringnullIf not null, represents the name of a class that extends the JavaMail * "javax.mail.Message" class. This class is able to generate a Message from an * XML representation and a JavaMail Session. The constructor must accept a * {@link Representation} and a JavaMail Session objects as parameters in this * order.
* * @author Jerome Louvel */ public class JavaMailClientHelper extends ClientHelper { /** POP protocol. */ public static final Protocol POP = new Protocol("pop", "POP", "Post Office Protocol", 110); /** Basic POP scheme. Based on the USER/PASS commands. */ public static final ChallengeScheme POP_BASIC = new ChallengeScheme( "POP_BASIC", "Basic", "Basic POP authentication (USER/PASS commands)"); /** Digest POP scheme. Based on the APOP command. */ public static final ChallengeScheme POP_DIGEST = new ChallengeScheme( "POP_DIGEST", "Digest", "Digest POP authentication (APOP command)"); /** POPS protocol (via SSL/TLS socket).. */ public static final Protocol POPS = new Protocol("pops", "POPS", "Post Office Protocol (Secure)", 995); /** * Constructor. * * @param client * The client to help. */ public JavaMailClientHelper(Client client) { super(client); getProtocols().add(Protocol.SMTP); getProtocols().add(Protocol.SMTPS); getProtocols().add(POP); getProtocols().add(POPS); } /** * Creates a JavaMail message by parsing an XML representation. * * @param xmlMessage * The XML message to parse. * @param session * The current JavaMail session. * @return The created JavaMail message. * @throws IOException * @throws AddressException * @throws MessagingException */ @SuppressWarnings("unchecked") protected Message createMessage(Representation xmlMessage, Session session) throws IOException, AddressException, MessagingException { final String representationMessageClassName = getRepresentationMessageClass(); if (representationMessageClassName == null) { return new RepresentationMessage(xmlMessage, session); } try { final Class representationMessageClass = (Class) Class .forName(representationMessageClassName); return representationMessageClass.getConstructor( Representation.class, Session.class).newInstance( xmlMessage, session); } catch (Exception e) { getLogger().log( Level.SEVERE, "Unable to create a new instance of " + representationMessageClassName, e); return new RepresentationMessage(xmlMessage, session); } } /** * Creates an XML representation based on a JavaMail message. * * @param message * The JavaMail message to format. * @return The XML representation. * @throws DOMException * @throws IOException * @throws MessagingException */ protected Representation createRepresentation(Message message) throws DOMException, IOException, MessagingException { return new MessageRepresentation(message); } /** * Creates an XML representation based on a list of JavaMail messages. * * @param messages * The list of JavaMail messages to format. * @return The XML representation. * @throws IOException * @throws MessagingException */ protected Representation createRepresentation(Message[] messages, POP3Folder inbox) throws IOException, MessagingException { return new MessagesRepresentation(messages, inbox); } /** * Returns the request login. * * @param request * The high-level request. * @return The login. */ private String getLogin(Request request) { if ((request != null) && (request.getChallengeResponse() != null)) { return request.getChallengeResponse().getIdentifier(); } return null; } /** * Returns the request password. * * @param request * The high-level request. * @return The password. */ private String getPassword(Request request) { if ((request != null) && (request.getChallengeResponse() != null)) { return new String(request.getChallengeResponse().getSecret()); } return null; } /** * Returns the full name of the class used for generating JavaMail Message * instances from an XML representation and a JavaMail Session. * * @return The full name of the class used for generating JavaMail Message * instances from an XML representation and a JavaMail Session. */ public String getRepresentationMessageClass() { return getHelpedParameters() .getFirstValue("representationMessageClass"); } @Override public void handle(Request request, Response response) { try { final Protocol protocol = request.getProtocol(); if (Protocol.SMTP.equals(protocol) || Protocol.SMTPS.equals(protocol)) { handleSmtp(request, response); } else if (POP.equals(protocol) || POPS.equals(protocol)) { handlePop(request, response); } } catch (IOException e) { getLogger().log(Level.WARNING, "JavaMail client error", e); response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, e.getMessage()); } catch (NoSuchProviderException e) { getLogger().log(Level.WARNING, "JavaMail client error", e); response.setStatus(Status.SERVER_ERROR_INTERNAL, e.getMessage()); } catch (AddressException e) { getLogger().log(Level.WARNING, "JavaMail client error", e); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage()); } catch (MessagingException e) { getLogger().log(Level.WARNING, "JavaMail client error", e); response.setStatus(Status.SERVER_ERROR_INTERNAL, e.getMessage()); } } /** * Handles a POP or POPS request. * * @param request * The request to handle. * @param response * The response to update. * @throws IOException * @throws MessagingException * @throws IOException */ private void handlePop(Request request, Response response) throws MessagingException, IOException { // Parse the POP URI final String popHost = request.getResourceRef().getHostDomain(); int popPort = request.getResourceRef().getHostPort(); final String path = request.getResourceRef().getPath(); if (popPort == -1) { // No port specified, the default one should be used popPort = request.getProtocol().getDefaultPort(); } if ((popHost == null) || (popHost.equals(""))) { throw new IllegalArgumentException("Invalid POP host specified"); } // Check if authentication required final boolean authenticate = ((getLogin(request) != null) && (getPassword(request) != null)); final boolean apop = authenticate && (POP_DIGEST.equals(request.getChallengeResponse() .getScheme())); String transport = null; if (POP.equals(request.getProtocol())) { transport = "pop3"; } else if (POPS.equals(request.getProtocol())) { transport = "pop3s"; } final Properties props = System.getProperties(); props.put("mail." + transport + ".host", popHost); props.put("mail." + transport + ".port", Integer.toString(popPort)); props.put("mail." + transport + ".apop.enable", Boolean.toString(apop)); // States whether or not to update the folder by removing deleted // messages. boolean updateFolder = false; final Session session = Session.getDefaultInstance(props); session.setDebug(isDebug()); final Store store = session.getStore(transport); store.connect(getLogin(request), getPassword(request)); final POP3Folder inbox = (POP3Folder) store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); final FetchProfile profile = new FetchProfile(); profile.add(UIDFolder.FetchProfileItem.UID); final Message[] messages = inbox.getMessages(); inbox.fetch(messages, profile); if ((path == null) || path.equals("") || path.equals("/")) { if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) { // Set the result document response.setEntity(createRepresentation(messages, inbox)); } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); } } else if (path.startsWith("/")) { // Retrieve the specified message final String mailUid = path.substring(1); Message message = null; for (int i = 0; (message == null) && (i < messages.length); i++) { final String uid = inbox.getUID(messages[i]); if (mailUid.equals(uid)) { message = messages[i]; } } if (message == null) { // Message not found response.setStatus(Status.CLIENT_ERROR_NOT_FOUND, "No message matches the given UID: " + mailUid); } else { if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) { // Set the result document response.setEntity(createRepresentation(message)); } else if (Method.DELETE.equals(request.getMethod())) { message.setFlag(Flags.Flag.DELETED, true); updateFolder = true; } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); response.getAllowedMethods().add(Method.DELETE); } } } inbox.close(updateFolder); store.close(); } /** * Handles a SMTP or SMTPS request. * * @param request * The request to handle. * @param response * The response to update. * @throws IOException * @throws MessagingException */ private void handleSmtp(Request request, Response response) throws IOException, MessagingException { if (!Method.POST.equals(request.getMethod())) { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.POST); } else { // Parse the SMTP URI final String smtpHost = request.getResourceRef().getHostDomain(); int smtpPort = request.getResourceRef().getHostPort(); if (smtpPort == -1) { // No port specified, the default one should be used smtpPort = request.getProtocol().getDefaultPort(); } if ((smtpHost == null) || (smtpHost.equals(""))) { throw new IllegalArgumentException( "Invalid SMTP host specified"); } // Check if authentication required final boolean authenticate = ((getLogin(request) != null) && (getPassword(request) != null)); String transport = null; if (Protocol.SMTP.equals(request.getProtocol())) { transport = "smtp"; } else if (Protocol.SMTPS.equals(request.getProtocol())) { transport = "smtps"; } final Properties props = System.getProperties(); props.put("mail." + transport + ".host", smtpHost); props .put("mail." + transport + ".port", Integer .toString(smtpPort)); props.put("mail." + transport + ".auth", Boolean.toString( authenticate).toLowerCase()); props.put("mail." + transport + ".starttls.enable", Boolean .toString(isStartTls())); // Open the JavaMail session final Session session = Session.getDefaultInstance(props); session.setDebug(isDebug()); final Transport tr = session.getTransport(transport); if (tr != null) { // Check if authentication is needed if (authenticate) { tr.connect(smtpHost, getLogin(request), getPassword(request)); } else { tr.connect(); } // Actually send the message if (tr.isConnected()) { getLogger() .info( "JavaMail client connection successfully established. Attempting to send the message"); // Create the JavaMail message final Message msg = createMessage(request.getEntity(), session); // Send the message tr.sendMessage(msg, msg.getAllRecipients()); tr.close(); getLogger().info( "JavaMail client successfully sent the message."); } } } } /** * Indicates if the connector should generate JavaMail debug messages. * * @return True the connector should generate JavaMail debug messages. */ public boolean isDebug() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "debug", "false")); } /** * Indicates if the SMTP protocol should attempt to start a TLS tunnel. * * @return True if the SMTP protocol should attempt to start a TLS tunnel. */ public boolean isStartTls() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "startTls", "false")); } } restlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/package.html0000664000175000017500000000051711757206344030507 0ustar jamespagejamespage Integration with JavaMail 1.4 (POP3 and SMTP clients). JavaMail provides a platform-independent and protocol-independent framework to build mail and messaging applications. @since Restlet 1.0 @see JavaMail product page restlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/JavaMailConverter.java0000664000175000017500000000644411757206344032452 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.javamail; import java.io.IOException; import java.util.List; import javax.mail.Message; import javax.mail.MessagingException; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; import org.w3c.dom.DOMException; /** * A JavaMail converter helper to convert from Message objects to * MessageRepresentation. * * @author Thierry Boileau */ public class JavaMailConverter extends ConverterHelper { @Override public List> getObjectClasses(Variant source) { return null; } @Override public List getVariants(Class source) { return null; } @Override public float score(Representation source, Class target, UniformResource resource) { return -1.0f; } @Override public float score(Object source, Variant target, UniformResource resource) { if (source instanceof Message) { return 1.0f; } return -1.0f; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { return null; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { if (source instanceof Message) { try { return new MessageRepresentation((Message) source); } catch (DOMException e) { throw new IOException( "Cannot convert the source message as a MessageRepresentation due to:" + e.getMessage()); } catch (MessagingException e) { throw new IOException( "Cannot convert the source message as a MessageRepresentation due to:" + e.getMessage()); } } return null; } } restlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/MessagesRepresentation.java0000664000175000017500000000476611757206344033575 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.javamail; import java.io.IOException; import javax.mail.Message; import javax.mail.MessagingException; import org.restlet.data.MediaType; import org.restlet.ext.xml.DomRepresentation; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.sun.mail.pop3.POP3Folder; /** * XML representation of a list of JavaMail messages. * * @author Jerome Louvel */ public class MessagesRepresentation extends DomRepresentation { /** * Constructor. * * @param messages * The list of JavaMail messages to format. * @throws IOException * @throws MessagingException */ public MessagesRepresentation(Message[] messages, POP3Folder inbox) throws IOException, MessagingException { super(MediaType.APPLICATION_XML); // Format the list final Document dom = getDocument(); final Element emails = dom.createElement("emails"); dom.appendChild(emails); // Retrieve the list of messages Element email; for (final Message message : messages) { final String uid = inbox.getUID(message); email = dom.createElement("email"); email.setAttribute("href", "/" + uid); emails.appendChild(email); } } } restlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/MessageRepresentation.java0000664000175000017500000001574211757206344033406 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.javamail; import java.io.IOException; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.MimeBodyPart; import org.restlet.data.MediaType; import org.restlet.engine.http.header.ContentType; import org.restlet.engine.util.DateUtils; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.w3c.dom.CDATASection; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * XML representation of a JavaMail message. * * @author Jerome Louvel */ public class MessageRepresentation extends DomRepresentation { /** * Constructor. * * @param message * The JavaMail message to format. * @throws IOException * @throws MessagingException * @throws DOMException */ public MessageRepresentation(Message message) throws IOException, DOMException, MessagingException { super(MediaType.APPLICATION_XML); final Document dom = getDocument(); final Element email = dom.createElement("email"); dom.appendChild(email); // Add the email header final Element head = dom.createElement("head"); email.appendChild(head); if (message.getSubject() != null) { final Element subject = dom.createElement("subject"); subject.setTextContent(message.getSubject()); head.appendChild(subject); } final Address[] froms = message.getFrom(); if (froms != null) { for (final Address fromAddress : froms) { final Element from = dom.createElement("from"); from.setTextContent(fromAddress.toString()); head.appendChild(from); } } final Address[] tos = message.getRecipients(Message.RecipientType.TO); if (tos != null) { for (final Address toAddress : tos) { final Element to = dom.createElement("to"); to.setTextContent(toAddress.toString()); head.appendChild(to); } } final Address[] ccs = message.getRecipients(Message.RecipientType.CC); if (ccs != null) { for (final Address ccAddress : ccs) { final Element cc = dom.createElement("cc"); cc.setTextContent(ccAddress.toString()); head.appendChild(cc); } } final Address[] bccs = message.getRecipients(Message.RecipientType.BCC); if (bccs != null) { for (final Address bccAddress : bccs) { final Element bcc = dom.createElement("bcc"); bcc.setTextContent(bccAddress.toString()); head.appendChild(bcc); } } if (message.getReceivedDate() != null) { final Element received = dom.createElement("received"); received.setTextContent(DateUtils.format(message.getReceivedDate(), DateUtils.FORMAT_RFC_1123.get(0))); head.appendChild(received); } if (message.getSentDate() != null) { final Element sent = dom.createElement("sent"); sent.setTextContent(DateUtils.format(message.getSentDate(), DateUtils.FORMAT_RFC_1123.get(0))); head.appendChild(sent); } email.appendChild(head); // Complete the XML representation with the text part of the message Representation content = null; if (message.getContent() instanceof Multipart) { // Look for the text part of the mail. final Multipart multipart = (Multipart) message.getContent(); for (int i = 0, n = multipart.getCount(); i < n; i++) { final Part part = multipart.getBodyPart(i); final String disposition = part.getDisposition(); if (disposition != null) { if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) { // create a representation from part.getInputStream() } } else { // Check if plain text final MimeBodyPart mimeBodyPart = (MimeBodyPart) part; final ContentType contentType = new ContentType( mimeBodyPart.getContentType()); if (MediaType.TEXT_PLAIN.equals(contentType.getMediaType(), true)) { content = new InputRepresentation(mimeBodyPart .getInputStream(), MediaType.TEXT_PLAIN); break; } // TODO Special non-attachment cases here of // image/gif, text/html, ... } } } else { // Add the email body if (message.getContentType() != null) { final ContentType contentType = new ContentType(message .getContentType()); if (MediaType.TEXT_PLAIN.equals(contentType.getMediaType(), true)) { content = new InputRepresentation(message.getInputStream(), MediaType.TEXT_PLAIN); } } } if (content != null) { final Element body = dom.createElement("body"); final CDATASection bodyContent = dom.createCDATASection(content .getText()); body.appendChild(bodyContent); email.appendChild(body); } } } restlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/RepresentationMessage.java0000664000175000017500000001076111757206344033402 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.javamail; import java.io.IOException; import java.util.Date; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * JavaMail MIME message based on an XML representation. For the XML format, see * the {@link JavaMailClientHelper} class. * * @author Jerome Louvel */ public class RepresentationMessage extends MimeMessage { /** * Creates a JavaMail message by parsing an XML representation. * * @param xmlMessage * The XML message to parse. * @param session * The current JavaMail session. * @throws IOException * @throws AddressException * @throws MessagingException */ public RepresentationMessage(Representation xmlMessage, Session session) throws IOException, AddressException, MessagingException { super(session); DomRepresentation dom = new DomRepresentation(xmlMessage); Document email = dom.getDocument(); Element root = (Element) email.getElementsByTagName("email").item(0); Element header = (Element) root.getElementsByTagName("head").item(0); String subject = header.getElementsByTagName("subject").item(0) .getTextContent(); String from = header.getElementsByTagName("from").item(0) .getTextContent(); NodeList toList = header.getElementsByTagName("to"); String[] to = new String[toList.getLength()]; for (int i = 0; i < toList.getLength(); i++) { to[i] = toList.item(i).getTextContent(); } NodeList ccList = header.getElementsByTagName("cc"); String[] cc = new String[ccList.getLength()]; for (int i = 0; i < ccList.getLength(); i++) { cc[i] = ccList.item(i).getTextContent(); } NodeList bccList = header.getElementsByTagName("bcc"); String[] bcc = new String[bccList.getLength()]; for (int i = 0; i < bccList.getLength(); i++) { bcc[i] = bccList.item(i).getTextContent(); } String text = root.getElementsByTagName("body").item(0) .getTextContent(); // Set the FROM and TO fields setFrom(new InternetAddress(from)); for (String element : to) { addRecipient(Message.RecipientType.TO, new InternetAddress(element)); } for (String element : cc) { addRecipient(Message.RecipientType.CC, new InternetAddress(element)); } for (final String element : bcc) { addRecipient(Message.RecipientType.BCC, new InternetAddress(element)); } // Set the subject and content text setSubject(subject); setText(text); setSentDate(new Date()); saveChanges(); } /** * Constructor. * * @param session * The current JavaMail session. */ public RepresentationMessage(Session session) { super(session); } } restlet-2.0.14/org.restlet.ext.javamail/src/org/restlet/ext/javamail/TriggerResource.java0000664000175000017500000004701711757206344032212 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.javamail; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import org.restlet.routing.Template; import org.restlet.util.Resolver; import org.w3c.dom.Node; /** * Resource that handles requests to target resources according to parameters * located in mails. * * @author Jerome Louvel */ public class TriggerResource extends ServerResource { public static final String ATTRIBUTE_MAILBOX_CHALLENGE_SCHEME = "org.restlet.ext.javamail.mailbox.authentication.scheme"; public static final String ATTRIBUTE_MAILBOX_LOGIN = "org.restlet.ext.javamail.mailbox.login"; public static final String ATTRIBUTE_MAILBOX_PASSWORD = "org.restlet.ext.javamail.mailbox.password"; public static final String ATTRIBUTE_MAILBOX_URI = "org.restlet.ext.javamail.mailbox.uri"; private ChallengeScheme mailboxChallengeScheme; private String mailboxLogin; private String mailboxPassword; /** The mailbox URI template. */ private String mailboxUri; /** * The mail URI template, optionally relative to the mailbox URI. The * template should contain a variable "{mailId}" for the insertion of the * mail identifier in the proper location. The default value is "/{mailId}". */ private String mailUriTemplate; /** Resolver that resolves a name into a value. */ private MailResolver resolver; /** * Indicates if the target entity should be provided to the target resource. */ private boolean targetEntityEnabled; /** The method to invoke on the target resource. */ private Method targetMethod; /** The target URI template. */ private String targetUri; /** * Handles POST requests. It retrieves a list of mails and generate requests * to target resources. * * @param entity * The representation of the mails list. * @throws ResourceException */ @Post public void acceptMails(Representation entity) throws ResourceException { // 1 - Get list of identifiers for the mails in the inbox final List mailIdentifiers = getMailIdentifiers(); // 2 - Process the list of mails final List mailsSuccessful = new ArrayList(); final Map mailsUnsuccessful = new HashMap(); Representation mail; for (final String mailIdentifier : mailIdentifiers) { try { mail = getMail(mailIdentifier); if (mail != null) { this.resolver = getResolver(mailIdentifier, mail); callTarget(this.resolver); deleteMail(mailIdentifier); mailsSuccessful.add(mailIdentifier); } } catch (ResourceException e) { mailsUnsuccessful.put(mailIdentifier, e.getMessage()); } } // 3 - Set response for timer client getResponse().setEntity( getResponseRepresentation(mailsSuccessful, mailsUnsuccessful)); getResponse().setStatus( getResponseStatus(mailsSuccessful, mailsUnsuccessful)); } /** * Requests the target resource. * * @param resolver * The data model that provides parameters value. * @throws ResourceException */ protected void callTarget(Resolver resolver) throws ResourceException { // A - Build the request for the target resource final Method method = getTargetMethod(resolver); final Reference targetRef = getTargetRef(resolver); final Request request = new Request(method, targetRef); final ChallengeResponse challengeResponse = getTargetChallengeResponse(resolver); if (challengeResponse != null) { request.setChallengeResponse(challengeResponse); } if (isTargetEntityEnabled()) { request.setEntity(getTargetEntity(resolver)); } // B - Call the target resource final Response response = getContext().getClientDispatcher().handle( request); if (!response.getStatus().isSuccess()) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Call to the target resource didn't succeed"); } } /** * Deletes a mail after it has been processed. * * @param mailIdentifier * The identifier of the mail * @throws ResourceException */ protected void deleteMail(String mailIdentifier) throws ResourceException { // A - Build the mail URI Reference mailRef = getMailRef(mailIdentifier); if (mailRef.isRelative()) { mailRef.setBaseRef(getMailboxUri()); mailRef = mailRef.getTargetRef(); } // B - Delete the mail final Request request = new Request(Method.DELETE, mailRef); if (getMailboxChallengeScheme() != null) { final ChallengeResponse challengeResponse = new ChallengeResponse( getMailboxChallengeScheme(), getMailboxLogin(), getMailboxPassword()); request.setChallengeResponse(challengeResponse); } final Response response = getContext().getClientDispatcher().handle( request); if (response.getStatus().isError()) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Unable to delete the mail from the mailbox"); } } @Override protected void doInit() throws ResourceException { this.mailboxChallengeScheme = null; this.mailboxLogin = null; this.mailboxPassword = null; this.mailboxUri = null; this.mailUriTemplate = "/{mailId}"; this.resolver = null; } /** * Get the mail representation according to its identifier. * * @param identifier * the mail identifier. * @throws ResourceException */ protected Representation getMail(String identifier) throws ResourceException { // A - Build the mail URI final Reference mailRef = getMailRef(identifier); // B - Get the mail final Request request = new Request(Method.GET, mailRef); if (getMailboxChallengeScheme() != null) { final ChallengeResponse challengeResponse = new ChallengeResponse( getMailboxChallengeScheme(), getMailboxLogin(), getMailboxPassword()); request.setChallengeResponse(challengeResponse); } final Response response = getContext().getClientDispatcher().handle( request); if (!response.getStatus().isSuccess()) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Unable to get the mail from the mailbox"); } return new DomRepresentation(response.getEntity()); } /** * Returns the scheme of the mailbox challenge. * * @return The scheme of the mailbox challenge. */ public ChallengeScheme getMailboxChallengeScheme() { if (this.mailboxChallengeScheme == null) { this.mailboxChallengeScheme = (ChallengeScheme) getContext() .getAttributes().get(ATTRIBUTE_MAILBOX_CHALLENGE_SCHEME); } return this.mailboxChallengeScheme; } /** * Returns the login for the mailbox. * * @return The login for the mailbox. */ public String getMailboxLogin() { if (this.mailboxLogin == null) { this.mailboxLogin = (String) getContext().getAttributes().get( ATTRIBUTE_MAILBOX_LOGIN); } return this.mailboxLogin; } /** * Returns the password for the mailbox. * * @return The password for the mailbox. */ public String getMailboxPassword() { if (this.mailboxPassword == null) { this.mailboxPassword = (String) getContext().getAttributes().get( ATTRIBUTE_MAILBOX_PASSWORD); } return this.mailboxPassword; } /** * Returns the URI of the mailbox. * * @return The URI of the mailbox. */ public String getMailboxUri() { if (this.mailboxUri == null) { this.mailboxUri = (String) getContext().getAttributes().get( ATTRIBUTE_MAILBOX_URI); } return this.mailboxUri; } /** * Returns the list of identifiers for the mails in the inbox * * @return The list of identifiers. * @throws ResourceException */ protected List getMailIdentifiers() throws ResourceException { final List result = new ArrayList(); // 1 - Get to mailbox content final Request request = new Request(Method.GET, getMailboxUri()); if (getMailboxChallengeScheme() != null) { final ChallengeResponse challengeResponse = new ChallengeResponse( getMailboxChallengeScheme(), getMailboxLogin(), getMailboxPassword()); request.setChallengeResponse(challengeResponse); } final Response response = getContext().getClientDispatcher().handle( request); if (!response.getStatus().isSuccess()) { throw new ResourceException(response.getStatus(), "Cannot get the mail iddentifiers."); } // 2 - Parse the list of mails if (response.isEntityAvailable()) { final DomRepresentation rep = new DomRepresentation(response .getEntity()); for (final Node node : rep.getNodes("/emails/email/@href")) { final String href = node.getNodeValue(); if (href.startsWith("/")) { result.add(href.substring(1)); } else { result.add(href); } } } return result; } /** * Returns the reference of a mail according to its identifier. * * @param identifier * The identifier of a mail. * @return The URI of the mail. * @throws ResourceException */ protected Reference getMailRef(String identifier) throws ResourceException { final Template mailTemplate = new Template(getMailUriTemplate()); Reference result = new Reference(mailTemplate.format(new MailResolver( identifier))); if (result.isRelative()) { result.setBaseRef(getMailboxUri()); result = result.getTargetRef(); } return result; } /** * Returns the template of the mail's URI. * * @return the template of the mail's URI. */ public String getMailUriTemplate() { return this.mailUriTemplate; } /** * Returns the resolver based on a mail. * * @return The resolver. */ public MailResolver getResolver() { return this.resolver; } /** * Returns a new resolver based on a mail. * * @param mailIdentifier * Identifier of the mail. * @param email * The mail. * @return A resolver. */ protected MailResolver getResolver(String mailIdentifier, Representation email) { return new MailResolver(mailIdentifier, email); } /** * Returns the response's representation according to the list of * successfull and unsuccessfull mails. * * @param mailsSuccessful * The list of successfull mails. * @param mailsUnsuccessful * The list of successfull mails and related error message. * @return The response's representation. */ protected Representation getResponseRepresentation( List mailsSuccessful, Map mailsUnsuccessful) { final Representation representation = null; return representation; } /** * Returns the response's status according to the list of successfull and * unsuccessfull mails. * * @param mailsSuccessful * The list of successfull mails. * @param mailsUnsuccessful * The list of successfull mails and related error message. * @return The response's status. */ protected Status getResponseStatus(List mailsSuccessful, Map mailsUnsuccessful) { Status status = null; if (mailsUnsuccessful.size() > 0) { status = Status.CLIENT_ERROR_NOT_FOUND; } else { status = Status.SUCCESS_OK; } return status; } /** * Returns the authentication data sent by client to the target according to * the a list of properties. By default, this method returns checks the * variable "challengeScheme", "login", "password" in order to build the * ChallengeResponse object. It can be overriden. * * @param resolver * The resolver. * @return The target challengeResponse object. * @throws ResourceException */ protected ChallengeResponse getTargetChallengeResponse( Resolver resolver) throws ResourceException { final ChallengeScheme challengeScheme = ChallengeScheme .valueOf(resolver.resolve("challengeScheme")); final String login = resolver.resolve("login"); final String password = resolver.resolve("password"); ChallengeResponse result = null; if ((challengeScheme != null) && (login != null) && (password != null)) { result = new ChallengeResponse(challengeScheme, login, password); } return result; } /** * Returns the entity sent to the target. By default, it sends the mail * message. * * @param resolver * the resolver. * @return The entity to be sent to the target. */ protected Representation getTargetEntity(Resolver resolver) { return new StringRepresentation(resolver.resolve("message")); } /** * Returns the default target method. * * @return The default target method. */ public Method getTargetMethod() { return this.targetMethod; } /** * Returns the target method according to a list of properties. * * @param resolver * The resolver. * @return The target method. */ protected Method getTargetMethod(Resolver resolver) { Method method = Method.valueOf(resolver.resolve("method")); if (method == null) { method = getTargetMethod(); } return method; } /** * Returns the reference of the target according to the a list of * properties. * * @param resolver * The resolver. * @return The target reference. * @throws ResourceException */ protected Reference getTargetRef(Resolver resolver) throws ResourceException { final Template targetTemplate = new Template(getTargetUri()); Reference result = new Reference(targetTemplate.format(resolver)); if (result.isRelative()) { result.setBaseRef(getMailboxUri()); result = result.getTargetRef(); } return result; } /** * Returns the target URI template. * * @return The template that represents a target URI. */ public String getTargetUri() { return this.targetUri; } /** * Indicate whether or not the target supports entity in the request. * * @return True if the target supports entity in the request, false, * otherwise. */ public boolean isTargetEntityEnabled() { return this.targetEntityEnabled; } /** * Sets the scheme of the mailbox challenge. * * @param mailboxChallengeScheme * The scheme of the mailbox challenge. */ public void setMailboxChallengeScheme(ChallengeScheme mailboxChallengeScheme) { this.mailboxChallengeScheme = mailboxChallengeScheme; } /** * Sets the login for the mailbox access. * * @param mailboxLogin * The login for the mailbox access. */ public void setMailboxLogin(String mailboxLogin) { this.mailboxLogin = mailboxLogin; } /** * Sets the password for the mailbox access. * * @param mailboxPassword * The password for the mailbox access. */ public void setMailboxPassword(String mailboxPassword) { this.mailboxPassword = mailboxPassword; } /** * Sets the URI of the mailbox. * * @param mailboxUri * the URI of the mailbox. */ public void setMailboxUri(String mailboxUri) { this.mailboxUri = mailboxUri; } /** * Sets the URI template for the target. * * @param mailUriTemplate * the URI template for the target. */ public void setMailUriTemplate(String mailUriTemplate) { this.mailUriTemplate = mailUriTemplate; } /** * Indicate whether or not the target supports entity in the request. * * @param targetEntityEnabled * True if the target supports entity in the request, false, * otherwise. */ public void setTargetEntityEnabled(boolean targetEntityEnabled) { this.targetEntityEnabled = targetEntityEnabled; } /** * Sets the default target method. * * @param targetMethod * The default target method. */ public void setTargetMethod(Method targetMethod) { this.targetMethod = targetMethod; } /** * Sets the target URI template. * * @param targetUri * The target URI template. */ public void setTargetUri(String targetUri) { this.targetUri = targetUri; } } restlet-2.0.14/org.restlet.ext.net/0000775000175000017500000000000012001473201017556 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/pom.xml0000600000175000017500000000137112001473201021063 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.net Restlet Extension - Net Integration with java.net.HttpURLConnection class. org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.net/src/0000775000175000017500000000000012001473200020344 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/META-INF/0000775000175000017500000000000011757206452021530 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/META-INF/services/0000775000175000017500000000000011757206352023352 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/META-INF/services/org.restlet.engine.ClientHelper0000664000175000017500000000014311757206352031364 0ustar jamespagejamespageorg.restlet.ext.net.HttpClientHelper # HTTP, HTTPS org.restlet.ext.net.FtpClientHelper # FTP restlet-2.0.14/org.restlet.ext.net/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023161 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.net/src/org/0000775000175000017500000000000011757206352021156 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/org/restlet/0000775000175000017500000000000011757206352022640 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/0000775000175000017500000000000011757206352023440 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/0000775000175000017500000000000011757206352024226 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/HttpClientHelper.java0000664000175000017500000001706011757206352030313 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.net; import java.io.IOException; import java.net.HttpURLConnection; import java.util.logging.Level; import javax.net.ssl.HostnameVerifier; import org.restlet.Client; import org.restlet.Request; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.engine.http.ClientCall; import org.restlet.ext.net.internal.HttpUrlConnectionCall; /** * HTTP client connector using the {@link HttpUrlConnectionCall}. Here is the * list of parameters that are supported. They should be set in the Client's * context before it is started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Parameter nameValue typeDefault valueDescription
allowUserInteractionbooleanfalseIf true, this URL is being examined in a context in which it makes sense * to allow user interactions such as popping up an authentication dialog.
chunkLengthint0 (uses HttpURLConnection's default)The chunk-length when using chunked encoding streaming mode for response * entities. A value of -1 means chunked encoding is disabled for response * entities.
followRedirectsbooleanfalseIf true, the protocol will automatically follow redirects. If false, the * protocol will not automatically follow redirects.
readTimeoutint0Sets the read timeout to a specified timeout, in milliseconds. A timeout * of zero is interpreted as an infinite timeout.
useCachesbooleanfalseIf true, the protocol is allowed to use caching whenever it can.
*
* It is also possible to specify a hostname verifier for HTTPS connections. See * the {@link #getHostnameVerifier()} method for details.
*
* Note that by default, the {@link HttpURLConnection} class as implemented by * Sun will retry a request if an IO exception is caught, for example due to a * connection reset by the server. This can be annoying, especially because the * HTTP semantics of non idempotent methods like POST can be broken, but also * because the new request won't include an entity. There is one way to disable * this behavior for POST requests only by setting the system property * "sun.net.http.retryPost" to "false". * * @see Client#getConnectTimeout() * @see Networking * Features * @author Jerome Louvel */ public class HttpClientHelper extends org.restlet.engine.http.HttpClientHelper { /** * Constructor. * * @param client * The client to help. */ public HttpClientHelper(Client client) { super(client); getProtocols().add(Protocol.HTTP); getProtocols().add(Protocol.HTTPS); } /** * Creates a low-level HTTP client call from a high-level uniform call. * * @param request * The high-level request. * @return A low-level HTTP client call. */ @Override public ClientCall create(Request request) { ClientCall result = null; try { Reference targetRef = request.getResourceRef().getBaseRef() == null ? request .getResourceRef() : request.getResourceRef().getTargetRef(); result = new HttpUrlConnectionCall(this, request.getMethod() .toString(), targetRef.toString(), request .isEntityAvailable()); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to create the HTTP client call", ioe); } return result; } /** * Returns the chunk-length when using chunked encoding streaming mode for * response entities. A value of -1 means chunked encoding is disabled for * response entities. * * @return The chunk-length when using chunked encoding streaming mode for * response entities. */ public int getChunkLength() { return Integer.parseInt(getHelpedParameters().getFirstValue( "chunkLength", "0")); } /** * Returns the hostname verifier by looking up the "hostnameVerifier" * attribute of the client's context. * * @return The hostname verifier or null. */ public HostnameVerifier getHostnameVerifier() { return (HostnameVerifier) ((getContext() == null) ? null : getContext() .getAttributes().get("hostnameVerifier")); } /** * Returns the read timeout value. A timeout of zero is interpreted as an * infinite timeout. * * @return The read timeout value. */ public int getReadTimeout() { return Integer.parseInt(getHelpedParameters().getFirstValue( "readTimeout", "0")); } /** * Indicates if this URL is being examined in a context in which it makes * sense to allow user interactions such as popping up an authentication * dialog. * * @return True if it makes sense to allow user interactions. */ public boolean isAllowUserInteraction() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "allowUserInteraction", "false")); } /** * Indicates if the protocol will automatically follow redirects. * * @return True if the protocol will automatically follow redirects. */ public boolean isFollowRedirects() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "followRedirects", "false")); } /** * Indicates if the protocol is allowed to use caching whenever it can. * * @return True if the protocol is allowed to use caching whenever it can. */ public boolean isUseCaches() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "useCaches", "false")); } @Override public synchronized void start() throws Exception { super.start(); getLogger().info("Starting the HTTP client"); } @Override public synchronized void stop() throws Exception { super.stop(); getLogger().info("Stopping the HTTP client"); } } restlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/internal/0000775000175000017500000000000011757206352026042 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/internal/HttpUrlConnectionCall.java0000664000175000017500000003344611757206352033135 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.net.internal; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.logging.Level; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import org.restlet.Request; import org.restlet.Response; import org.restlet.Uniform; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.engine.Edition; import org.restlet.engine.http.ClientCall; import org.restlet.engine.security.SslContextFactory; import org.restlet.engine.security.SslUtils; import org.restlet.engine.util.SystemUtils; import org.restlet.ext.net.HttpClientHelper; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * HTTP client connector call based on JDK's java.net.HttpURLConnection class. * * @author Jerome Louvel */ public class HttpUrlConnectionCall extends ClientCall { /** The wrapped HTTP URL connection. */ private final HttpURLConnection connection; /** Indicates if the response headers were added. */ private volatile boolean responseHeadersAdded; /** * Constructor. * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. * @param hasEntity * Indicates if the call will have an entity to send to the * server. * @throws IOException */ public HttpUrlConnectionCall(HttpClientHelper helper, String method, String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); if (requestUri.startsWith("http")) { URL url = new URL(requestUri); this.connection = (HttpURLConnection) url.openConnection(); // These properties can only be used with Java 1.5 and upper // releases int majorVersionNumber = SystemUtils.getJavaMajorVersion(); int minorVersionNumber = SystemUtils.getJavaMinorVersion(); if ((majorVersionNumber > 1) || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) { this.connection.setConnectTimeout(getHelper() .getConnectTimeout()); this.connection.setReadTimeout(getHelper().getReadTimeout()); } this.connection.setAllowUserInteraction(getHelper() .isAllowUserInteraction()); this.connection.setDoOutput(hasEntity); this.connection.setInstanceFollowRedirects(getHelper() .isFollowRedirects()); this.connection.setUseCaches(getHelper().isUseCaches()); this.responseHeadersAdded = false; if (this.connection instanceof HttpsURLConnection) { setConfidential(true); HttpsURLConnection https = (HttpsURLConnection) this.connection; SslContextFactory sslContextFactory = SslUtils .getSslContextFactory(getHelper()); if (sslContextFactory != null) { try { SSLContext sslContext = sslContextFactory .createSslContext(); https .setSSLSocketFactory(sslContext .getSocketFactory()); } catch (Exception e) { throw new RuntimeException( "Unable to create SSLContext.", e); } } HostnameVerifier verifier = helper.getHostnameVerifier(); if (verifier != null) { https.setHostnameVerifier(verifier); } } } else { throw new IllegalArgumentException( "Only HTTP or HTTPS resource URIs are allowed here"); } } /** * Returns the connection. * * @return The connection. */ public HttpURLConnection getConnection() { return this.connection; } /** * Returns the HTTP client helper. * * @return The HTTP client helper. */ @Override public HttpClientHelper getHelper() { return (HttpClientHelper) super.getHelper(); } /** * Returns the response reason phrase. * * @return The response reason phrase. */ @Override public String getReasonPhrase() { try { return getConnection().getResponseMessage(); } catch (IOException e) { return null; } } @Override protected Representation getRepresentation(InputStream stream) { Representation r = super.getRepresentation(stream); return new ConnectionClosingRepresentation(r, getConnection()); } @Override public WritableByteChannel getRequestEntityChannel() { return null; } @Override public OutputStream getRequestEntityStream() { return getRequestStream(); } @Override public OutputStream getRequestHeadStream() { return getRequestStream(); } /** * Returns the request entity stream if it exists. * * @return The request entity stream if it exists. */ public OutputStream getRequestStream() { try { return getConnection().getOutputStream(); } catch (IOException ioe) { return null; } } @Override public ReadableByteChannel getResponseEntityChannel(long size) { return null; } @Override public InputStream getResponseEntityStream(long size) { InputStream result = null; try { result = getConnection().getInputStream(); } catch (IOException ioe) { result = getConnection().getErrorStream(); } if (result == null) { // Maybe an error stream is available instead result = getConnection().getErrorStream(); } return result; } /** * Returns the modifiable list of response headers. * * @return The modifiable list of response headers. */ @Override public Series getResponseHeaders() { Series result = super.getResponseHeaders(); if (!this.responseHeadersAdded) { // Read the response headers int i = 1; String headerName = getConnection().getHeaderFieldKey(i); String headerValue = getConnection().getHeaderField(i); while (headerName != null) { result.add(headerName, headerValue); i++; if (Edition.CURRENT != Edition.GAE) { headerName = getConnection().getHeaderFieldKey(i); headerValue = getConnection().getHeaderField(i); } else { try { headerName = getConnection().getHeaderFieldKey(i); headerValue = getConnection().getHeaderField(i); } catch (java.util.NoSuchElementException e) { headerName = null; } } } this.responseHeadersAdded = true; } return result; } /** * Returns the response address.
* Corresponds to the IP address of the responding server. * * @return The response address. */ @Override public String getServerAddress() { return getConnection().getURL().getHost(); } /** * Returns the response status code. * * @return The response status code. * @throws IOException * @throws IOException */ @Override public int getStatusCode() throws IOException { return getConnection().getResponseCode(); } /** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * * @param request * The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { if (request.isEntityAvailable()) { Representation entity = request.getEntity(); // These properties can only be used with Java 1.5 and upper // releases int majorVersionNumber = SystemUtils.getJavaMajorVersion(); int minorVersionNumber = SystemUtils.getJavaMinorVersion(); if ((majorVersionNumber > 1) || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) { // Adjust the streaming mode if (entity.getSize() != -1) { // The size of the entity is known in advance getConnection().setFixedLengthStreamingMode( (int) entity.getSize()); } else { // The size of the entity is not known in advance if (getHelper().getChunkLength() >= 0) { // Use chunked encoding getConnection().setChunkedStreamingMode( getHelper().getChunkLength()); } else { // Use entity buffering to determine the content // length } } } } // Set the request method getConnection().setRequestMethod(getMethod()); // Set the request headers for (Parameter header : getRequestHeaders()) { getConnection().addRequestProperty(header.getName(), header.getValue()); } // Ensure that the connection is active getConnection().connect(); // Send the optional entity result = super.sendRequest(request); } catch (ConnectException ce) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the connection to the remote HTTP server.", ce); result = new Status(Status.CONNECTOR_ERROR_CONNECTION, ce); } catch (SocketTimeoutException ste) { getHelper() .getLogger() .log( Level.FINE, "An timeout error occurred during the communication with the remote HTTP server.", ste); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ste); } catch (FileNotFoundException fnfe) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", fnfe); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, fnfe); } catch (IOException ioe) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); } catch (Exception e) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", e); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, e); } return result; } @Override public void sendRequest(Request request, Response response, Uniform callback) throws Exception { // Send the request sendRequest(request); if(request.getOnSent() != null){ request.getOnSent().handle(request, response); } if (callback != null) { // Transmit to the callback, if any. callback.handle(request, response); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/internal/ConnectionClosingRepresentation.javarestlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/internal/ConnectionClosingRepresentation.0000664000175000017500000000433511757206352034411 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.net.internal; import java.net.HttpURLConnection; import org.restlet.representation.Representation; import org.restlet.util.WrapperRepresentation; /** * Representation that wraps another representation and closes the parent * {@link HttpURLConnection} when the representation is released. * * @author Kevin Conaway */ class ConnectionClosingRepresentation extends WrapperRepresentation { /** The parent connection. */ private final HttpURLConnection connection; /** * Default constructor. * * @param wrappedRepresentation * The wrapped representation. * @param connection * The parent connection. */ public ConnectionClosingRepresentation( Representation wrappedRepresentation, HttpURLConnection connection) { super(wrappedRepresentation); this.connection = connection; } @Override public void release() { this.connection.disconnect(); super.release(); } } restlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/FtpClientHelper.java0000664000175000017500000001633611757206352030132 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.net; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.ClientHelper; import org.restlet.engine.local.Entity; import org.restlet.engine.util.SystemUtils; import org.restlet.representation.InputRepresentation; /** * FTP client connector using the {@link URLConnection}. Here is the list of * parameters that are supported. They should be set in the Client's context * before it is started: * * * * * * * * * * * * * * * * * * * * * * * * * *
Parameter nameValue typeDefault valueDescription
allowUserInteractionbooleanfalseIf true, this URL is being examined in a context in which it makes sense * to allow user interactions such as popping up an authentication dialog.
readTimeoutint0Sets the read timeout to a specified timeout, in milliseconds. A timeout * of zero is interpreted as an infinite timeout.
useCachesbooleanfalseIf true, the protocol is allowed to use caching whenever it can.
* * @see Networking * Features * @author Jerome Louvel */ public class FtpClientHelper extends ClientHelper { /** * Constructor. * * @param client * The client to help. */ public FtpClientHelper(Client client) { super(client); getProtocols().add(Protocol.FTP); } /** * Returns the read timeout value. A timeout of zero is interpreted as an * infinite timeout. * * @return The read timeout value. */ public int getReadTimeout() { return Integer.parseInt(getHelpedParameters().getFirstValue( "readTimeout", "0")); } /** * Indicates if this URL is being examined in a context in which it makes * sense to allow user interactions such as popping up an authentication * dialog. * * @return True if it makes sense to allow user interactions. */ public boolean isAllowUserInteraction() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "allowUserInteraction", "false")); } /** * Indicates if the protocol is allowed to use caching whenever it can. * * @return True if the protocol is allowed to use caching whenever it can. */ public boolean isUseCaches() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "useCaches", "false")); } @Override public void handle(Request request, Response response) { try { if (Protocol.FTP.equals(request.getProtocol())) { if (Method.GET.equals(request.getMethod())) { Reference ftpRef = request.getResourceRef(); String userInfo = null; if ((request.getChallengeResponse() != null) && ChallengeScheme.FTP_PLAIN.equals(request .getChallengeResponse().getScheme()) && (request.getChallengeResponse().getIdentifier() != null)) { userInfo = request.getChallengeResponse() .getIdentifier(); if (request.getChallengeResponse().getSecret() != null) { userInfo += ":" + new String(request.getChallengeResponse() .getSecret()); } } if (userInfo != null) { ftpRef.setUserInfo(userInfo); } URL url = ftpRef.toUrl(); URLConnection connection = url.openConnection(); // These properties can only be used with Java 1.5 and upper // releases int majorVersionNumber = SystemUtils.getJavaMajorVersion(); int minorVersionNumber = SystemUtils.getJavaMinorVersion(); if ((majorVersionNumber > 1) || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) { connection.setConnectTimeout(getConnectTimeout()); connection.setReadTimeout(getReadTimeout()); } connection .setAllowUserInteraction(isAllowUserInteraction()); connection.setUseCaches(isUseCaches()); response.setEntity(new InputRepresentation(connection .getInputStream())); // Try to infer the metadata from the file extensions Entity.updateMetadata(request.getResourceRef().getPath(), response.getEntity(), true, getMetadataService()); } else { getLogger() .log(Level.WARNING, "Only GET method are supported by this FTP connector"); } } } catch (IOException e) { getLogger().log(Level.WARNING, "FTP client error", e); response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, e.getMessage()); } } @Override public synchronized void start() throws Exception { super.start(); getLogger().info("Starting the FTP client"); } @Override public synchronized void stop() throws Exception { super.stop(); getLogger().info("Stopping the FTP client"); } } restlet-2.0.14/org.restlet.ext.net/src/org/restlet/ext/net/package.html0000664000175000017500000000040411757206352026505 0ustar jamespagejamespage Integration with Java URLConnection class. Provides FTP, HTTP and HTTPS client connectors. @since Restlet 1.0 @see URLConnection Javadocs restlet-2.0.14/org.restlet.ext.jaxrs/0000775000175000017500000000000012001473147020130 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/pom.xml0000600000175000017500000000376212001473147021443 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.jaxrs Restlet Extension - JAX-RS Implementation of JAX-RS (JSR-311) javax.activation activation 1.1.1 commons-fileupload commons-fileupload 1.2.1 javax.mail mail 1.4.2 javax.xml.bind jaxb-api 2.1 com.sun.xml.bind jaxb-impl 2.1.12 javax.ws.rs jsr311-api 1.0 org.restlet.jse org.restlet.lib.org.json ${lib-json-version} javax.servlet servlet-api 2.5 javax.xml.stream stax-api 1.0-2 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.jaxrs/src/0000775000175000017500000000000012001473147020717 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/META-INF/0000775000175000017500000000000011757206450022067 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/META-INF/services/0000775000175000017500000000000011757206350023711 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/META-INF/services/javax.ws.rs.ext.RuntimeDelegate0000664000175000017500000000006611757206350031676 0ustar jamespagejamespageorg.restlet.ext.jaxrs.internal.spi.RuntimeDelegateImplrestlet-2.0.14/org.restlet.ext.jaxrs/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446023527 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.jaxrs/src/org/0000775000175000017500000000000011757206350021515 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/0000775000175000017500000000000011757206350023177 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/0000775000175000017500000000000011757206350023777 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/0000775000175000017500000000000011757206350025126 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/JaxRsApplication.java0000664000175000017500000002417711757206350031217 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import java.util.Collection; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Component; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.ClientInfo; import org.restlet.routing.Filter; import org.restlet.security.Authenticator; /** *

* This is the main class to be used for the instantiation of a JAX-RS runtime * environment. *

*

* To set up a JAX-RS runtime environment you should instantiate a * {@link JaxRsApplication#JaxRsApplication(Context)}. *

    *
  • Add your {@link Application}(s) by calling {@link #add(Application)}.
  • *
  • If you need authentication, set a {@link Authenticator} and perhaps an * {@link RoleChecker}, see {@link #setGuard(Authenticator)} or * {@link #setAuthentication(Authenticator, RoleChecker)}.
  • *
* At least add the JaxRsApplication to a {@link Component}. *

* * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Stephan Koops */ public class JaxRsApplication extends org.restlet.Application { /** * The Guard to use (either {@link org.restlet.security.Guard} or * {@link org.restlet.security.UniformGuard}). May be null. */ private volatile Filter guard; /** The {@link JaxRsRestlet} to use. */ private volatile JaxRsRestlet jaxRsRestlet; /** * Creates an new JaxRsApplication. * * @see #JaxRsApplication(Context) */ public JaxRsApplication() { this((Context) null); } /** * Creates an new JaxRsApplication. Attach JAX-RS-{@link Application}s by * using {@link #add(Application)}. * * @param context * The application's dedicated context based on the protected * parent component's context. */ public JaxRsApplication(Context context) { super(context); this.jaxRsRestlet = new JaxRsRestlet(context, getMetadataService()); } /** * * @param appConfig * @throws IllegalArgumentException */ public JaxRsApplication(javax.ws.rs.core.Application appConfig) throws IllegalArgumentException { add(appConfig); } /** *

* Attaches a JAX-RS {@link Application} to this JaxRsApplication.
* The providers are available for all root resource classes provided to * this JaxRsApplication. If you won't mix them, instantiate another * JaxRsApplication. *

* * @param appConfig * Contains the classes to load as root resource classes and as * providers. Invalid root resource classes and provider classes * are ignored, according to JAX-RS specification. * @return true, if all resource classes and providers could be added, or * false at least one could not be added. Exceptions were logged. * @throws IllegalArgumentException * if the given appConfig is null. */ public boolean add(Application appConfig) throws IllegalArgumentException { if (appConfig == null) { throw new IllegalArgumentException( "The ApplicationConfig must not be null"); } final JaxRsRestlet jaxRsRestlet = this.jaxRsRestlet; final Set> classes = appConfig.getClasses(); final Set singletons = appConfig.getSingletons(); boolean everythingFine = true; if (singletons != null) { for (final Object singleton : singletons) { // LATER test: check, if a singelton is also available in the // classes -> ignore or whatever if (singleton != null && !classes.contains(singleton.getClass())) { everythingFine &= jaxRsRestlet.addSingleton(singleton); } } } if (classes != null) { for (final Class clazz : classes) { everythingFine &= jaxRsRestlet.addClass(clazz); } } return everythingFine; } @Override public Restlet createInboundRoot() { Restlet restlet = this.jaxRsRestlet; if (this.guard != null) { this.guard.setNext(restlet); restlet = this.guard; } return restlet; } /** * Returns the Guard * * @return the Guard */ public Filter getGuard() { return this.guard; } /** * Returns the used {@link JaxRsRestlet}. * * @return the used {@link JaxRsRestlet}. */ public JaxRsRestlet getJaxRsRestlet() { return this.jaxRsRestlet; } /** * Returns the ObjectFactory for root resource class and provider * instantiation, if given. * * @return the ObjectFactory for root resource class and provider * instantiation, if given. */ public ObjectFactory getObjectFactory() { return this.jaxRsRestlet.getObjectFactory(); } /** * Returns the current RoleChecker * * @return the current RoleChecker * @deprecated Use {@link ClientInfo#getRoles()} instead */ @Deprecated public RoleChecker getRoleChecker() { return this.jaxRsRestlet.getRoleChecker(); } /** * Returns an unmodifiable set with the attached root resource classes. * * @return an unmodifiable set with the attached root resource classes. */ public Collection> getRootResources() { return this.jaxRsRestlet.getRootResourceClasses(); } /** * Returns an unmodifiable set of supported URIs (relative to this * Application). * * @return an unmodifiable set of supported URIs (relative). */ public Collection getRootUris() { return this.jaxRsRestlet.getRootUris(); } /** * Adds the given applications to the available applications. * * @param apps */ public void setApplications(Collection apps) { for (Application app : apps) { add(app); } } /** * Sets the objects to check the authentication. The {@link Authenticator} * checks the username and password (e.g.), the {@link RoleChecker} manages * the role management for the JAX-RS extension. * * @param guard * the Guard to use. * @param roleChecker * the RoleChecker to use * @see #setGuard(Authenticator) * @see #setRoleChecker(RoleChecker) * @deprecated Use {@link ClientInfo#getRoles()} instead */ @Deprecated public void setAuthentication(Authenticator guard, RoleChecker roleChecker) { setGuard(guard); setRoleChecker(roleChecker); } @Override public void setContext(Context context) { super.setContext(context); this.jaxRsRestlet.setContext(context); } /** * Sets the {@link Authenticator} to use. It should typically use the * {@link Context} of this application.
* The new one is ignored, after the root Restlet is created (see * {@link #createRoot()}. * *

* This replaced the guard set via * {@link #setGuard(org.restlet.security.Authenticator)}. * * @param guard * the Guard to use. * @see #setAuthentication(Authenticator, RoleChecker) * @see #setGuard(org.restlet.security.Authenticator) * @deprecated Use the {@link #setGuard(Authenticator)} method instead. */ @Deprecated public void setGuard(org.restlet.security.Guard guard) { this.guard = guard; } /** * Set the Guard from the org.restlet.security package. This should be * called before the root Restlet is created. *

* This replaced the guard set via * {@link #setGuard(org.restlet.security.Guard)}. * * @param guard * the Guard to use. */ public void setGuard(Authenticator guard) { this.guard = guard; } /** * Sets the ObjectFactory for root resource class and provider * instantiation. * * @param objectFactory * the ObjectFactory for root resource class and provider * instantiation. */ public void setObjectFactory(ObjectFactory objectFactory) { this.jaxRsRestlet.setObjectFactory(objectFactory); } /** * Sets the {@link RoleChecker} to use.
* If you give an RoleChecker, you should also give a Guard. * * @param roleChecker * @see #setAuthentication(Authenticator, RoleChecker) * @see #setGuard(Authenticator) * @deprecated Use {@link ClientInfo#getRoles()} instead */ @Deprecated public void setRoleChecker(RoleChecker roleChecker) { this.jaxRsRestlet.setRoleChecker(roleChecker); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/0000775000175000017500000000000011757206350026742 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/0000775000175000017500000000000011757206350030574 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/ReaderProvider.java0000664000175000017500000001075511757206350034364 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.engine.io.BioUtils; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.representation.Representation; /** * This ProviderWrapper is used to read directly from a {@link Reader}. * * @author Stephan Koops * @see BufferedReaderProvider */ @Provider public class ReaderProvider extends AbstractProvider { /** * Returns a Reader wrapping the given entity stream, with respect to the * {@link CharacterSet} of the entity of the current {@link Request}, or * UTF-8 if no character set was given or if it is not available */ static Reader getReader(InputStream entityStream) { final Representation entity = Request.getCurrent().getEntity(); CharacterSet cs; if (entity != null) { cs = entity.getCharacterSet(); if (cs == null) { cs = Util.JAX_RS_DEFAULT_CHARACTER_SET; } } else { cs = Util.JAX_RS_DEFAULT_CHARACTER_SET; } try { return BioUtils.getReader(entityStream, cs); } catch (UnsupportedEncodingException e) { try { return BioUtils.getReader(entityStream, null); } catch (UnsupportedEncodingException e2) { throw new WebApplicationException(500); } } } /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ @Override public long getSize(Reader t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public Reader readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { return getReader(entityStream); } @Override protected Class supportedClass() { return Reader.class; } /** * @see MessageBodyWriter#writeTo(Object, Type, Annotation[], MediaType, * MultivaluedMap, OutputStream) */ @Override public void writeTo(Reader reader, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { CharacterSet cs = Response.getCurrent().getEntity().getCharacterSet(); BioUtils.copy(BioUtils.getStream(reader, cs), entityStream); // NICE test charset for ReaderProvider.writeTo(..) ? } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/JaxbProvider.java0000664000175000017500000002056511757206350034046 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.restlet.Context; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * Provider for JAXB objects. * * @author Stephan Koops */ @Provider @Produces({ "application/xml", MediaType.TEXT_XML, "application/*+xml" }) @Consumes({ "application/xml", MediaType.TEXT_XML, "application/*+xml" }) public class JaxbProvider extends AbstractJaxbProvider { /** * Specifies that the parser will expand entity reference nodes. By default * the value of this is set to true. */ private volatile boolean expandingEntityRefs; private final Logger logger = Context.getCurrentLogger(); /** Limits potential XML overflow attacks. */ private boolean secureProcessing; /** * Indicates the desire for validating this type of XML representations * against a DTD. Note that for XML schema or Relax NG validation, use the * "schema" property instead. * * @see DocumentBuilderFactory#setValidating(boolean) */ private volatile boolean validatingDtd; /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @see DocumentBuilderFactory#setXIncludeAware(boolean) */ private volatile boolean xIncludeAware; /** * Default constructor. */ public JaxbProvider() { this.expandingEntityRefs = false; this.secureProcessing = true; this.validatingDtd = false; this.xIncludeAware = false; } @Override Logger getLogger() { return this.logger; } /** * Indicates if the parser will expand entity reference nodes. By default * the value of this is set to true. * * @return True if the parser will expand entity reference nodes. */ public boolean isExpandingEntityRefs() { return expandingEntityRefs; } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.isAnnotationPresent(XmlRootElement.class); } /** * Indicates if it limits potential XML overflow attacks. * * @return True if it limits potential XML overflow attacks. */ public boolean isSecureProcessing() { return secureProcessing; } /** * Indicates the desire for validating this type of XML representations * against an XML schema if one is referenced within the contents. * * @return True if the schema-based validation is enabled. */ public boolean isValidatingDtd() { return validatingDtd; } @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.isAnnotationPresent(XmlRootElement.class); } /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @return The current value of the xIncludeAware flag. */ public boolean isXIncludeAware() { return xIncludeAware; } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { try { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setXIncludeAware(isXIncludeAware()); spf.setNamespaceAware(true); spf.setValidating(isValidatingDtd()); spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isSecureProcessing()); spf.setFeature( "http://xml.org/sax/features/external-general-entities", isExpandingEntityRefs()); spf.setFeature( "http://xml.org/sax/features/external-parameter-entities", isExpandingEntityRefs()); XMLReader reader = spf.newSAXParser().getXMLReader(); JAXBContext jaxbContext = getJaxbContext(type); Unmarshaller um = jaxbContext.createUnmarshaller(); return um.unmarshal(new SAXSource(reader, new InputSource( entityStream))); } catch (Exception e) { throw new IOException("Could not unmarshal to " + type.getName()); } } /** * Indicates if the parser will expand entity reference nodes. By default * the value of this is set to true. * * @param expandEntityRefs * True if the parser will expand entity reference nodes. */ public void setExpandingEntityRefs(boolean expandEntityRefs) { this.expandingEntityRefs = expandEntityRefs; } /** * Indicates if it limits potential XML overflow attacks. * * @param secureProcessing * True if it limits potential XML overflow attacks. */ public void setSecureProcessing(boolean secureProcessing) { this.secureProcessing = secureProcessing; } /** * Indicates the desire for validating this type of XML representations * against an XML schema if one is referenced within the contents. * * @param validating * The new validation flag to set. */ public void setValidatingDtd(boolean validating) { this.validatingDtd = validating; } /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @param includeAware * The new value of the xIncludeAware flag. */ public void setXIncludeAware(boolean includeAware) { xIncludeAware = includeAware; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpResponseHeaders, OutputStream entityStream) throws IOException { marshal(object, entityStream); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/AbstractProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/AbstractProvider.ja0000664000175000017500000001145411757206350034373 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; /** * This abstract class ease the development of {@link MessageBodyReader}s and * {@link MessageBodyWriter}. * * @author Stephan Koops * @param * the type that can be read and written * @see MessageBodyReader * @see MessageBodyWriter */ public abstract class AbstractProvider implements MessageBodyWriter, MessageBodyReader { /** * Logs the problem and throws an IOException. * * @param logger * @param message * @param exc * @throws IOException */ protected static IOException logAndIOExc(Logger logger, String message, Throwable exc) throws IOException { logger.log(Level.WARNING, message, exc); if (exc == null) { throw new IOException(message); } throw new IOException(message + ": " + exc.getMessage()); } /** * Returns the size of the given objects. * * @param object * the object to check the size * @return the size of the object, or -1, if it is not direct readable from * the object. * @see MessageBodyWriter#getSize(Object, Class, Type, Annotation[], * MediaType) */ public abstract long getSize(T object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.isAssignableFrom(supportedClass()); } public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return supportedClass().isAssignableFrom(type); // mainClass.isAssignableFrom(subClass); } /** * @param genericType * The generic {@link Type} to convert to. * @param annotations * the annotations of the artefact to convert to * @see javax.ws.rs.ext.MessageBodyReader#readFrom(java.lang.Class, * javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, * java.io.InputStream) */ public abstract T readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpResponseHeaders, InputStream entityStream) throws IOException; /** * Returns the class object supported by this provider. * * @return the class object supported by this provider. */ protected Class supportedClass() { throw new UnsupportedOperationException( "You must implement method " + this.getClass().getName() + ".supportedClass(), if you do not implement isReadable(...) or isWriteable(...)"); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public abstract void writeTo(T object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException; } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/StringProvider.java0000664000175000017500000001371711757206350034431 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.engine.io.BioUtils; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.representation.Representation; /** * ProviderWrapper for {@link String}s. Could also write other * {@link CharSequence}s. * * @author Stephan Koops */ @Provider @Produces("*/*") @Consumes("*/*") public class StringProvider extends AbstractProvider { /** * Returns the given entity as byte array converted by the given character * set. * * @param entity * @param charsetName * @return the given entity as byte array converted by the given character * set. */ private byte[] getByteArray(CharSequence entity, String charsetName) { final String string = entity.toString(); try { if (charsetName != null) return string.getBytes(charsetName); } catch (UnsupportedEncodingException e) { // try with default character set, see below } try { return string.getBytes(Util.JAX_RS_DEFAULT_CHARACTER_SET_AS_STRING); } catch (UnsupportedEncodingException e1) { return string.getBytes(); } // NICE cache for some seconds } /** * @return the character set of the current entity, or null, if no entity or * no character set is available. */ private String getCurrentResponseEntityCharset() { Representation entity = Response.getCurrent().getEntity(); if (entity == null) return null; CharacterSet characterSet = entity.getCharacterSet(); if (characterSet == null) return null; return characterSet.toString(); } /** * @return the character set of the current entity, or null, if no entity or * no character set is available. */ private CharacterSet getCurrentRequestEntityCharacterSet() { Representation entity = Request.getCurrent().getEntity(); if (entity == null) return null; return entity.getCharacterSet(); } /** * Returns an {@link InputStream}, that returns the right encoded data * according to the given {@link CharacterSet}. * * @param charSequ * @param charsetName * see {@link String#getBytes(String)} * @return */ private ByteArrayInputStream getInputStream(CharSequence charSequ, String charsetName) { byte[] bytes = getByteArray(charSequ, charsetName); return new ByteArrayInputStream(bytes); } /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ @Override public long getSize(CharSequence entity, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return getByteArray(entity, getCurrentResponseEntityCharset()).length; } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.isAssignableFrom(String.class); } @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return CharSequence.class.isAssignableFrom(type); } @Override public String readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { return BioUtils.toString(entityStream, getCurrentRequestEntityCharacterSet()); } /** * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(Object, Class, Type, * Annotation[], MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(CharSequence charSequence, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { String charset = getCurrentResponseEntityCharset(); InputStream inputStream = getInputStream(charSequence, charset); BioUtils.copy(inputStream, entityStream); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/BufferedReaderProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/BufferedReaderProvi0000664000175000017500000000506311757206350034410 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.IoUtils; /** * This {@link MessageBodyReader} is used to read data from the network to a * {@link BufferedReader}. * * @author Stephan Koops * @see ReaderProvider */ @Provider public class BufferedReaderProvider implements MessageBodyReader { public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return BufferedReader.class.isAssignableFrom(type); } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ public BufferedReader readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { return new BufferedReader(ReaderProvider.getReader(entityStream), IoUtils.getBufferSize()); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/FileUploadProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/FileUploadProvider.0000664000175000017500000001263711757206350034345 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import static javax.ws.rs.core.HttpHeaders.CONTENT_ENCODING; import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH; import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadException; import org.restlet.ext.jaxrs.internal.util.Util; /** * Entity Provider, that reads "multipart/form-data" to a {@link List}< * {@link FileItem}>. It is using the Apache Commons FileUpload (developed * with version 1.2), which must be available in the classpath, if you want to * use this provider. For more information see the Apache FileUpload website.
* This provider is not tested yet. * * @author Stephan Koops * @see MultipartProvider */ @Provider @Consumes("multipart/form-data") public class FileUploadProvider implements MessageBodyReader> { // NICE test FileUploadProvider private static final class RequestContext implements org.apache.commons.fileupload.RequestContext { private final InputStream entityStream; private final String contentEncoding; private final String contentType; private final int contentLength; /** * @param entityStream * @param respHeaders * @throws NumberFormatException * if the content length is not an int */ private RequestContext(InputStream entityStream, MultivaluedMap respHeaders) throws NumberFormatException { this.entityStream = entityStream; this.contentEncoding = respHeaders.getFirst(CONTENT_ENCODING); final String contentLength = respHeaders.getFirst(CONTENT_LENGTH); this.contentLength = Integer.parseInt(contentLength); this.contentType = respHeaders.getFirst(CONTENT_TYPE); } public final String getCharacterEncoding() { return this.contentEncoding; } public final int getContentLength() { return this.contentLength; } public final String getContentType() { return this.contentType; } public final InputStream getInputStream() { return this.entityStream; } } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[], MediaType) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (!type.equals(List.class)) { return false; } final Class genericClass = Util.getGenericClass(genericType); if (genericClass == null) { return false; } return FileItem.class.isAssignableFrom(genericClass); } /** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ @SuppressWarnings("unchecked") public List readFrom(Class> type, Type genericType, Annotation[] annotations, MediaType mediaType, final MultivaluedMap respHeaders, final InputStream entityStream) throws IOException { final FileUpload rfu = new FileUpload(); final RequestContext requCtx = new RequestContext(entityStream, respHeaders); try { return rfu.parseRequest(requCtx); } catch (FileUploadException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } final IOException ioExc = new IOException( "Could not read the multipart/form-data"); ioExc.initCause(e); throw ioExc; } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/ByteArrayProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/ByteArrayProvider.j0000664000175000017500000000624011757206350034366 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.BioUtils; /** * {@link Provider} to read and write byte[]. * * @author Stephan Koops */ @Provider public class ByteArrayProvider extends AbstractProvider { /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object, * java.lang.Class, java.lang.reflect.Type, * java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) */ @Override public long getSize(byte[] t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return t.length; } @Override public byte[] readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BioUtils.copy(entityStream, baos); return baos.toByteArray(); } /** * @see MessageBodyWriter#isWriteable(Class) */ @Override protected Class supportedClass() { return byte[].class; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(byte[] data, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { entityStream.write(data); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/MultipartProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/MultipartProvider.j0000664000175000017500000001142711757206350034450 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.activation.DataSource; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.internet.MimeMultipart; import javax.mail.util.ByteArrayDataSource; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; /** * Entity Provider, that reads "multipart/form-data" to a {@link Multipart} and * writes vice versa.
* This provider is not tested yet. * * @author Stephan Koops * @see FileUploadProvider */ @Provider @Consumes("multipart/form-data") @Produces("multipart/form-data") @SuppressWarnings("all") public class MultipartProvider implements MessageBodyReader, MessageBodyWriter { // NICE test MultipartProvider /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ public long getSize(Multipart multipart, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[]) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.isAssignableFrom(MimeMultipart.class); } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[]) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Multipart.class.isAssignableFrom(type); } /** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ public Multipart readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpResponseHeaders, InputStream entityStream) throws IOException { final String contentType = "multipart/form-data"; final DataSource ds = new ByteArrayDataSource(entityStream, contentType); try { return new MimeMultipart(ds); } catch (MessagingException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } final IOException ioExc = new IOException( "Could not deserialize the data to a Multipart"); ioExc.initCause(e); throw ioExc; } } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Multipart multipart, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { try { multipart.writeTo(entityStream); } catch (MessagingException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } final IOException ioExc = new IOException( "Could not serialize the Multipart"); ioExc.initCause(e); throw ioExc; } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/InputStreamProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/InputStreamProvider0000664000175000017500000000623011757206350034506 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.BioUtils; /** * This Provider is used to read directly from an {@link InputStream}. * * @author Stephan Koops * @see MessageBodyReader * @see MessageBodyWriter */ @Provider public class InputStreamProvider extends AbstractProvider { /** * @see MessageBodyWriter#getSize(Object) */ @Override public long getSize(InputStream t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public InputStream readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { return entityStream; } /** * @see AbstractProvider#supportedClass() */ @Override protected Class supportedClass() { return InputStream.class; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(InputStream inputStream, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { BioUtils.copy(inputStream, entityStream); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/StreamingOutputProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/StreamingOutputProv0000664000175000017500000000540011757206350034537 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; /** * This ProviderWrapper is used to read directly from an {@link StreamingOutput}. * * @author Stephan Koops * @see StreamingOutput */ @Provider public class StreamingOutputProvider implements MessageBodyWriter { /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ public long getSize(StreamingOutput t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[]) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return StreamingOutput.class.isAssignableFrom(type); } /** * @see MessageBodyWriter#writeTo(Object, Type, Annotation[], MediaType, * MultivaluedMap, OutputStream) */ public void writeTo(StreamingOutput so, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { so.write(entityStream); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/WwwFormMmapProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/WwwFormMmapProvider0000664000175000017500000001000111757206350034445 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.data.Form; import org.restlet.engine.io.BioUtils; import org.restlet.ext.jaxrs.internal.core.UnmodifiableMultivaluedMap; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper; import org.restlet.representation.Representation; /** * This {@link ProviderWrapper} converts MultivaluedMap<String,String> * form content to application/x-www-form-urlencoded and vice versa. * * @author Stephan Koops * @see WwwFormFormProvider */ @Provider @Consumes("application/x-www-form-urlencoded") @Produces("application/x-www-form-urlencoded") public class WwwFormMmapProvider extends AbstractProvider> { /** * @see MessageBodyWriter#getSize(Object) */ @Override public long getSize(MultivaluedMap mmap, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see org.restlet.ext.jaxrs.internal.provider.AbstractProvider#supportedClass() */ @Override protected Class supportedClass() { return MultivaluedMap.class; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(MultivaluedMap mmap, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { Form form = Converter.toForm(mmap); Representation formRepr = form.getWebRepresentation(); BioUtils.copy(formRepr.getStream(), entityStream); } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public MultivaluedMap readFrom( Class> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpResponseHeaders, InputStream entityStream) throws IOException { Form form = WwwFormFormProvider.getForm(mediaType, entityStream); return UnmodifiableMultivaluedMap.getFromForm(form, false); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/JaxbElementProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/JaxbElementProvider0000664000175000017500000001165011757206350034433 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import org.restlet.Context; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.util.Util; /** * Provider for {@link JAXBElement}s. * * @author Stephan Koops * @see MessageBodyReader * @see MessageBodyWriter */ @Provider @Produces( { "application/xml", MediaType.TEXT_XML, "application/*+xml" }) @Consumes( { "application/xml", MediaType.TEXT_XML, "application/*+xml" }) public class JaxbElementProvider extends AbstractJaxbProvider> { private final Logger logger = Context.getCurrentLogger(); @Override Logger getLogger() { return this.logger; } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[]) */ @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (!JAXBElement.class.isAssignableFrom(type)) { return false; } return Util.getGenericClass(genericType) != null; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[]) */ @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (!type.isAssignableFrom(JAXBElement.class)) { return false; } return Util.getGenericClass(genericType) != null; } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public JAXBElement readFrom(Class> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpResponseHeaders, InputStream entityStream) throws IOException { final Class clazz = Util.getGenericClass(genericType); if (clazz == null) { throw new ImplementationException( "The JaxbElement provider has gotten a type it could not unmarshal. Perhaps is the JaxbElementProvider not consistent to itself."); } try { final JAXBContext jaxbContext = getJaxbContext(clazz); final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); JAXBElement je = unmarshaller.unmarshal(new StreamSource( entityStream), type); return je; } catch (JAXBException e) { final String message = "Could not unmarshal to " + type.getName(); throw logAndIOExc(getLogger(), message, e); } } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(JAXBElement jaxbElement, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpResponseHeaders, OutputStream entityStream) throws IOException { marshal(jaxbElement.getValue(), entityStream); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/WebAppExcMapper.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/WebAppExcMapper.jav0000664000175000017500000002333411757206350034266 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE; import static javax.ws.rs.core.Response.Status.UNSUPPORTED_MEDIA_TYPE; import java.util.Collection; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.ext.ExceptionMapper; import org.restlet.Application; import org.restlet.ext.jaxrs.ExtendedUriBuilder; import org.restlet.ext.jaxrs.ExtendedUriInfo; import org.restlet.ext.jaxrs.internal.exceptions.NotAcceptableWebAppException; import org.restlet.ext.jaxrs.internal.exceptions.UnsupportedMediaTypeWebAppException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; /** * The exception mapper for {@link WebApplicationException}s. * * @author Stephan Koops */ public class WebAppExcMapper implements ExceptionMapper { @Context private ExtensionBackwardMapping extBackwMapping; @Context private HttpHeaders httpHeaders; @Context private ExtendedUriInfo uriInfo; /** * Adds the extensions for the given {@link Variant}. * * @param uriBuilder * the UriBuilder to add the extensions. * @param variant * the Variant to add the extensions for. * @return true, if the extensions where added, or false, if the extension * for the media type is not available. */ private boolean addExtensions(ExtendedUriBuilder uriBuilder, Variant variant) { uriBuilder.equals(null); String mediaTypeExt = null; String languageExt = null; String encodingExt = null; if (variant.getMediaType() != null) { mediaTypeExt = this.extBackwMapping.getByMediaType(variant .getMediaType()); if (mediaTypeExt == null) { return false; } } if (variant.getLanguage() != null) { languageExt = this.extBackwMapping.getByLanguage(variant .getLanguage()); if (languageExt == null) { languageExt = Converter.toLanguageString(variant.getLanguage()); } } if (variant.getEncoding() != null) { encodingExt = this.extBackwMapping.getByEncoding(variant .getEncoding()); if (encodingExt == null) { encodingExt = variant.getEncoding(); } } if (languageExt != null) { uriBuilder.extensionLanguage(languageExt); } if (mediaTypeExt != null) { uriBuilder.extensionMedia(mediaTypeExt); } if (encodingExt != null) { uriBuilder.queryParam(Application.getCurrent().getTunnelService() .getEncodingParameter(), encodingExt); } return true; } /** * @return the allowed variants for an unsupported media type exception, or * null if they could not be found. */ private Collection getAcceptedVariants(WebApplicationException wae) { if (wae instanceof UnsupportedMediaTypeWebAppException) { return ((UnsupportedMediaTypeWebAppException) wae).getAccepted(); } return null; } /** * @return the allowed variants for an unsupported media type exception, or * null if they could not be found. */ private Collection getSupportedVariants(WebApplicationException wae) { if (wae instanceof NotAcceptableWebAppException) { return ((NotAcceptableWebAppException) wae).getSupported(); } return null; } /** * Creates an entity with a list of links to the accepted variants. */ private Response giveOtherVariant(Collection acceptedVariants, Response response) { if ((acceptedVariants != null) && acceptedVariants.isEmpty()) { acceptedVariants = null; } final ResponseBuilder rb = Response.fromResponse(response); final StringBuilder stb = new StringBuilder(); // NICE speed optimization possible by using a Reader or InputStream, // which returns the values of String[] or better byte[][] stb.append("The given resource variant is not supported."); if (acceptedVariants != null) { stb.append("Please use one of the following:\n"); stb.append("\n"); for (final Variant variant : acceptedVariants) { stb.append("* "); stb.append(variant); stb.append("\n"); } } rb.entity(stb); rb.type(MediaType.TEXT_PLAIN_TYPE); return rb.build(); } /** * Creates an entity with a list of links to the supported variants. * * @param supportedVariants * the supported variants * @param response * the Response to add the entity to. * @return a Response with a list of the given variants as entity. If the * supportedVariants is null, the given {@link Response} is * returned. */ private Response requestOtherVariants( Collection supportedVariants, Response response) { if ((supportedVariants != null) && supportedVariants.isEmpty()) { supportedVariants = null; } final ResponseBuilder rb = Response.fromResponse(response); boolean xhtml = false; boolean html = this.httpHeaders.getAcceptableMediaTypes().contains( MediaType.TEXT_HTML_TYPE); if (!html) { xhtml = this.httpHeaders.getAcceptableMediaTypes().contains( MediaType.APPLICATION_XHTML_XML_TYPE); html = xhtml; } final StringBuilder stb = new StringBuilder(); // NICE speed optimization possible by using a Reader or InputStream, // which returns the values of String[] or better byte[][] if (html) { stb.append("\n"); stb.append("The requested variant is not available"); stb.append("\n\n\n

\n"); } stb.append("The requested variant is not available."); if (supportedVariants != null) { stb.append(" Try one of the following:\n"); if (html) { stb.append("

    "); } stb.append("\n"); for (final Variant variant : supportedVariants) { final ExtendedUriBuilder uriBuilder = this.uriInfo .getRequestUriBuilder(); final boolean added = addExtensions(uriBuilder, variant); if (!added) { continue; } final String uri = uriBuilder.build().toString(); if (html) { stb.append("
  • "); stb.append(uri); stb.append("
  • "); } stb.append("\n"); } if (html) { stb.append("
"); } } if (html) { stb.append(""); } rb.entity(stb); if (xhtml) { rb.type(MediaType.APPLICATION_XHTML_XML_TYPE); } else if (html) { rb.type(MediaType.TEXT_HTML_TYPE); } else { rb.type(MediaType.TEXT_PLAIN_TYPE); } return rb.build(); } /** * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Object) */ public Response toResponse(WebApplicationException wae) { final Response response = wae.getResponse(); if (response == null) { return null; } if (response.getEntity() != null) { return response; } if (response.getStatus() == NOT_ACCEPTABLE.getStatusCode()) { return requestOtherVariants(getSupportedVariants(wae), response); } if (response.getStatus() == UNSUPPORTED_MEDIA_TYPE.getStatusCode()) { return giveOtherVariant(getAcceptedVariants(wae), response); } return response; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/SourceProvider.java0000664000175000017500000001120711757206350034413 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.restlet.Context; /** * JAX-RS ProviderWrapper to convert a {@link Source} to an object and vice * versa. * * @author Stephan Koops */ @Provider public class SourceProvider extends AbstractProvider { private final Logger logger = Context.getCurrentLogger(); private final TransformerFactory transformerFactory = TransformerFactory .newInstance(); @Override public long getSize(Source object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public Source readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { return new StreamSource(entityStream); } @Override protected Class supportedClass() { return Source.class; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(Source source, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { final StreamResult streamResult = new StreamResult(entityStream); Transformer transformer; try { transformer = this.transformerFactory.newTransformer(); } catch (TransformerConfigurationException e) { this.logger.log(Level.WARNING, "Could not create Transformer", e); final IOException ioException = new IOException( "Could not create javax.xml.transform.Transformer"); ioException.setStackTrace(e.getStackTrace()); throw ioException; } try { transformer.transform(source, streamResult); } catch (Exception e) { final IOException ioException = new IOException( "Could not transform the javax.xml.transform.Source"); ioException.setStackTrace(e.getStackTrace()); throw ioException; } catch (TransformerFactoryConfigurationError e) { final IOException ioException = new IOException( "Could not transform the javax.xml.transform.Source"); ioException.setStackTrace(e.getStackTrace()); throw ioException; } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/WwwFormFormProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/WwwFormFormProvider0000664000175000017500000001234611757206350034474 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import org.restlet.Context; import org.restlet.Message; import org.restlet.Request; import org.restlet.data.Form; import org.restlet.engine.io.BioUtils; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; /** * This {@link ProviderWrapper} converts Restlet {@link Form}s to * application/x-www-form-urlencoded and vice versa.
* For encoding or not the same conventions are valid than for * {@link WwwFormMmapProvider}. * * @author Stephan Koops * @see WwwFormMmapProvider */ @Provider @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_FORM_URLENCODED) public class WwwFormFormProvider extends AbstractProvider
{ private static Logger logger = Context.getCurrentLogger(); /** * @see AbstractProvider#getSize(java.lang.Object) */ @Override public long getSize(Form form, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see AbstractProvider#supportedClass() */ @Override protected Class supportedClass() { return Form.class; } /** * @see AbstractProvider#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(Form form, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { Representation formRepr = form.getWebRepresentation(); BioUtils.copy(formRepr.getStream(), entityStream); } /** * @see AbstractProvider#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ @Override public Form readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpResponseHeaders, InputStream entityStream) throws IOException { return getForm(mediaType, entityStream); } /** * @param mediaType * @param entityStream * @return */ static Form getForm(MediaType mediaType, InputStream entityStream) { org.restlet.data.MediaType restletMediaType = Converter .toRestletMediaType(mediaType); final Form form; form = new Form(new InputRepresentation(entityStream, restletMediaType)); saveToThreadsRequest(form); return form; } /** * @param form */ private static void saveToThreadsRequest(Form form) { try { Field formField = Message.class.getDeclaredField("entityForm"); formField.setAccessible(true); formField.set(Request.getCurrent(), form); } catch (SecurityException e) { logger.log(Level.WARNING, "Could not put the Form into the Restlet request", e); } catch (IllegalArgumentException e) { logger.log(Level.WARNING, "Could not put the Form into the Restlet request", e); } catch (NoSuchFieldException e) { logger.log(Level.WARNING, "Could not put the Form into the Restlet request", e); } catch (IllegalAccessException e) { logger.log(Level.WARNING, "Could not put the Form into the Restlet request", e); } } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/FileProvider.java0000664000175000017500000000651011757206350034033 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.BioUtils; /** * This Provider reads or writes {@link File}s. * * @author Stephan Koops */ @Provider public class FileProvider extends AbstractProvider { /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ @Override public long getSize(File t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public File readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { final File file = File.createTempFile("FileProvider", ".tmp"); BioUtils.copy(entityStream, new FileOutputStream(file)); return file; } /** * @see AbstractProvider#supportedClass() */ @Override protected Class supportedClass() { return File.class; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(File file, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { final InputStream inputStream = new FileInputStream(file); BioUtils.copy(inputStream, entityStream); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/AbstractJaxbProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/AbstractJaxbProvide0000664000175000017500000001110411757206350034415 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Providers; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; /** * @author Stephan Koops */ abstract class AbstractJaxbProvider extends AbstractProvider { /** Improves performance by caching contexts which are expensive to create. */ private final static ConcurrentMap, JAXBContext> contexts = new ConcurrentHashMap, JAXBContext>(); /** * Returns the JAXB context, if possible from the cached contexts. * * @param type * * @param contextResolver * * @return The JAXB context. * @throws JAXBException */ public static synchronized JAXBContext getJaxbContext(Class type, ContextResolver contextResolver) throws JAXBException { // Contexts are thread-safe so reuse those. JAXBContext result = contexts.get(type); if (result == null) { if (contextResolver != null) { result = contextResolver.getContext(type); } if (result == null) { try { result = JAXBContext.newInstance(type); } catch (NoClassDefFoundError e) { throw new WebApplicationException(Response.serverError() .entity(e.getMessage()).build()); } } contexts.put(type, result); } return result; } /** public for testing */ public ContextResolver contextResolver; /** * Returns the JAXB context, if possible from the cached contexts. * * @param type * * @return The JAXB context. * @throws JAXBException */ public JAXBContext getJaxbContext(Class type) throws JAXBException { return getJaxbContext(type, this.contextResolver); } abstract Logger getLogger(); /** * @see MessageBodyWriter#getSize(Object) */ @Override public final long getSize(T object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } void marshal(Object object, OutputStream entityStream) throws IOException { final Class type = object.getClass(); try { final JAXBContext jaxbContext = getJaxbContext(object.getClass()); final Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(object, entityStream); } catch (JAXBException e) { throw logAndIOExc(getLogger(), "Could not marshal the " + type.getName(), e); } } @Context void setContextResolver(Providers providers) { this.contextResolver = providers.getContextResolver(JAXBContext.class, MediaType.APPLICATION_XML_TYPE); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/JsonProvider.java0000664000175000017500000001525711757206350034075 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONString; import org.json.JSONTokener; import org.restlet.Request; import org.restlet.data.CharacterSet; import org.restlet.engine.io.BioUtils; import org.restlet.representation.Representation; /** * This Provider serializes all Objects by the package org.json. It can * deserialize to {@link JSONObject}, {@link JSONArray} and {@link JSONString}. * * @author Stephan Koops */ @Provider @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class JsonProvider extends AbstractProvider { // NICE better JSON support planned for later. /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ @Override public long getSize(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[]) */ @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (JSONObject.class.isAssignableFrom(type)) { return true; } if (JSONArray.class.isAssignableFrom(type)) { return true; } if (JSONString.class.isAssignableFrom(type)) { return true; } return false; } @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } /** * @return the character set of the current entity, or null, if no entity or * no character set is available. */ private CharacterSet getCurrentRequestEntityCharacterSet() { Representation entity = Request.getCurrent().getEntity(); if (entity == null) return null; return entity.getCharacterSet(); } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { final String jsonString; jsonString = BioUtils.toString(entityStream, getCurrentRequestEntityCharacterSet()); try { if (JSONObject.class.isAssignableFrom(type)) { return new JSONObject(jsonString); } if (JSONArray.class.isAssignableFrom(type)) { return new JSONArray(jsonString); } } catch (JSONException e) { final IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } if (JSONString.class.isAssignableFrom(type)) { return new JSONString() { public String toJSONString() { return jsonString; } @Override public String toString() { return jsonString; } }; } throw new IllegalArgumentException("the given type " + type + " is not supported"); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { try { final OutputStreamWriter writer = new OutputStreamWriter( entityStream); if (object instanceof JSONString) { writer.write(((JSONString) object).toJSONString()); } else if (object instanceof JSONArray) { writer.write(((JSONArray) object).toString()); } else if (object instanceof CharSequence) { writer.write(object.toString()); } else { JSONObject jsonObject; if (object instanceof JSONObject) { jsonObject = (JSONObject) object; } else if (object instanceof JSONTokener) { jsonObject = new JSONObject((JSONTokener) object); } else if (object instanceof Map) { jsonObject = new JSONObject((Map) object); } else { jsonObject = new JSONObject(object); } jsonObject.write(writer); } writer.flush(); } catch (JSONException e) { final IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/ConverterProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/ConverterProvider.j0000664000175000017500000001310611757206350034432 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import org.restlet.Application; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.service.ConverterService; /** * This Provider is based on the pluggable Restlet's {@link ConverterService}. * * @author Jerome Louvel */ @Provider public class ConverterProvider extends AbstractProvider { /** The Restlet converter service. */ private ConverterService converterService; /** * Constructor. */ public ConverterProvider() { Application application = Application.getCurrent(); if (application != null) { this.converterService = application.getConverterService(); } if (this.converterService == null) { this.converterService = new ConverterService(); } } /** * Return the Restlet converter service. * * @return The Restlet converter service. */ private ConverterService getConverterService() { return converterService; } @Override public long getSize(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { // Convert the object into a representation Variant targetVariant = new Variant(new org.restlet.data.MediaType( mediaType.toString())); Representation representation = getConverterService().toRepresentation( object, targetVariant, null); return (representation == null) ? -1 : representation.getSize(); } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { Variant sourceVariant = new Variant(new org.restlet.data.MediaType( mediaType.toString())); List> classes = getConverterService().getObjectClasses( sourceVariant); for (Class clazz : classes) { if (clazz.isAssignableFrom(type)) { return true; } } return false; } @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { Variant targetVariant = new Variant(new org.restlet.data.MediaType( mediaType.toString())); List variants = getConverterService().getVariants( type, targetVariant); return (variants != null) && !variants.isEmpty(); } @Override public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { Representation sourceRepresentation = new InputRepresentation( entityStream, new org.restlet.data.MediaType( mediaType.toString())); return getConverterService().toObject(sourceRepresentation, type, null); } @Override public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { // Convert the object into a representation Variant targetVariant = new Variant(new org.restlet.data.MediaType( mediaType.toString())); Representation representation = getConverterService().toRepresentation( object, targetVariant, null); // Copy entity headers (NOT SUPPORTED) // Series entityHeaders = new Form(); // HttpServerAdapter.addEntityHeaders(representation, entityHeaders); // // for (Parameter header : entityHeaders) { // httpHeaders.add(header.getName(), header.getValue()); // } // Write the representation if (representation != null) { representation.write(entityStream); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/DataSourceProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/provider/DataSourceProvider.0000664000175000017500000000650211757206350034345 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.activation.DataSource; import javax.mail.util.ByteArrayDataSource; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.BioUtils; /** * Provider for {@link DataSource}s. * * @author Stephan Koops */ @Provider public class DataSourceProvider extends AbstractProvider { /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object, java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) */ @Override public long getSize(DataSource t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], * MultivaluedMap, InputStream) */ @Override public DataSource readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { return new ByteArrayDataSource(entityStream, mediaType.toString()); } @Override protected Class supportedClass() { return DataSource.class; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ @Override public void writeTo(DataSource dataSource, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { final InputStream inputStream = dataSource.getInputStream(); BioUtils.copy(inputStream, entityStream); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/0000775000175000017500000000000011757206350030605 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceClass.java0000664000175000017500000004475111757206350034240 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import static org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil.checkForJaxRsAnnotations; import static org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil.getHttpMethod; import static org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil.isVolatile; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.Encoded; import javax.ws.rs.Path; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalMethodParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.util.RemainingPath; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; /** * Instances represents a root resource class. * * A Java class that uses JAX-RS annotations to implement a corresponding Web * resource, see chapter 3 of JAX-RS specification * * @author Stephan Koops */ public class ResourceClass extends AbstractJaxRsWrapper { /** * Caches the allowed methods (unmodifiable) for given remainingParts. */ private final Map> allowedMethods = new HashMap>(); protected final Class jaxRsClass; /** * is true, if the resource class is annotated with @Path. Is available * after constructor was running. */ private final boolean leaveEncoded; /** * The resource methods of this resource class. (It is initialized in * method.) * {@link #initResourceMethodsAndLocators(ThreadLocalizedContext, JaxRsProviders, ExtensionBackwardMapping, Logger)} */ private final Collection resourceMethods = new ArrayList(); /** * The resource methods and sub resource locators of this resource class. * (It is initialized in method.) * {@link #initResourceMethodsAndLocators(ThreadLocalizedContext, JaxRsProviders, ExtensionBackwardMapping, Logger)} */ private final Collection resourceMethodsAndLocators = new ArrayList(); /** * The sub resource locators of this resource class. (It is initialized in * method.) * {@link #initResourceMethodsAndLocators(ThreadLocalizedContext, JaxRsProviders, ExtensionBackwardMapping, Logger)} */ private final Collection subResourceLocators = new ArrayList(); /** * Creates a new root resource class wrapper. Will not set the path, because * it is not available for a normal resource class. * * @param jaxRsClass * @param tlContext * the {@link ThreadLocalizedContext} of the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * @param jaxRsProviders * all entity providers * @param extensionBackwardMapping * the extension backward mapping * @param logger * The logger to log warnings, if the class is not valid. * @throws MissingAnnotationException * @throws IllegalArgumentException * @see ResourceClasses#getResourceClass(Class) */ ResourceClass(Class jaxRsClass, ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalArgumentException, MissingAnnotationException { super(); this.leaveEncoded = jaxRsClass.isAnnotationPresent(Encoded.class); this.jaxRsClass = jaxRsClass; initResourceMethodsAndLocators(tlContext, jaxRsProviders, extensionBackwardMapping, logger); } /** * Creates a new root resource class wrapper. To be used by subclass * {@link RootResourceClass}. * * @param jaxRsClass * @param jaxRsProviders * all entity providers * @param tlContext * the {@link ThreadLocalizedContext} of the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * @param extensionBackwardMapping * the extension backward mapping * @param logger * @throws IllegalArgumentException * @throws IllegalPathOnClassException * @throws MissingAnnotationException * if @{@link Path} is missing on the jaxRsClass * @see ResourceClasses#getResourceClass(Class) */ protected ResourceClass(Class jaxRsClass, JaxRsProviders jaxRsProviders, ThreadLocalizedContext tlContext, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalArgumentException, IllegalPathOnClassException, MissingAnnotationException { super(PathRegExp.createForClass(jaxRsClass)); this.leaveEncoded = jaxRsClass.isAnnotationPresent(Encoded.class); this.jaxRsClass = jaxRsClass; this.initResourceMethodsAndLocators(tlContext, jaxRsProviders, extensionBackwardMapping, logger); } /** * Warn, if one of the message parameters is primitive. * * @param execMethod * @param logger */ private void checkForPrimitiveParameters(Method execMethod, Logger logger) { final Class[] paramTypes = execMethod.getParameterTypes(); for (final Class paramType : paramTypes) { if (paramType.isPrimitive()) { logger.config("The method " + execMethod + " contains a primitive parameter " + paramType + "."); logger .config("It is recommended to use it's wrapper class. If no value could be read from the request, now you would got the default value. If you use the wrapper class, you would get null."); break; } } } @Override public boolean equals(Object anotherObject) { if (this == anotherObject) { return true; } if (!(anotherObject instanceof ResourceClass)) { return false; } final ResourceClass otherResourceClass = (ResourceClass) anotherObject; return this.jaxRsClass.equals(otherResourceClass.jaxRsClass); } /** * Returns the allowed methods on the remainingPart. This method is used for * a OPTIONS request, if no special java method in the root resource class * was found for the given remainingPart. * * @param remainingPath * @return an unmodifiable {@link Set} of the allowed methods. */ public Set getAllowedMethods( RemainingPath remainingPath) { Set allowedMethods = this.allowedMethods .get(remainingPath); if (allowedMethods != null) { return allowedMethods; } allowedMethods = new HashSet(6); for (final ResourceMethod rm : getMethodsForPath(remainingPath)) { allowedMethods.add(rm.getHttpMethod()); } if (!allowedMethods.isEmpty()) { if (allowedMethods.contains(org.restlet.data.Method.GET)) { allowedMethods.add(org.restlet.data.Method.HEAD); } } final Set unmodifiable = Collections .unmodifiableSet(allowedMethods); this.allowedMethods.put(remainingPath, unmodifiable); return unmodifiable; } /** * Returns the method with the annotations, corresponding to the given * method. If the given method contains any JAX-RS annotations, it is * returned. If it is not annotated with JAX-RS annotations, this method * looks recursive in the subclass and the implemented interfaces, until it * found one. This would be returned. * * @param javaMethod * The java method to look for annotations * @return the founded method, or null, if no method with annotations was * found. Returns also null, if null was given. */ private Method getAnnotatedJavaMethod(Method javaMethod) { if (javaMethod == null) { return null; } final boolean useMethod = checkForJaxRsAnnotations(javaMethod); if (useMethod) { return javaMethod; } final Class methodClass = javaMethod.getDeclaringClass(); final Class superclass = methodClass.getSuperclass(); final Method scMethod = getMethodFromClass(superclass, javaMethod); Method annotatedMeth = getAnnotatedJavaMethod(scMethod); if (annotatedMeth != null) { return annotatedMeth; } final Class[] interfaces = methodClass.getInterfaces(); for (final Class interfaze : interfaces) { final Method ifMethod = getMethodFromClass(interfaze, javaMethod); annotatedMeth = getAnnotatedJavaMethod(ifMethod); if (annotatedMeth != null) { return annotatedMeth; } } return null; } /** * @return Returns the wrapped root resource class. */ public final Class getJaxRsClass() { return this.jaxRsClass; } /** * Looks for the method with the same signature as the given method in the * given class. * * @param clazz * The Class to look for the method. * @param subClassMethod * the Method to look for it's signature in the given class. * @return the method in the given class, with the same signature as given * method, or null if such method is not available. Returns also * null, if the given class is null. */ private Method getMethodFromClass(Class clazz, Method subClassMethod) { if (clazz == null) { return null; } final String methodName = subClassMethod.getName(); final Class[] parameterTypes = subClassMethod.getParameterTypes(); try { return clazz.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { return null; } } /** * Return all resource methods for the given path, ignoring HTTP method, * consumed or produced mimes and so on. * * @param resourceObject * The resource object * @param remainingPath * the path * @return The ist of ResourceMethods */ public Collection getMethodsForPath( RemainingPath remainingPath) { // NICE results may be chached, if any method is returned. // The 404 case will be called rarely and produce a lot of cached data. final List resourceMethods = new ArrayList(); for (final ResourceMethod method : this.resourceMethods) { final PathRegExp methodPath = method.getPathRegExp(); if (remainingPath.isEmptyOrSlash()) { if (methodPath.isEmptyOrSlash()) { resourceMethods.add(method); } } else { if (methodPath.matchesWithEmpty(remainingPath)) { resourceMethods.add(method); } } } return resourceMethods; } /** * @return returns the name of the wrapped class */ public String getName() { return this.jaxRsClass.getName(); } /** * @return Return the sub resource methods of the given class. */ public final Iterable getResourceMethods() { return this.resourceMethods; } /** * @return Returns the sub resource locatores and sub resource methods. */ public final Collection getResourceMethodsAndLocators() { return this.resourceMethodsAndLocators; } /** * @return Returns the sub resource locators of the given class. */ public final Iterable getSubResourceLocators() { return this.subResourceLocators; } @Override public int hashCode() { return this.jaxRsClass.hashCode(); } /** * @return Returns true if the wrapped resource class has sub resource * methods or sub resource locators. */ public final boolean hasSubResourceMethodsOrLocators() { return !this.resourceMethodsAndLocators.isEmpty(); } private void initResourceMethodsAndLocators( ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalArgumentException, MissingAnnotationException { for (final Method execMethod : jaxRsClass.getMethods()) { final Method annotatedMethod = getAnnotatedJavaMethod(execMethod); if (annotatedMethod == null) { continue; } final Path path = annotatedMethod.getAnnotation(Path.class); org.restlet.data.Method httpMethod; httpMethod = getHttpMethod(annotatedMethod); try { if (httpMethod != null) { if (isVolatile(execMethod)) { continue; } ResourceMethod subResMeth; try { subResMeth = new ResourceMethod(execMethod, annotatedMethod, this, httpMethod, tlContext, jaxRsProviders, extensionBackwardMapping, logger); } catch (IllegalMethodParamTypeException e) { String message = "Ignore method " + execMethod + ": An annotated parameter of the resource method " + annotatedMethod + " is has an illegal type"; logger.log(Level.WARNING, message, e); continue; } catch (IllegalParamTypeException e) { String message = "Ignore method " + execMethod + ": " + e.getMessage(); logger.log(Level.WARNING, message, e); continue; } this.resourceMethods.add(subResMeth); this.resourceMethodsAndLocators.add(subResMeth); checkForPrimitiveParameters(execMethod, logger); } else { if (path != null) { if (isVolatile(execMethod)) { continue; } SubResourceLocator subResLoc; try { subResLoc = new SubResourceLocator(execMethod, annotatedMethod, this, tlContext, jaxRsProviders, extensionBackwardMapping, logger); } catch (IllegalMethodParamTypeException e) { String message = "Ignore method " + execMethod + ": An annotated parameter of the resource method " + annotatedMethod + " is has an illegal type"; logger.log(Level.WARNING, message, e); continue; } catch (IllegalParamTypeException e) { String message = "Ignore method " + execMethod + ": " + e.getMessage(); logger.log(Level.WARNING, message, e); continue; } this.subResourceLocators.add(subResLoc); this.resourceMethodsAndLocators.add(subResLoc); checkForPrimitiveParameters(execMethod, logger); } } // NICE warn, if @Consumes, @Produces or another // non-useful annotation is available on a method to ignore. } catch (IllegalPathOnMethodException e) { logger.warning("The method " + annotatedMethod + " is annotated with an illegal path: " + e.getPath() + ". Ignoring this method. (" + e.getMessage() + ")"); } } } /** * @return the leaveEncoded */ boolean isLeaveEncoded() { return this.leaveEncoded; } @Override public String toString() { return this.getClass().getSimpleName() + "[" + this.jaxRsClass + "]"; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/AbstractMethodWrapper.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/AbstractMethodWrapp0000664000175000017500000001532611757206350034455 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Logger; import javax.ws.rs.Encoded; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalMethodParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; /** * An abstract wrapper class for resource methods, sub resource methods and sub * resource locators. * * @author Stephan Koops */ public abstract class AbstractMethodWrapper extends AbstractJaxRsWrapper { /** * the Java method that should be called. This method could be different * from the method containing the annotations, see section 3.6 "Annotation * Inheritance" of JSR-311-spec. * * @see ResourceMethod#annotatedMethod */ final Method executeMethod; final ParameterList parameters; final ResourceClass resourceClass; /** * * @param executeMethod * @param annotatedMethod * @param resourceClass * @param tlContext * @param jaxRsProviders * @param extensionBackwardMapping * @param entityAllowed * @param logger * @throws IllegalPathOnMethodException * @throws IllegalArgumentException * if the annotated method is null * @throws MissingAnnotationException * @throws IllegalMethodParamTypeException * if one of the parameters annotated with @{@link Context} * has a type that must not be annotated with @ * {@link Context}. * @throws IllegalPathParamTypeException */ AbstractMethodWrapper(Method executeMethod, Method annotatedMethod, ResourceClass resourceClass, ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, boolean entityAllowed, Logger logger) throws IllegalPathOnMethodException, IllegalArgumentException, MissingAnnotationException, IllegalMethodParamTypeException, IllegalPathParamTypeException { super(PathRegExp.createForMethod(annotatedMethod)); this.executeMethod = executeMethod; this.executeMethod.setAccessible(true); // NICE log message, if an Exception with no exc mapper is declared. this.resourceClass = resourceClass; final boolean leaveEncoded = resourceClass.isLeaveEncoded() || annotatedMethod.isAnnotationPresent(Encoded.class); try { this.parameters = new ParameterList(executeMethod, annotatedMethod, tlContext, leaveEncoded, jaxRsProviders, extensionBackwardMapping, entityAllowed, logger); } catch (IllegalTypeException e) { throw new IllegalMethodParamTypeException(e); } } /** * Returns the name of the method * * @return Returns the name of the method */ public String getName() { final Class[] paramTypes = this.executeMethod.getParameterTypes(); final StringBuilder stb = new StringBuilder(); stb.append(this.executeMethod.getName()); stb.append('('); Util.append(stb, paramTypes); stb.append(')'); return stb.toString(); } /** * @return Returns the regular expression for the URI template */ @Override public PathRegExp getPathRegExp() { return super.getPathRegExp(); } /** * @return Returns the resource class of this method. */ public ResourceClass getResourceClass() { return this.resourceClass; } /** * Invokes the method and returned the created representation for the * response. * * @param resourceObject * @return the unwrapped returned object by the wrapped method. * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws WebApplicationException * @throws ConvertRepresentationException */ Object internalInvoke(ResourceObject resourceObject) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ConvertRepresentationException, WebApplicationException { final Object[] args = this.parameters.get(); final Object jaxRsResourceObj = resourceObject.getJaxRsResourceObject(); return this.executeMethod.invoke(jaxRsResourceObj, args); } @Override public String toString() { return this.getClass().getSimpleName() + "[" + this.executeMethod.getDeclaringClass().getSimpleName() + "." + this.executeMethod.getName() + "(__)]"; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/SingletonRootResourceClass.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/SingletonRootResour0000664000175000017500000001101311757206350034532 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalConstrParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.MissingConstructorException; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; /** * @author Stephan Koops */ public class SingletonRootResourceClass extends RootResourceClass { private final ResourceObject rootResObject; /** * @param rootResourceObject * @param tlContext * @param jaxRsProviders * @param extensionBackwardMapping * @param logger * @throws IllegalArgumentException * @throws MissingAnnotationException * @throws IllegalPathOnClassException * @throws MissingConstructorException * @throws IllegalConstrParamTypeException * @throws IllegalFieldTypeException * @throws IllegalBeanSetterTypeException * @throws IllegalPathParamTypeException * @throws InvocationTargetException * if an exception occurs while the injecting of * dependencies. * @throws InjectException */ SingletonRootResourceClass(Object rootResourceObject, ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalArgumentException, MissingAnnotationException, IllegalPathOnClassException, MissingConstructorException, IllegalConstrParamTypeException, IllegalFieldTypeException, IllegalBeanSetterTypeException, IllegalPathParamTypeException, InvocationTargetException, InjectException { super(rootResourceObject.getClass(), tlContext, jaxRsProviders, extensionBackwardMapping, logger); this.injectHelper.injectInto(rootResourceObject, true); this.rootResObject = new ResourceObject(rootResourceObject, this); } /** * Creates an or gets the instance of this root resource class. * * @param objectFactory * object responsible for instantiating the root resource * class. Optional, thus can be null. * @return the wrapped root resource class instance * @throws InvocationTargetException * @throws InstantiateException * @throws MissingAnnotationException * @throws WebApplicationException */ @Override public ResourceObject getInstance(ObjectFactory objectFactory) { return this.rootResObject; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.j0000664000175000017500000002010111757206350034373 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import javax.ws.rs.Encoded; import javax.ws.rs.Path; import javax.ws.rs.WebApplicationException; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalConstrParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.MissingConstructorException; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.params.IntoRrcInjector; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; /** * Instances represents a root resource class, see chapter 3 of JAX-RS * specification. * * @author Stephan Koops */ public abstract class RootResourceClass extends ResourceClass implements RrcOrRml { /** * Checks, if the class is public and so on. * * @param jaxRsClass * JAX-RS root resource class or JAX-RS provider. * @param typeName * "root resource class" or "provider" * @throws MissingAnnotationException * if the class is not annotated with @Path. */ private static void checkClassForPathAnnot(Class jaxRsClass, String typeName) throws MissingAnnotationException { boolean found = jaxRsClass.isAnnotationPresent(Path.class); if (!found) { Class[] interfaces = jaxRsClass.getInterfaces(); for (int i = 0; !found && i < interfaces.length; i++) { found = (interfaces[i].isAnnotationPresent(Path.class)); } } if (!found) { final String msg = "The " + typeName + " " + jaxRsClass.getName() + " is not annotated with @Path. The class will be ignored."; throw new MissingAnnotationException(msg); } } protected final Constructor constructor; protected final ParameterList constructorParameters; /** * Injects the necessary values directly into the root resource class. */ protected final IntoRrcInjector injectHelper; private final boolean singelton = false; /** * Creates a wrapper for the given JAX-RS root resource class. * * @param jaxRsClass * the root resource class to wrap * @param tlContext * the {@link ThreadLocalizedContext} of the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * @param jaxRsProviders * all entity providers. * @param extensionBackwardMapping * the extension backward mapping * @param logger * the logger to use. * @see ResourceClasses#getRootResourceClass(Class) * @throws IllegalArgumentException * if the class is not a valid root resource class. * @throws MissingAnnotationException * if the class is not annotated with @Path. * @throws IllegalPathOnClassException * @throws MissingConstructorException * if no valid constructor could be found * @throws IllegalConstrParamTypeException * @throws IllegalBeanSetterTypeException * @throws IllegalFieldTypeException * @throws IllegalPathParamTypeException */ RootResourceClass(Class jaxRsClass, ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalArgumentException, MissingAnnotationException, IllegalPathOnClassException, MissingConstructorException, IllegalConstrParamTypeException, IllegalFieldTypeException, IllegalBeanSetterTypeException, IllegalPathParamTypeException { super(jaxRsClass, jaxRsProviders, tlContext, extensionBackwardMapping, logger); Util.checkClassConcrete(getJaxRsClass(), "root resource class"); checkClassForPathAnnot(jaxRsClass, "root resource class"); this.injectHelper = new IntoRrcInjector(jaxRsClass, tlContext, isLeaveEncoded(), jaxRsProviders, extensionBackwardMapping); this.constructor = WrapperUtil.findJaxRsConstructor(getJaxRsClass(), "root resource class"); final boolean constructorLeaveEncoded = isLeaveEncoded() || constructor.isAnnotationPresent(Encoded.class); try { this.constructorParameters = new ParameterList(this.constructor, tlContext, constructorLeaveEncoded, jaxRsProviders, extensionBackwardMapping, true, logger, !this.singelton); } catch (IllegalConstrParamTypeException e) { throw e; } catch (IllegalTypeException e) { throw new IllegalConstrParamTypeException(e); } } @Override public boolean equals(Object anotherObject) { if (this == anotherObject) { return true; } if (!(anotherObject instanceof RootResourceClass)) { return false; } final RootResourceClass otherRootResourceClass = (RootResourceClass) anotherObject; return this.jaxRsClass.equals(otherRootResourceClass.jaxRsClass); } /** * Creates an or gets the instance of this root resource class. * * @param objectFactory * object responsible for instantiating the root resource * class. Optional, thus can be null. * @return a wrapped root resource instance * @throws InvocationTargetException * @throws InstantiateException * @throws MissingAnnotationException * @throws WebApplicationException */ public abstract ResourceObject getInstance(ObjectFactory objectFactory) throws InstantiateException, InvocationTargetException; /** * @return Returns the regular expression for the URI template */ @Override public PathRegExp getPathRegExp() { return super.getPathRegExp(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/0000775000175000017500000000000011757206350032437 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriterSubSet.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBod0000664000175000017500000001210011757206350034365 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.SortedMetadata; /** * Contains a List of wrapped {@link javax.ws.rs.ext.MessageBodyWriter}s. * * @author Stephan Koops */ public class MessageBodyWriterSubSet { private static final MessageBodyWriterSubSet EMPTY = new MessageBodyWriterSubSet( new ArrayList(), null, null); /** * @return an empty {@link MessageBodyWriterSubSet} */ public static MessageBodyWriterSubSet empty() { return EMPTY; } /** * The class supported by the contained message body writers, given by the * type parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}. Could * be {@code null}. */ private final Class type; /** * The type supported by the contained message body writers, given by the * type parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}. Could * be {@code null}. */ private final Type genericType; private final List mbws; MessageBodyWriterSubSet(List mbws, final Class type, final Type genericType) { this.mbws = mbws; this.genericType = genericType; this.type = type; } /** * returns a list of all producible media types. * * @return a list of all producible media types. If this set is not empty, * this result is not empty. '*/*' is returned for a message * body writer with no @{@link javax.ws.rs.Produces} * annotation. */ public Collection getAllProducibleMediaTypes() { final List p = new ArrayList(); for (final MessageBodyWriter messageBodyWriter : this.mbws) { p.addAll(messageBodyWriter.getProducedMimes()); } return p; } /** * Finds a {@link MessageBodyWriter} in this Set that best matches media * types of the response method and of the accepted {@link MediaType}s. * * @param determinedResponseMediaType * The {@link MediaType}s of the response, declared by the * resource methods or given by the * {@link javax.ws.rs.core.Response}. * @param annotations * @param accMediaTypes * the accepted media types. * @return A {@link MessageBodyWriter} that best matches the given accepted. * Returns null, if no adequate {@link MessageBodyWriter} could be * found in this set. */ public MessageBodyWriter getBestWriter( MediaType determinedResponseMediaType, Annotation[] annotations, SortedMetadata accMediaTypes) { final List mbws = new ArrayList(); for (final MessageBodyWriter mbw : this.mbws) { if (mbw.supportsWrite(determinedResponseMediaType)) { if (mbw.isWriteable(type, genericType, annotations, Converter .toJaxRsMediaType(determinedResponseMediaType))) { mbws.add(mbw); } } } for (final Iterable amts : accMediaTypes.listOfColls()) { for (final MessageBodyWriter mbw : mbws) { if (mbw.supportsWrite(amts)) { return mbw; } } } return null; } /** * Returns true, if this set is empty * * @return true, if this set is empty */ public boolean isEmpty() { return this.mbws.isEmpty(); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/AbstractProviderWrapper.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/AbstractPr0000664000175000017500000002555211757206350034440 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Providers; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil; import org.restlet.ext.jaxrs.internal.wrappers.params.ContextInjector; /** * Wraps a JAX-RS provider, see chapter 4 of JAX-RS specification. * * @author Stephan Koops * @see javax.ws.rs.ext.Provider */ abstract class AbstractProviderWrapper implements ProviderWrapper { /** * the mimes this MessageBodyReader consumes. */ private final List consumedMimes; private final List producedMimes; private final Class genericMbrType; private final Class genericMbwType; /** * Creates a new wrapper for a Provider and initializes the provider. If the * given class is not a provider, an {@link IllegalArgumentException} is * thrown. * * @param jaxRsProviderClass * the JAX-RS provider class. * @throws IllegalArgumentException * if the class is not a valid provider, may not be instantiated * or what ever. * @throws WebApplicationException * @see javax.ws.rs.ext.MessageBodyReader * @see javax.ws.rs.ext.MessageBodyWriter * @see javax.ws.rs.ext.ContextResolver */ AbstractProviderWrapper(Class jaxRsProviderClass) throws IllegalArgumentException, WebApplicationException { final Consumes pm = jaxRsProviderClass.getAnnotation(Consumes.class); if (pm != null) { this.consumedMimes = WrapperUtil.convertToMediaTypes(pm.value()); } else { this.consumedMimes = Collections.singletonList(MediaType.ALL); } final Produces cm = jaxRsProviderClass.getAnnotation(Produces.class); if (cm != null) { this.producedMimes = WrapperUtil.convertToMediaTypes(cm.value()); } else { this.producedMimes = Collections.singletonList(MediaType.ALL); } this.genericMbrType = Util.getGenericClass(jaxRsProviderClass, javax.ws.rs.ext.MessageBodyReader.class); this.genericMbwType = Util.getGenericClass(jaxRsProviderClass, javax.ws.rs.ext.MessageBodyWriter.class); // LATER use Type instead of Class here } @Override public abstract boolean equals(Object otherProvider); /** * @return the JAX-RS provider class name */ public abstract String getClassName(); /** * Returns the list of produced {@link MediaType}s of the wrapped * {@link javax.ws.rs.ext.MessageBodyWriter}. * * @return List of produced {@link MediaType}s. */ public List getConsumedMimes() { return this.consumedMimes; } /** * Returns the list of produced {@link MediaType}s of the wrapped * {@link javax.ws.rs.ext.MessageBodyWriter}. * * @return List of produced {@link MediaType}s. If the entity provider is * not annotated with @ {@link Produces}, '*/*' is * returned. */ public List getProducedMimes() { return this.producedMimes; } @Override public abstract int hashCode(); // TEST before a call of a message body reader or writer the current state // of the matched resources and URIs must be stored for the current thread. /** * initializes the provider (injection into annotated fields and setters). * * @throws IllegalFieldTypeException * @throws IllegalBeanSetterTypeException * @throws InjectException * @throws InvocationTargetException */ void initProvider(Object jaxRsProvider, ThreadLocalizedContext tlContext, Providers allProviders, ExtensionBackwardMapping extensionBackwardMapping) throws IllegalFieldTypeException, IllegalBeanSetterTypeException, InjectException, InvocationTargetException { final ContextInjector iph = new ContextInjector(jaxRsProvider.getClass(), tlContext, allProviders, extensionBackwardMapping); iph.injectInto(jaxRsProvider, false); } /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.ContextResolver}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.ContextResolver}, otherwise false. */ public abstract boolean isContextResolver(); /** * Checks, if this provider represents an {@link ExceptionMapper}. * * @return true, if this provider is an {@link ExceptionMapper}, or false if * not. */ public abstract boolean isExceptionMapper(); /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyReader}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyReader}, otherwise false. */ public abstract boolean isReader(); /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyWriter}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyWriter}, otherwise false. */ public abstract boolean isWriter(); /** * Checks, if this message body writer supports the given type (by the type * parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}) * * @param entityClass * the type * @param genericType * the generic type * @return true, if this MessageBodyWriter supports the given type, false, * if not. * @see org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriter#supportsWrite(java.lang.Class, * java.lang.reflect.Type) */ public boolean supportsWrite(Class entityClass, Type genericType) { if (entityClass == null) { return false; } if (genericType == null) { // LATER use Type instead of Class } if (this.genericMbwType == null) { return false; } final boolean supportsWrite = this.genericMbwType .isAssignableFrom(entityClass); return supportsWrite; } /** * Checks, if this message body reader supports the given type (by the type * parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}) * * @param entityClass * the type * @param genericType * the generic type * @return true, if this MessageBodyReader supports the given type, false, * if not. * @see MessageBodyReader#supportsRead(Class, Type) */ public boolean supportsRead(Class entityClass, Type genericType) { if (entityClass == null) { return false; } if (genericType == null) { // LATER use Type instead of Class } if (this.genericMbrType == null) { return false; } return this.genericMbrType.isAssignableFrom(entityClass); } /** * Checks, if this MessageBodyReader supports the given MediaType. * * @param mediaType */ public boolean supportsRead(MediaType mediaType) { boolean result = false; for (int i = 0; !result && i < getConsumedMimes().size(); i++) { result = getConsumedMimes().get(i).isCompatible(mediaType) || (mediaType == null); } return result; } /** * Checks, if the wrapped MessageBodyWriter supports at least one of the * requested {@link MediaType}s. * * @param mediaTypes * the {@link MediaType}s * @return true, if at least one of the requested {@link MediaType}s is * supported, otherwise false. */ public boolean supportsWrite(Iterable mediaTypes) { for (final MediaType produced : getProducedMimes()) { for (final MediaType requested : mediaTypes) { if (requested.isCompatible(produced)) { return true; } } } return false; } public boolean supportsWrite(javax.ws.rs.core.MediaType requested) { return this.supportsWrite(Converter.toRestletMediaType(requested)); } /** * Checks, if the wrapped MessageBodyWriter supports at least one of the * requested {@link MediaType}s. * * @param requested * the requested {@link MediaType}s * @return true, if at least one of the requested {@link MediaType}s is * supported, otherwise false. */ public boolean supportsWrite(MediaType requested) { for (final MediaType produced : getProducedMimes()) { if (requested.isCompatible(produced)) { return true; } } return false; } @Override public final String toString() { return this.getClassName(); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ExtensionBackwardMapping.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ExtensionB0000664000175000017500000000661711757206350034452 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.util.Locale; import javax.ws.rs.core.MediaType; import org.restlet.data.Encoding; import org.restlet.ext.jaxrs.JaxRsApplication; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.service.MetadataService; /** * Allows a backward mapping for the extension mapping. * * @author Stephan Koops */ public class ExtensionBackwardMapping { private final MetadataService metadataService; /** * Creates a new ExtensionBackwardMapping * * @param metadataService * the metadata service of the {@link JaxRsApplication}. */ public ExtensionBackwardMapping(MetadataService metadataService) { this.metadataService = metadataService; } /** * Returns the virtual extension for the given encoding. * * @param encoding * the encoding to get the virtual file extension for. * @return the extension for the given encoding. Returns null, if no mapping * could be found. */ public String getByEncoding(String encoding) { return this.metadataService.getExtension(Encoding.valueOf(encoding)); } /** * Returns the virtual extension for the given language. * * @param language * the language to get the virtual file extension for. * @return the extension for the given language. Returns null, if no mapping * could be found. */ public String getByLanguage(Locale language) { return this.metadataService .getExtension(Converter.toLanguage(language)); } /** * Returns the virtual extension for the given {@link MediaType}. * * @param mediaType * the JAX-RS media type to get the virtual file extension for. * @return the extension for the given {@link MediaType}. Returns null, if * no mapping could be found. */ public String getByMediaType(MediaType mediaType) { org.restlet.data.MediaType restletMediaType; restletMediaType = Converter.toRestletMediaType(mediaType); return this.metadataService.getExtension(restletMediaType); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ContextResolver.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ContextRes0000664000175000017500000000375611757206350034473 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import javax.ws.rs.core.MediaType; /** * Wrapper for an initialized JAX-RS {@link javax.ws.rs.ext.ContextResolver}. * * @author Stephan Koops */ public interface ContextResolver { /** * Returns the wrapped ContextResolver * * @return the wrapped ContextResolver */ public javax.ws.rs.ext.ContextResolver getContextResolver(); /** * Checks, if the wrapped ContextResolver supports the given * {@link MediaType}. * * @param mediaType * the {@link MediaType} to check for support. * @return true, if the requested {@link MediaType} is supported, otherwise * false. */ public boolean supportsWrite(MediaType mediaType); } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReaderSet.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBod0000664000175000017500000000413111757206350034372 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import org.restlet.data.MediaType; /** * Contains a List of wrapped {@link javax.ws.rs.ext.MessageBodyReader}s. * * @author Stephan Koops */ public interface MessageBodyReaderSet { /** * Returns the best {@link MessageBodyReader} in this Set. * * @param paramType * @param genericType * @param annotations * @param mediaType * The {@link MediaType}, that should be supported. * * @return the {@link MessageBodyReader}, that best matches the given * criteria, or null if no matching MessageBodyReader could be * found. */ public MessageBodyReader getBestReader(Class paramType, Type genericType, Annotation[] annotations, MediaType mediaType); } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/PerRequestProviderWrapper.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/PerRequest0000664000175000017500000004125111757206350034464 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Providers; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertCookieParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertHeaderParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertMatrixParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertPathParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertQueryParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalConstrParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.MissingConstructorException; import org.restlet.ext.jaxrs.internal.exceptions.NoMessageBodyReaderException; import org.restlet.ext.jaxrs.internal.exceptions.ProviderNotInitializableException; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList; /** * @author Stephan Koops */ class PerRequestProviderWrapper extends AbstractProviderWrapper { /** * Returns a new instance of the wrapped provider. * * @return A new instance of the wrapped provider. * @throws IllegalArgumentException * @throws InvocationTargetException * if the constructor throws an Throwable * @throws InstantiateException * @throws MissingAnnotationException * @throws WebApplicationException * @throws IllegalConstrParamTypeException * if one of the fields or bean setters annotated with @ * {@link Context} has a type that must not be annotated with * @{@link Context}. * @throws IllegalPathParamTypeException * @throws MissingConstructorException */ private Object createInstance() throws IllegalArgumentException, InvocationTargetException, InstantiateException, MissingAnnotationException, WebApplicationException, IllegalConstrParamTypeException, IllegalPathParamTypeException, MissingConstructorException { Util.checkClassConcrete(jaxRsProviderClass, "provider"); if (objectFactory != null) { Object jaxRsProvider; jaxRsProvider = objectFactory.getInstance(jaxRsProviderClass); if (jaxRsProvider != null) { return jaxRsProvider; } } final Constructor providerConstructor = WrapperUtil .findJaxRsConstructor(jaxRsProviderClass, "provider"); ParameterList parameters; try { parameters = new ParameterList(providerConstructor, tlContext, false, allProviders, extensionBackwardMapping, false, logger, true); } catch (IllegalTypeException ite) { throw new IllegalConstrParamTypeException(ite); } try { final Object[] args = parameters.get(); return WrapperUtil.createInstance(providerConstructor, args); } catch (NoMessageBodyReaderException e) { // should be not possible here throw new IllegalArgumentException( "Could not instantiate the Provider, class " + jaxRsProviderClass.getName(), e); } catch (ConvertRepresentationException e) { // should be not possible here throw new IllegalArgumentException( "Could not instantiate the Provider, class " + jaxRsProviderClass.getName(), e); } catch (ConvertHeaderParamException e) { // should be not possible here throw new IllegalArgumentException( "Could not instantiate the Provider, class " + jaxRsProviderClass.getName(), e); } catch (ConvertPathParamException e) { // should be not possible here throw new IllegalArgumentException( "Could not instantiate the Provider, class " + jaxRsProviderClass.getName(), e); } catch (ConvertMatrixParamException e) { // should be not possible here throw new IllegalArgumentException( "Could not instantiate the Provider, class " + jaxRsProviderClass.getName(), e); } catch (ConvertQueryParamException e) { // should be not possible here throw new IllegalArgumentException( "Could not instantiate the Provider, class " + jaxRsProviderClass.getName(), e); } catch (ConvertCookieParamException e) { // should be not possible here throw new IllegalArgumentException( "Could not instantiate the Provider, class " + jaxRsProviderClass.getName(), e); } } private final Class jaxRsProviderClass; private final ObjectFactory objectFactory; private final ThreadLocalizedContext tlContext; private final JaxRsProviders allProviders; private final ExtensionBackwardMapping extensionBackwardMapping; private final Logger logger; /** * Creates a new wrapper for a Provider and initializes the provider. If the * given class is not a provider, an {@link IllegalArgumentException} is * thrown. * * @param jaxRsProviderClass * the JAX-RS provider class. * @param objectFactory * The object factory is responsible for the provider * instantiation, if given. * @param tlContext * The tread local wrapped call context * @param allProviders * all available {@link ContextResolver}s. * @param extensionBackwardMapping * the extension backward mapping * @param logger * the logger to use * @throws IllegalArgumentException * @throws InvocationTargetException * @throws MissingConstructorException * @throws InstantiateException * @throws MissingAnnotationException * @throws WebApplicationException * @throws IllegalConstrParamTypeException * @throws IllegalPathParamTypeException */ public PerRequestProviderWrapper(final Class jaxRsProviderClass, final ObjectFactory objectFactory, final ThreadLocalizedContext tlContext, final JaxRsProviders allProviders, final ExtensionBackwardMapping extensionBackwardMapping, final Logger logger) throws IllegalArgumentException, InvocationTargetException, MissingConstructorException, InstantiateException, MissingAnnotationException, WebApplicationException, IllegalConstrParamTypeException, IllegalPathParamTypeException { super(jaxRsProviderClass); this.jaxRsProviderClass = jaxRsProviderClass; this.objectFactory = objectFactory; this.tlContext = tlContext; this.allProviders = allProviders; this.extensionBackwardMapping = extensionBackwardMapping; this.logger = logger; createInstance(); // test, if it works. // If not, the provider class is not useable. } @Override public final boolean equals(Object otherProvider) { if (this == otherProvider) { return true; } if (!(otherProvider instanceof PerRequestProviderWrapper)) { return false; } return this.jaxRsProviderClass .equals(((PerRequestProviderWrapper) otherProvider).jaxRsProviderClass); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getClassName() */ @Override public String getClassName() { return this.jaxRsProviderClass.getName(); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getExcMapperType() */ public Class getExcMapperType() { return Util.getGenericClass(this.jaxRsProviderClass, ExceptionMapper.class); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedCtxResolver() */ public ContextResolver getInitializedCtxResolver() throws ProviderNotInitializableException { return new SingletonProvider(instantiateAndInitialize(), logger); } /** * Instantiates the provider class, initializes the instance and returns it * unwrapped. * * @throws ProviderNotInitializableException * @throws WebApplicationException */ private Object instantiateAndInitialize() throws ProviderNotInitializableException { Object jaxRsProvider; try { jaxRsProvider = createInstance(); } catch (IllegalConstrParamTypeException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } catch (IllegalPathParamTypeException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } catch (IllegalArgumentException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } catch (WebApplicationException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } catch (MissingAnnotationException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } catch (MissingConstructorException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } catch (InvocationTargetException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } catch (InstantiateException e) { throw new ImplementationException( "The provider could not be instantiated, but this could not be here", e); } try { initProvider(jaxRsProvider, tlContext, allProviders, extensionBackwardMapping); } catch (IllegalFieldTypeException e) { logger.log(Level.WARNING, "The provider " + this.getClassName() + " could not be initialized and so it could not be used", e); throw new ProviderNotInitializableException(); } catch (IllegalBeanSetterTypeException e) { logger.log(Level.WARNING, "The provider " + this.getClassName() + " could not be initialized and so it could not be used", e); throw new ProviderNotInitializableException(); } catch (InjectException e) { logger.log(Level.WARNING, "The provider " + this.getClassName() + " could not be initialized and so it could not be used", e); throw new ProviderNotInitializableException(); } catch (InvocationTargetException e) { logger.log(Level.WARNING, "The provider " + this.getClassName() + " could not be initialized and so it could not be used", e); throw new ProviderNotInitializableException(); } return jaxRsProvider; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedExcMapper() */ @SuppressWarnings("unchecked") public ExceptionMapper getInitializedExcMapper() throws ProviderNotInitializableException { return (ExceptionMapper) instantiateAndInitialize(); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedReader() */ public org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyReader getInitializedReader() throws ProviderNotInitializableException { return new SingletonProvider(instantiateAndInitialize(), logger); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedWriter() */ public org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriter getInitializedWriter() throws ProviderNotInitializableException { return new SingletonProvider(instantiateAndInitialize(), logger); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#hashCode() */ @Override public int hashCode() { return this.jaxRsProviderClass.hashCode(); } /** * This method does nothing in this class. * * @see ProviderWrapper#initAtAppStartUp(ThreadLocalizedContext, Providers, * ExtensionBackwardMapping) */ public void initAtAppStartUp(ThreadLocalizedContext tlContext, Providers allProviders, ExtensionBackwardMapping extensionBackwardMapping) throws InjectException, InvocationTargetException, IllegalTypeException { // nothing to do here } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#isContextResolver() */ @Override public boolean isContextResolver() { return Util.doesImplement(jaxRsProviderClass, javax.ws.rs.ext.ContextResolver.class); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#isExceptionMapper() */ @Override public boolean isExceptionMapper() { return Util.doesImplement(jaxRsProviderClass, javax.ws.rs.ext.ExceptionMapper.class); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#isReader() */ @Override public boolean isReader() { return Util.doesImplement(jaxRsProviderClass, javax.ws.rs.ext.MessageBodyReader.class); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#isWriter() */ @Override public boolean isWriter() { return Util.doesImplement(jaxRsProviderClass, javax.ws.rs.ext.MessageBodyWriter.class); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriter.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBod0000664000175000017500000001302211757206350034371 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; import org.restlet.data.MediaType; /** * Interface to access a wrapped an initialized * {@link javax.ws.rs.ext.MessageBodyWriter} * * @author Stephan Koops * @see javax.ws.rs.ext.MessageBodyWriter */ public interface MessageBodyWriter { /** * * @param type * @param genericType * @param annotations * @param mediaType * The JAX-RS MediaType * @return true, if the wrapped writer could write an object of the given * class with the given annotations and media type. * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(Class, Type, * Annotation[]) */ public boolean isWriteable(Class type, Type genericType, Annotation annotations[], javax.ws.rs.core.MediaType mediaType); /** * Called before writeTo to ascertain the length in bytes of * the serialized form of t. A non-negative return value is * used in a HTTP Content-Length header. * * @param t * the instance to write * @param type * @param genericType * @param annotations * @param mediaType * The Restlet MediaType * @return length in bytes or -1 if the length cannot be determined in * advance * @see javax.ws.rs.ext.MessageBodyWriter#getSize(Object, Class, Type, * Annotation[], javax.ws.rs.core.MediaType) */ public long getSize(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); /** * @param object * @param type * @param genericType * @param annotations * @param mediaType * The Restlet MediaType * @param httpHeaders * @param entityStream * @throws IOException * @throws WebApplicationException * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(Object, Class, Type, * Annotation[], javax.ws.rs.core.MediaType, MultivaluedMap, * OutputStream) */ public void writeTo(Object object, Class type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException; /** * Returns the JAX-RS {@link javax.ws.rs.ext.MessageBodyWriter}. * * @return the JAX-RS MessageBodyWriter */ public javax.ws.rs.ext.MessageBodyWriter getJaxRsWriter(); /** * Returns the list of produced {@link MediaType}s of the wrapped * {@link javax.ws.rs.ext.MessageBodyWriter}. * * @return List of produced Restlet {@link MediaType}s. If the entity * provider is not annotated with @ {@link javax.ws.rs.Produces} * , '*/*' is returned. */ public List getProducedMimes(); /** * Checks, if the wrapped MessageBodyWriter supports at least one of the * given {@link MediaType}s. * * @param mediaTypes * the Restlet {@link MediaType}s * @return true, if at least one of the requested {@link MediaType}s is * supported, otherwise false. */ public boolean supportsWrite(Iterable mediaTypes); /** * Checks, if the wrapped MessageBodyWriter supports the given * {@link MediaType}. * * @param mediaType * the Restlet {@link MediaType} * @return true, if the requested {@link MediaType} is supported, otherwise * false. */ public boolean supportsWrite(MediaType mediaType); /** * Checks, if this message body writer supports the given type (by the type * parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}) * * @param entityClass * the type * @param genericType * the generic type * @return true, if this MessageBodyWriter supports the given type, false, * if not. */ public boolean supportsWrite(Class entityClass, Type genericType); } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/JaxRsProviders.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/JaxRsProvi0000664000175000017500000005664311757206350034447 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Providers; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalConstrParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.MissingConstructorException; import org.restlet.ext.jaxrs.internal.exceptions.ProviderNotInitializableException; import org.restlet.ext.jaxrs.internal.util.Converter; /** * Contains the entity providers and has some methods to pick the wished out. * * @author Stephan Koops */ public class JaxRsProviders implements javax.ws.rs.ext.Providers, MessageBodyReaderSet { private static final Logger localLogger = Context.getCurrentLogger(); /** * Returns the generic class of the given {@link ContextResolver} class. */ private static Class getCtxResGenClass(Class crClaz) { Type[] crIfTypes = crClaz.getGenericInterfaces(); for (Type crIfType : crIfTypes) { if (!(crIfType instanceof ParameterizedType)) continue; Type t = ((ParameterizedType) crIfType).getActualTypeArguments()[0]; if (!(t instanceof Class)) continue; return (Class) t; } return null; } private final Set all; /** * This {@link Set} contains all available * {@link javax.ws.rs.ext.ContextResolver}s.
* This field is final, because it is shared with other objects. */ private final Collection contextResolvers; private final Map, ProviderWrapper> excMappers; private final ExtensionBackwardMapping extensionBackwardMapping; private final Logger logger; private final List messageBodyReaderWrappers; private final List messageBodyWriterWrappers; private volatile ObjectFactory objectFactory; private final ThreadLocalizedContext tlContext; /** * Creates a new JaxRsProviders. * * @param objectFactory * @param tlContext * @param extensionBackwardMapping * @param logger */ public JaxRsProviders(ObjectFactory objectFactory, ThreadLocalizedContext tlContext, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) { this.all = new CopyOnWriteArraySet(); this.messageBodyReaderWrappers = new CopyOnWriteArrayList(); this.messageBodyWriterWrappers = new CopyOnWriteArrayList(); this.contextResolvers = new CopyOnWriteArraySet(); this.excMappers = new ConcurrentHashMap, ProviderWrapper>(); this.objectFactory = objectFactory; this.tlContext = tlContext; this.extensionBackwardMapping = extensionBackwardMapping; this.logger = logger; } /** * Adds the given provider to this JaxRsProviders. If the Provider is not an * entity provider, it doesn't matter. * * @param provider * @param defaultProvider */ private void add(ProviderWrapper provider, boolean defaultProvider) { if (provider.isWriter()) { if (defaultProvider) this.messageBodyWriterWrappers.add(provider); else this.messageBodyWriterWrappers.add(0, provider); } if (provider.isReader()) { if (defaultProvider) this.messageBodyReaderWrappers.add(provider); else this.messageBodyReaderWrappers.add(0, provider); } if (provider.isContextResolver()) this.contextResolvers.add(provider); if (provider.isExceptionMapper()) this.addExcMapper(provider); this.all.add(provider); } /** * @param jaxRsProviderClass * @return true if the provider was added, or false if not */ public boolean addClass(Class jaxRsProviderClass) { ProviderWrapper provider; try { provider = new PerRequestProviderWrapper(jaxRsProviderClass, objectFactory, tlContext, this, extensionBackwardMapping, this.logger); } catch (IllegalParamTypeException e) { String msg = "Ignore provider " + jaxRsProviderClass.getName() + ": Could not instantiate class " + jaxRsProviderClass.getName(); logger.log(Level.WARNING, msg, e); return false; } catch (InstantiateException e) { String msg = "Ignore provider " + jaxRsProviderClass.getName() + ": Could not instantiate class " + jaxRsProviderClass.getName(); logger.log(Level.WARNING, msg, e); return false; } catch (MissingAnnotationException e) { String msg = "Ignore provider " + jaxRsProviderClass.getName() + ": Could not instantiate class " + jaxRsProviderClass.getName() + ", because " + e.getMessage(); logger.log(Level.WARNING, msg); return false; } catch (InvocationTargetException ite) { String msg = "Ignore provider " + jaxRsProviderClass.getName() + ", because an exception occured while instantiating"; logger.log(Level.WARNING, msg, ite); return false; } catch (IllegalArgumentException iae) { String msg = "Ignore provider " + jaxRsProviderClass.getName() + ", because it could not be instantiated"; logger.log(Level.WARNING, msg, iae); return false; } catch (MissingConstructorException mce) { String msg = "Ignore provider " + jaxRsProviderClass.getName() + ", because no valid constructor was found: " + mce.getMessage(); logger.warning(msg); return false; } catch (IllegalConstrParamTypeException e) { String msg = "Ignore provider " + jaxRsProviderClass.getName() + ", because no valid constructor was found: " + e.getMessage(); logger.warning(msg); return false; } this.add(provider, false); return true; } /** * Adds the given {@link ExceptionMapper} to this ExceptionMappers. * * @param excMapper * @throws NullPointerException * if null is given */ @SuppressWarnings("unchecked") private void addExcMapper(ProviderWrapper excMapperWrapper) { Class excClass = (Class) excMapperWrapper .getExcMapperType(); excMappers.put(excClass, excMapperWrapper); } /** * @param jaxRsProviderObject * @param defaultProvider * @return true if the object was added, false if not. * @throws WebApplicationException */ public boolean addSingleton(Object jaxRsProviderObject, boolean defaultProvider) throws WebApplicationException { ProviderWrapper provider; try { provider = new SingletonProvider(jaxRsProviderObject, this.logger); } catch (IllegalArgumentException iae) { String msg = "Ignore provider " + jaxRsProviderObject.getClass().getName() + ", because it could not be instantiated"; logger.log(Level.WARNING, msg, iae); return false; } this.add(provider, defaultProvider); return true; } /** * converts the cause of the given InvocationTargetException to a * {@link Response}, if an {@link ExceptionMapper} could be found.
* Otherwise this method returns an Response with an internal server error. * * @param cause * the thrown exception (was wrapped by an * {@link InvocationTargetException}) * @return the created Response * @throws NullPointerException * if null is given * @see ExceptionMapper#toResponse(Object) */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Response convert(Throwable cause) { ExceptionMapper mapper = getExceptionMapper(cause.getClass()); if (mapper == null) { if (cause instanceof RuntimeException) throw (RuntimeException) cause; if (cause instanceof Error) throw (Error) cause; String entity = "No ExceptionMapper was found, but must be found"; return Response.serverError().entity(entity) .type(javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE).build(); } Response response = mapper.toResponse(cause); if (response == null) { String message = "The ExceptionMapper returned null"; localLogger.log(Level.WARNING, message); return Response.serverError().entity(message).build(); } return response; } /** * Returns the {@link MessageBodyReader}, that best matches the given * criteria. * * @param paramType * @param genericType * @param annotations * @param mediaType * The {@link MediaType}, that should be supported. * @return the {@link MessageBodyReader}, that best matches the given * criteria, or null if no matching MessageBodyReader could be * found. * @see MessageBodyReaderSet#getBestReader(Class, Type, Annotation[], * MediaType) */ public MessageBodyReader getBestReader(Class paramType, Type genericType, Annotation[] annotations, MediaType mediaType) { // NICE optimization: may be cached for speed. for (ProviderWrapper mbrw : this.messageBodyReaderWrappers) { if (mbrw.supportsRead(mediaType)) { MessageBodyReader mbr; try { mbr = mbrw.getInitializedReader(); } catch (ProviderNotInitializableException e) { continue; } catch (WebApplicationException e) { continue; } if (mbr.isReadable(paramType, genericType, annotations, Converter.toJaxRsMediaType(mediaType))) return mbr; } } return null; } /** * Get a context resolver for a particular type of context and media type. * The set of resolvers is first filtered by comparing the supplied value of * {@code mediaType} with the value of each resolver's * {@link javax.ws.rs.Produces}, ensuring the generic type of the context * resolver is assignable to the supplied value of {@code contextType}, and * eliminating those that do not match. If only one resolver matches the * criteria then it is returned. If more than one resolver matches then the * list of matching resolvers is ordered with those with the best matching * values of {@link javax.ws.rs.Produces} (x/y > x/* > */*) sorted * first. A proxy is returned that delegates calls to * {@link ContextResolver#getContext(java.lang.Class)} to each matching * context resolver in order and returns the first non-null value it obtains * or null if all matching context resolvers return null. * * @param contextType * the class of context desired * @param mediaType * the media type of data for which a context is required. * @return a matching context resolver instance or null if no matching * context providers are found. * @see Providers#getContextResolver(Class, javax.ws.rs.core.MediaType) */ @SuppressWarnings("unchecked") public javax.ws.rs.ext.ContextResolver getContextResolver( Class contextType, javax.ws.rs.core.MediaType mediaType) { // TODO refactor JaxRsProviders.getContextResolver() // LATER test JaxRsProviders.getContextResolver for (ProviderWrapper crWrapper : this.contextResolvers) { final javax.ws.rs.ext.ContextResolver cr; try { cr = crWrapper.getInitializedCtxResolver().getContextResolver(); } catch (ProviderNotInitializableException e1) { continue; } catch (WebApplicationException e1) { continue; } if (cr == null) { // TODO this is a little bit hacky. continue; } final Class crClaz = cr.getClass(); final Class genClass = JaxRsProviders.getCtxResGenClass(crClaz); if (genClass == null || !genClass.equals(contextType)) { continue; } if (!crWrapper.supportsWrite(mediaType)) { continue; } try { Method getContext = crClaz.getMethod("getContext", Class.class); if (getContext.getReturnType().equals(contextType)) { return (javax.ws.rs.ext.ContextResolver) cr; } } catch (SecurityException e) { throw new RuntimeException( "sorry, the method getContext(Class) of ContextResolver " + crClaz + " is not accessible"); } catch (NoSuchMethodException e) { throw new RuntimeException( "The ContextResolver " + crClaz + " is not valid, because it has no method getContext(Class)"); } } return null; } /** * @param causeClass * @return the ExceptionMapper for the given Throwable class, or null, if * none was found. */ @SuppressWarnings("unchecked") public ExceptionMapper getExceptionMapper( Class causeClass) { if (causeClass == null) throw new ImplementationException( "The call of an exception mapper with null is not allowed"); ProviderWrapper mapperWrapper; for (;;) { mapperWrapper = this.excMappers.get(causeClass); if (mapperWrapper != null) { try { return (ExceptionMapper) mapperWrapper .getInitializedExcMapper(); } catch (ProviderNotInitializableException e) { localLogger .info("The exception mapper for " + causeClass + " could not be initialized, so it can#t be used. Will look for the next exception mapper in hierarchy."); // look for next } catch (WebApplicationException e) { localLogger .log(Level.INFO, "The exception mapper for " + causeClass + " could not be initialized, so it can#t be used. Will look for the next exception mapper in hierarchy.", e); // look for next } } Class superclass = causeClass.getSuperclass(); if (superclass == null || superclass.equals(Object.class)) return null; causeClass = (Class) superclass; } // disabled caching, because adding of new ExceptionMappers could // cause trouble. // this.excMappers.put(superclass, mapper); } /** * @see javax.ws.rs.ext.Providers#getMessageBodyReader(Class, Type, * Annotation[], javax.ws.rs.core.MediaType) */ @SuppressWarnings({ "unchecked", "rawtypes" }) public javax.ws.rs.ext.MessageBodyReader getMessageBodyReader( Class type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) { MediaType restletMediaType = Converter.toRestletMediaType(mediaType); final MessageBodyReader mbr; mbr = getBestReader(type, genericType, annotations, restletMediaType); return (javax.ws.rs.ext.MessageBodyReader) mbr.getJaxRsReader(); } /** * @see javax.ws.rs.ext.Providers#getMessageBodyWriter(Class, Type, * Annotation[], javax.ws.rs.core.MediaType) */ @SuppressWarnings({ "unchecked" }) public javax.ws.rs.ext.MessageBodyWriter getMessageBodyWriter( Class type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) { MediaType restletMediaType = Converter.toRestletMediaType(mediaType); for (ProviderWrapper mbww : this.messageBodyWriterWrappers) { if (mbww.supportsWrite(restletMediaType)) { MessageBodyWriter mbw; try { mbw = mbww.getInitializedWriter(); } catch (ProviderNotInitializableException e) { continue; } catch (WebApplicationException e) { continue; } if (mbw.isWriteable(type, genericType, annotations, mediaType)) return (javax.ws.rs.ext.MessageBodyWriter) mbw .getJaxRsWriter(); } } return null; } /** * Init all providers. If an error for one provider occurs, this provider is * ignored and the next provider initialized. * * @param tlContext * @param extensionBackwardMapping */ public void initAll() { for (final ProviderWrapper provider : new ArrayList( this.all)) { try { provider.initAtAppStartUp(tlContext, this, extensionBackwardMapping); } catch (InjectException e) { localLogger.log(Level.WARNING, "The provider " + provider.getClassName() + " could not be used", e); this.remove(provider); } catch (IllegalTypeException e) { localLogger.log(Level.WARNING, "The provider " + provider.getClassName() + " could not be used", e); this.remove(provider); } catch (InvocationTargetException e) { localLogger.log(Level.WARNING, "The provider " + provider.getClassName() + " could not be used", e.getCause()); this.remove(provider); } catch (SecurityException e) { localLogger.log(Level.WARNING, "The provider " + provider.getClassName() + " could not be used", e.getCause()); this.remove(provider); } } } /** * @param provider */ private void remove(ProviderWrapper provider) { this.all.remove(provider); this.contextResolvers.remove(provider); this.messageBodyReaderWrappers.remove(provider); this.messageBodyWriterWrappers.remove(provider); Iterator, ProviderWrapper>> excMapperEntryIter = this.excMappers .entrySet().iterator(); while (excMapperEntryIter.hasNext()) { final Map.Entry, ProviderWrapper> excMapperEntry; excMapperEntry = excMapperEntryIter.next(); ProviderWrapper providerWrapper = excMapperEntry.getValue(); if (providerWrapper.equals(provider)) excMapperEntryIter.remove(); } } /** * Returns a Collection of {@link MessageBodyWriter}s, which generic type * supports the given entityClass. * * @param entityClass * @param genericType * may be null * @param annotations * @param mediaType * @return a sub set of message body writers * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(Class, Type, * Annotation[]) */ public MessageBodyWriterSubSet writerSubSet(Class entityClass, Type genericType) { final List mbws = new ArrayList(); for (ProviderWrapper mbww : this.messageBodyWriterWrappers) { MessageBodyWriter mbw; try { mbw = mbww.getInitializedWriter(); } catch (ProviderNotInitializableException e) { continue; } if (mbw.supportsWrite(entityClass, genericType)) { mbws.add(mbw); } } // NICE optimization: may be cached for speed. return new MessageBodyWriterSubSet(mbws, entityClass, genericType); } /** * Sets the ObjectFactory * * @param objectFactory */ public void setObjectFactory(ObjectFactory objectFactory) { this.objectFactory = objectFactory; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ProviderWrapper.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ProviderWr0000664000175000017500000001636011757206350034473 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.lang.reflect.InvocationTargetException; import java.util.List; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Providers; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.ProviderNotInitializableException; /** * Wraps a JAX-RS provider, see chapter 4 of JAX-RS specification. * * @author Stephan Koops * @see javax.ws.rs.ext.Provider */ public interface ProviderWrapper { public abstract boolean equals(Object otherProvider); /** * @return the JAX-RS provider class name */ abstract String getClassName(); /** * Returns the list of produced {@link MediaType}s of the wrapped * {@link javax.ws.rs.ext.MessageBodyWriter}. * * @return List of produced {@link MediaType}s. */ List getConsumedMimes(); /** * @return an initialized {@link javax.ws.rs.ext.ContextResolver} * @throws ProviderNotInitializableException */ abstract ContextResolver getInitializedCtxResolver() throws ProviderNotInitializableException; /** * Beispiele: *
    *
  • ExceptionMapper<IllegalArgumentException> -> * IllegalArgumentException
  • *
  • MessageBodyReader<Integer> -> Integer
  • *
* * @return the type the wrapped exception mapper could map. */ public Class getExcMapperType(); /** * @return the initialized exception mapper * @throws ProviderNotInitializableException */ abstract ExceptionMapper getInitializedExcMapper() throws ProviderNotInitializableException; /** * @return an initialized reader * @throws ProviderNotInitializableException */ abstract MessageBodyReader getInitializedReader() throws ProviderNotInitializableException; // LATER before a call of a message body reader or writer the current state // of the matched resources and URIs must be stored for the current thread. /** * @return an initialized writer * @throws ProviderNotInitializableException */ abstract MessageBodyWriter getInitializedWriter() throws ProviderNotInitializableException; /** * Returns the list of produced {@link MediaType}s of the wrapped * {@link javax.ws.rs.ext.MessageBodyWriter}. * * @return List of produced {@link MediaType}s. If the entity provider is * not annotated with @ {@link javax.ws.rs.Produces}, * '*/*' is returned. */ List getProducedMimes(); public int hashCode(); /** * Initializes this entity provider at start up. If the life cycle is * instantiation per-request, nothing happens in this method. * * @param tlContext * @param allProviders * @param extensionBackwardMapping * @throws InjectException * @throws InvocationTargetException * @throws IllegalTypeException */ public void initAtAppStartUp(ThreadLocalizedContext tlContext, Providers allProviders, ExtensionBackwardMapping extensionBackwardMapping) throws InjectException, InvocationTargetException, IllegalTypeException; /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.ContextResolver}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.ContextResolver}, otherwise false. */ abstract boolean isContextResolver(); /** * Checks, if this provider represents an {@link ExceptionMapper}. * * @return true, if this provider is an {@link ExceptionMapper}, or false if * not. */ abstract boolean isExceptionMapper(); /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyReader}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyReader}, otherwise false. */ abstract boolean isReader(); /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyWriter}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyWriter}, otherwise false. */ abstract boolean isWriter(); /** * Checks, if this MessageBodyReader supports the given MediaType. * * @param mediaType * @return true, if the wrapped {@link javax.ws.rs.ext.MessageBodyReader} * supports the read for the given media type. */ public boolean supportsRead(MediaType mediaType); /** * Checks, if the wrapped MessageBodyWriter supports at least one of the * requested {@link MediaType}s. * * @param mediaTypes * the {@link MediaType}s * @return true, if at least one of the requested {@link MediaType}s is * supported, otherwise false. */ public boolean supportsWrite(Iterable mediaTypes); /** * Checks, if the wrapped MessageBodyWriter supports at least one of the * requested {@link MediaType}s. * * @param requested * the requested {@link MediaType}s * @return true, if at least one of the requested {@link MediaType}s is * supported, otherwise false. */ public boolean supportsWrite(javax.ws.rs.core.MediaType requested); /** * Checks, if the wrapped MessageBodyWriter supports at least one of the * requested {@link MediaType}s. * * @param requested * the requested {@link MediaType}s * @return true, if at least one of the requested {@link MediaType}s is * supported, otherwise false. */ public boolean supportsWrite(MediaType requested); } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/SingletonProvider.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/SingletonP0000664000175000017500000003775711757206350034467 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Providers; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.Util; /** * @author Stephan * */ public class SingletonProvider extends AbstractProviderWrapper implements MessageBodyReader, MessageBodyWriter, ContextResolver { /** * the {@link ContextResolver}, if this providers is a * {@link ContextResolver} */ private final javax.ws.rs.ext.ContextResolver contextResolver; private final javax.ws.rs.ext.ExceptionMapper excMapper; private final Object jaxRsProvider; /** * The JAX-RS {@link javax.ws.rs.ext.MessageBodyReader} this wrapper * represent. */ private final javax.ws.rs.ext.MessageBodyReader reader; private final javax.ws.rs.ext.MessageBodyWriter writer; /** * Creates a new wrapper for a ProviderWrapper and initializes the provider. * If the given class is not a provider, an {@link IllegalArgumentException} * is thrown. * * @param jaxRsProvider * the JAX-RS provider class. * @param logger * the logger to use. * @throws IllegalArgumentException * if the class is not a valid provider, may not be instantiated * or what ever. * @throws WebApplicationException * @see javax.ws.rs.ext.MessageBodyReader * @see javax.ws.rs.ext.MessageBodyWriter * @see javax.ws.rs.ext.ContextResolver */ /** * @param jaxRsProvider * @param logger * needed, if the provider implements no provider interface * @throws IllegalArgumentException * @throws WebApplicationException */ @SuppressWarnings("unchecked") public SingletonProvider(Object jaxRsProvider, Logger logger) throws IllegalArgumentException, WebApplicationException { super((jaxRsProvider == null) ? null : jaxRsProvider.getClass()); if (jaxRsProvider == null) { throw new IllegalArgumentException( "The JAX-RS provider class must not be null"); } this.jaxRsProvider = jaxRsProvider; boolean isProvider = false; if (jaxRsProvider instanceof javax.ws.rs.ext.MessageBodyWriter) { this.writer = (javax.ws.rs.ext.MessageBodyWriter) jaxRsProvider; isProvider = true; } else { this.writer = null; } if (jaxRsProvider instanceof javax.ws.rs.ext.MessageBodyReader) { this.reader = (javax.ws.rs.ext.MessageBodyReader) jaxRsProvider; isProvider = true; } else { this.reader = null; } if (jaxRsProvider instanceof javax.ws.rs.ext.ExceptionMapper) { this.excMapper = (javax.ws.rs.ext.ExceptionMapper) jaxRsProvider; isProvider = true; } else { this.excMapper = null; } if (jaxRsProvider instanceof javax.ws.rs.ext.ContextResolver) { this.contextResolver = (javax.ws.rs.ext.ContextResolver) jaxRsProvider; isProvider = true; } else { this.contextResolver = null; } if (!isProvider) { logger.config("The provider " + jaxRsProvider.getClass() + " is neither a MessageBodyWriter nor a MessageBodyReader nor a ContextResolver nor an ExceptionMapper"); } } /** * Checks, if this MessageBodyReader could read the given type. * * @param type * @param genericType * @param annotations * @return true, if the wrapped message body reader supports reading for the * given class with the given parameters. * @see javax.ws.rs.ext.MessageBodyReader#isReadable(Class, Type, * Annotation[]) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) { try { return this.getJaxRsReader().isReadable(type, genericType, annotations, mediaType); } catch (NullPointerException e) { if (genericType == null || annotations == null) { // interpreted as not readable for the given combination return false; } throw e; } catch (IllegalArgumentException e) { if (genericType == null || annotations == null) { // interpreted as not readable for the given combination return false; } throw e; } } /** * Checks, if the given class could be written by this MessageBodyWriter. * * @param type * @param genericType * @param annotations * @return true, if the wrapped message writer reader supports writing for * the given class with the given parameters. * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(Class) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) { try { return this.getJaxRsWriter().isWriteable(type, genericType, annotations, mediaType); } catch (NullPointerException e) { if (genericType == null || annotations == null) { // interpreted as not writable for the given combination return false; } throw e; } catch (IllegalArgumentException e) { if (genericType == null || annotations == null) { // interpreted as not writable for the given combination return false; } throw e; } } @Override public final boolean equals(Object otherProvider) { if (this == otherProvider) { return true; } if (!(otherProvider instanceof SingletonProvider)) { return false; } return this.jaxRsProvider.getClass().equals( ((SingletonProvider) otherProvider).getClass()); } /** * @return the JAX-RS provider class name */ @Override public String getClassName() { return jaxRsProvider.getClass().getName(); } /** * @return the contextResolver */ public javax.ws.rs.ext.ContextResolver getContextResolver() { return this.contextResolver; } /** * Returns the {@link ExceptionMapper}, or null, if this provider is not an * {@link ExceptionMapper}. * * @return the {@link ExceptionMapper}, or null, if this provider is not an * {@link ExceptionMapper}. */ public javax.ws.rs.ext.ExceptionMapper getExcMapper() { return this.excMapper; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedReader() */ public MessageBodyReader getInitializedReader() { return this; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedWriter() */ public MessageBodyWriter getInitializedWriter() { return this; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyReader#getJaxRsReader() */ public javax.ws.rs.ext.MessageBodyReader getJaxRsReader() { return this.reader; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriter#getJaxRsWriter() */ public javax.ws.rs.ext.MessageBodyWriter getJaxRsWriter() { return this.writer; } @Override public final int hashCode() { return this.jaxRsProvider.hashCode(); } /** * * @param type * @param genericType * The generic {@link Type} to convert to. * @param annotations * the annotations of the artifact to convert to * @param mediaType * @param httpHeaders * @param entityStream * @return the read object * @throws IOException * @see javax.ws.rs.ext.MessageBodyReader#readFrom(Class, Type, * javax.ws.rs.core.MediaType, Annotation[], MultivaluedMap, * InputStream) */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, CharacterSet characterSet, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, InvocationTargetException { try { return this.getJaxRsReader().readFrom((Class) type, genericType, annotations, Converter.toJaxRsMediaType(mediaType), httpHeaders, entityStream); } catch (Throwable t) { if (t instanceof IOException) throw (IOException) t; if (t instanceof WebApplicationException) throw (WebApplicationException) t; throw new InvocationTargetException(t); } } /** * Write a type to an HTTP response. The response header map is mutable but * any changes must be made before writing to the output stream since the * headers will be flushed prior to writing the response body. * * @param genericType * The generic {@link Type} to convert to. * @param annotations * the annotations of the artifact to convert to * @param mediaType * the media type of the HTTP entity. * @param httpHeaders * a mutable map of the HTTP response headers. * @param entityStream * the {@link OutputStream} for the HTTP entity. * @param object * the object to write. * * @throws java.io.IOException * if an IO error arises * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(Object, Type, * Annotation[], javax.ws.rs.core.MediaType, MultivaluedMap, * OutputStream) */ public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { this.getJaxRsWriter().writeTo(object, type, genericType, annotations, Converter.toJaxRsMediaType(mediaType), httpHeaders, entityStream); } /** * Injects the supported dependencies into this provider and calls the * method annotated with @{@link PostConstruct}. * * @param tlContext * The thread local wrapped {@link CallContext} * @param allProviders * all providers. * @param extensionBackwardMapping * the extension backward mapping * @throws InjectException * @throws InvocationTargetException * if a bean setter throws an exception * @throws IllegalTypeException * if the given class is not valid to be annotated with @ * {@link Context}. * @see ProviderWrapper#initAtAppStartUp(ThreadLocalizedContext, Providers, * ExtensionBackwardMapping) */ public void initAtAppStartUp(ThreadLocalizedContext tlContext, Providers allProviders, ExtensionBackwardMapping extensionBackwardMapping) throws InjectException, InvocationTargetException, IllegalTypeException { initProvider(this.jaxRsProvider, tlContext, allProviders, extensionBackwardMapping); } /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.ContextResolver}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.ContextResolver}, otherwise false. */ @Override public final boolean isContextResolver() { return this.contextResolver != null; } /** * Checks, if this provider represents an {@link ExceptionMapper}. * * @return true, if this provider is an {@link ExceptionMapper}, or false if * not. */ @Override public final boolean isExceptionMapper() { return this.excMapper != null; } /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyReader}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyReader}, otherwise false. */ @Override public final boolean isReader() { return this.reader != null; } /** * Returns true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyWriter}, otherwise false. * * @return true, if this ProviderWrapper is also a * {@link javax.ws.rs.ext.MessageBodyWriter}, otherwise false. */ @Override public final boolean isWriter() { return this.writer != null; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriter#getSize(java.lang.Object, * Class, Type, Annotation[], MediaType) */ public long getSize(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return this.writer.getSize(t, type, genericType, annotations, Converter.toJaxRsMediaType(mediaType)); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedCtxResolver() */ public ContextResolver getInitializedCtxResolver() { return this; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getInitializedExcMapper() */ public ExceptionMapper getInitializedExcMapper() { return excMapper; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.provider.ProviderWrapper#getExcMapperType() */ public Class getExcMapperType() { return Util.getGenericClass(jaxRsProvider.getClass(), ExceptionMapper.class); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBod0000664000175000017500000000770511757206350034404 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.provider; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; /** * Class to wrap an initialized {@link javax.ws.rs.ext.MessageBodyReader} * * @author Stephan Koops * @see javax.ws.rs.ext.MessageBodyReader */ public interface MessageBodyReader { /** * Returns the list of produced {@link MediaType}s of the wrapped * {@link javax.ws.rs.ext.MessageBodyWriter}. * * @return List of produced {@link MediaType}s. */ public List getConsumedMimes(); /** * Returns the JAX-RS {@link javax.ws.rs.ext.MessageBodyReader}. * * @return the JAX-RS MessageBodyReader */ public javax.ws.rs.ext.MessageBodyReader getJaxRsReader(); /** * * @param type * @param genericType * @param annotations * @param mediaType * @return true, if the mapped message body reader could read to the given * class * @see {@link javax.ws.rs.ext.MessageBodyReader#isReadable(Class, Type, Annotation[])} */ public boolean isReadable(Class type, Type genericType, Annotation annotations[], javax.ws.rs.core.MediaType mediaType); /** * * @param type * @param genericType * @param annotations * @param mediaType * @param characterSet * @param httpHeaders * @param entityStream * @return the read object * @throws IOException * @throws WebApplicationException * @throws InvocationTargetException * @see {@link javax.ws.rs.ext.MessageBodyReader#readFrom(Class, Type, Annotation[], javax.ws.rs.core.MediaType, MultivaluedMap, InputStream)} */ public Object readFrom(Class type, Type genericType, Annotation annotations[], MediaType mediaType, CharacterSet characterSet, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException, InvocationTargetException; /** * Checks, if this message body reader supports the given type (by the type * parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}) * * @param entityClass * the type * @param genericType * the generic type * @return true, if this MessageBodyReader supports the given type, false, * if not. */ public boolean supportsRead(Class entityClass, Type genericType); } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/SubResourceLocator.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/SubResourceLocator.0000664000175000017500000001471111757206350034377 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertCookieParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertHeaderParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertMatrixParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertPathParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertQueryParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalMethodParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.NoMessageBodyReaderException; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; /** * A method of a resource class that is used to locate sub-resources of the * corresponding resource, see section 3.3.1. of the JAX-RS specification. * * @author Stephan Koops */ public class SubResourceLocator extends AbstractMethodWrapper implements ResourceMethodOrLocator { /** * Creates a new wrapper for the given sub resource locator. * * @param javaMethod * The Java method which creats the sub resource * @param annotatedMethod * the message containing the annotations for this sub * resource locator. * @param resourceClass * the wrapped resource class. * @param tlContext * the {@link ThreadLocalizedContext} of the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * @param jaxRsProviders * all providers * @param extensionBackwardMapping * the extension backward mapping * @param logger * @throws IllegalPathOnMethodException * @throws MissingAnnotationException * @throws IllegalArgumentException * if the annotated method is null * @throws IllegalPathParamTypeException */ SubResourceLocator(Method javaMethod, Method annotatedMethod, ResourceClass resourceClass, ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalPathOnMethodException, IllegalArgumentException, MissingAnnotationException, IllegalMethodParamTypeException, IllegalPathParamTypeException { super(javaMethod, annotatedMethod, resourceClass, tlContext, jaxRsProviders, extensionBackwardMapping, false, logger); } /** * Creates a sub resource * * @param resourceObject * the wrapped resource object. * @param resourceClasses * factory to create wrappers. * @param logger * The logger to use * @return Returns the wrapped sub resource object. * @throws InvocationTargetException * @throws NoMessageBodyReaderException * @throws WebApplicationException * @throws MissingAnnotationException * @throws InstantiateException * @throws ConvertCookieParamException * @throws ConvertQueryParamException * @throws ConvertMatrixParamException * @throws ConvertPathParamException * @throws ConvertHeaderParamException * @throws ConvertRepresentationException * @throws MissingAnnotationException * @throws IllegalArgumentException */ public ResourceObject createSubResource(ResourceObject resourceObject, ResourceClasses resourceClasses, Logger logger) throws InvocationTargetException, WebApplicationException, InstantiateException, ConvertRepresentationException, IllegalArgumentException, MissingAnnotationException { Object subResObj; try { subResObj = internalInvoke(resourceObject); } catch (IllegalArgumentException e) { throw new InstantiateException(this.executeMethod, e); } catch (IllegalAccessException e) { throw new InstantiateException(this.executeMethod, e); } if (subResObj == null) { logger .warning("The sub resource object is null. That is not allowed"); final ResponseBuilder rb = javax.ws.rs.core.Response.serverError(); rb.entity("The sub resource object is null. That is not allowed"); throw new WebApplicationException(rb.build()); } ResourceClass resourceClass; resourceClass = resourceClasses.getResourceClass(subResObj.getClass()); return new ResourceObject(subResObj, resourceClass); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceClasses.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceClasses.jav0000664000175000017500000003452211757206350034422 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalConstrParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.MissingConstructorException; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; /** * A ResourceClasses creates and caches some of the wrapper objects. * * @author Stephan Koops */ public class ResourceClasses { private final ExtensionBackwardMapping extensionBackwardMapping; private final JaxRsProviders jaxRsProviders; private final Logger logger; private final Map, ResourceClass> resourceClasses = new HashMap, ResourceClass>(); /** * This set must only changed by adding a root resource class to this * JaxRsRestlet. */ private final Set rootResourceClasses = new CopyOnWriteArraySet(); private final ThreadLocalizedContext tlContext; /** * @param tlContext * the {@link ThreadLocalizedContext} of the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * @param jaxRsProviders * @param extensionBackwardMapping * the extension backward mapping * @param logger */ public ResourceClasses(ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) { this.tlContext = tlContext; this.jaxRsProviders = jaxRsProviders; this.extensionBackwardMapping = extensionBackwardMapping; this.logger = logger; } /** * @param rootResourceClass * @return true, if the root resource class could be added, or false if not. */ public boolean addRootClass(Class rootResourceClass) { RootResourceClass newRrc; try { newRrc = this.getPerRequestRootClassWrapper(rootResourceClass); } catch (IllegalParamTypeException e) { String msg = "Ignore provider " + rootResourceClass.getName() + ": Could not instantiate class " + rootResourceClass.getName(); this.logger.log(Level.WARNING, msg, e); return false; } catch (IllegalPathOnClassException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " is annotated with an illegal path: " + e.getPath() + ". (" + e.getMessage() + ")"); return false; } catch (IllegalArgumentException e) { this.logger.log(Level.WARNING, "The root resource class " + rootResourceClass.getName() + " is not a valid root resource class: " + e.getMessage(), e); return false; } catch (MissingAnnotationException e) { this.logger.log(Level.WARNING, "The root resource class " + rootResourceClass.getName() + " is not a valid root resource class: " + e.getMessage(), e); return false; } catch (MissingConstructorException e) { this.logger .warning("The root resource class " + rootResourceClass.getName() + " has no valid constructor"); return false; } catch (IllegalConstrParamTypeException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " has an invalid parameter: " + e.getMessage()); return false; } catch (IllegalBeanSetterTypeException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " has an bean setter with an illegal type: " + e.getMessage()); return false; } catch (IllegalFieldTypeException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " has an illegal annotated and typed field: " + e.getMessage()); return false; } PathRegExp uriTempl = newRrc.getPathRegExp(); for (RootResourceClass rrc : this.rootResourceClasses) { if (rrc.getJaxRsClass().equals(rootResourceClass)) { return true; } if (rrc.getPathRegExp().equals(uriTempl)) { this.logger .warning("There is already a root resource class with path " + uriTempl.getPathTemplateEnc()); return false; } } rootResourceClasses.add(newRrc); return true; } /** * * @param jaxRsRootObject * @return true, if the root resource class could be added, or false if not. */ public boolean addRootSingleton(Object jaxRsRootObject) { Class rootResourceClass = jaxRsRootObject.getClass(); RootResourceClass newRrc; try { newRrc = this.getSingletonRootClassWrapper(jaxRsRootObject); } catch (IllegalParamTypeException e) { String msg = "Ignore provider " + rootResourceClass.getName() + ": Could not instantiate class " + rootResourceClass.getName(); this.logger.log(Level.WARNING, msg, e); return false; } catch (IllegalPathOnClassException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " is annotated with an illegal path: " + e.getPath() + ". (" + e.getMessage() + ")"); return false; } catch (IllegalArgumentException e) { this.logger.log(Level.WARNING, "The root resource class " + rootResourceClass.getName() + " is not a valid root resource class: " + e.getMessage(), e); return false; } catch (MissingAnnotationException e) { this.logger.log(Level.WARNING, "The root resource class " + rootResourceClass.getName() + " is not a valid root resource class: " + e.getMessage(), e); return false; } catch (MissingConstructorException e) { this.logger .warning("The root resource class " + rootResourceClass.getName() + " has no valid constructor"); return false; } catch (IllegalConstrParamTypeException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " has an invalid parameter: " + e.getMessage()); return false; } catch (IllegalBeanSetterTypeException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " has an bean setter with an illegal type: " + e.getMessage()); return false; } catch (IllegalFieldTypeException e) { this.logger.warning("The root resource class " + rootResourceClass.getName() + " has an illegal annotated and typed field: " + e.getMessage()); return false; } catch (InjectException e) { this.logger.warning("Dependencies could not be injected in " + "root resource class " + rootResourceClass.getName() + ": " + e.getMessage()); return false; } catch (InvocationTargetException e) { this.logger.warning("Exception while calling bean setters in " + "root resource class " + rootResourceClass.getName() + ": " + e.getMessage()); return false; } PathRegExp uriTempl = newRrc.getPathRegExp(); for (RootResourceClass rrc : this.rootResourceClasses) { if (rrc.getJaxRsClass().equals(rootResourceClass)) { return true; } if (rrc.getPathRegExp().equals(uriTempl)) { this.logger .warning("There is already a root resource class with path " + uriTempl.getPathTemplateEnc()); return false; } } rootResourceClasses.add(newRrc); return true; } /** * Creates a new JAX-RS root resource class wrapper. * * @param jaxRsRootResourceClass * @return the wrapped root resource class. * @throws IllegalArgumentException * if the class is not a valid root resource class. * @throws MissingAnnotationException * if the class is not annotated with @Path. * @throws IllegalPathOnClassException * @throws MissingConstructorException * if no valid constructor could be found. * @throws IllegalBeanSetterTypeException * @throws IllegalFieldTypeException * @throws IllegalConstrParamTypeException * @throws IllegalPathParamTypeException */ private RootResourceClass getPerRequestRootClassWrapper( Class jaxRsRootResourceClass) throws IllegalArgumentException, MissingAnnotationException, IllegalPathOnClassException, MissingConstructorException, IllegalConstrParamTypeException, IllegalFieldTypeException, IllegalBeanSetterTypeException, IllegalPathParamTypeException { return new PerRequestRootResourceClass(jaxRsRootResourceClass, this.tlContext, this.jaxRsProviders, this.extensionBackwardMapping, Context.getCurrentLogger()); } /** * Creates a new JAX-RS resource class wrapper. * * @param jaxRsResourceClass * @return * @throws MissingAnnotationException * @throws IllegalArgumentException */ ResourceClass getResourceClass(Class jaxRsResourceClass) throws IllegalArgumentException, MissingAnnotationException { ResourceClass rc; // NICE thread save Map access without synchronized? synchronized (this.resourceClasses) { rc = this.resourceClasses.get(jaxRsResourceClass); } if (rc == null) { rc = new ResourceClass(jaxRsResourceClass, this.tlContext, this.jaxRsProviders, this.extensionBackwardMapping, Context .getCurrentLogger()); synchronized (this.resourceClasses) { this.resourceClasses.put(jaxRsResourceClass, rc); } } return rc; } /** * Creates a new JAX-RS root resource object wrapper. * * @param jaxRsRootResourceClass * @return the wrapped root resource class. * @throws InvocationTargetException * if an exception occurs while the injecting of dependencies. * @throws IllegalArgumentException * if the class is not a valid root resource class. * @throws MissingAnnotationException * if the class is not annotated with @Path. * @throws MissingConstructorException * if no valid constructor could be found. */ private RootResourceClass getSingletonRootClassWrapper( Object jaxRsRootResourceObject) throws IllegalPathOnClassException, IllegalConstrParamTypeException, IllegalFieldTypeException, IllegalBeanSetterTypeException, IllegalPathParamTypeException, IllegalArgumentException, MissingAnnotationException, MissingConstructorException, InjectException, InvocationTargetException { // TEST singleton root resource class return new SingletonRootResourceClass(jaxRsRootResourceObject, this.tlContext, this.jaxRsProviders, this.extensionBackwardMapping, Context.getCurrentLogger()); } /** * @return the wrapped root resource classes */ public Iterable roots() { return this.rootResourceClasses; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/AbstractJaxRsWrapper.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/AbstractJaxRsWrappe0000664000175000017500000000445311757206350034430 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.util.PathRegExp; /** * An abstract wrapper class. Contains some useful static methods. * * @author Stephan Koops */ public abstract class AbstractJaxRsWrapper { private final PathRegExp pathRegExp; /** * Creates a new AbstractJaxRsWrapper without a path. */ AbstractJaxRsWrapper() { this.pathRegExp = PathRegExp.EMPTY; } /** * Creates a new AbstractJaxRsWrapper with a given {@link PathRegExp}. * * @param pathRegExp * must not be null. */ AbstractJaxRsWrapper(PathRegExp pathRegExp) throws ImplementationException { if (pathRegExp == null) { throw new ImplementationException("The PathRegExp must not be null"); } this.pathRegExp = pathRegExp; } /** * @return Returns the regular expression for the URI template. */ protected PathRegExp getPathRegExp() { return this.pathRegExp; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceObject.java0000664000175000017500000000561211757206350034372 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; /** * An instance wraps a JAX-RS resource object. See section 3 of JAX-RS * specification. * * @author Stephan Koops */ public class ResourceObject { private final Object jaxRsResourceObject; private final ResourceClass resourceClass; /** * Creates a new wrapper for a resource object * * @param jaxRsResourceObject * the resource object * @param resourceClass * the wrapped resource class * @param logger * The logger to log unexpected Exceptions. */ ResourceObject(Object jaxRsResourceObject, ResourceClass resourceClass) { if (jaxRsResourceObject == null) { throw new IllegalArgumentException( "The JAX-RS resource object must not be null"); } if (resourceClass == null) { throw new IllegalArgumentException( "The ResourceClass must not be null"); } if (jaxRsResourceObject instanceof ResourceObject) { throw new IllegalArgumentException( "The given resource class object should not be an instance of the wrapping class ResourceObject"); } this.jaxRsResourceObject = jaxRsResourceObject; this.resourceClass = resourceClass; } /** * @return Returns the wrapped JAX-RS resource object. Returns never null. */ public Object getJaxRsResourceObject() { return this.jaxRsResourceObject; } /** * @return Returns the wrapped resource class. Returns never null. */ public ResourceClass getResourceClass() { return this.resourceClass; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/0000775000175000017500000000000011757206350032070 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ParameterList.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ParameterLis0000664000175000017500000012675511757206350034423 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.params; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Logger; import javax.ws.rs.CookieParam; import javax.ws.rs.DefaultValue; import javax.ws.rs.Encoded; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.core.PathSegmentImpl; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo; import org.restlet.ext.jaxrs.internal.exceptions.ConvertCookieParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertHeaderParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertMatrixParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertParameterException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertPathParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertQueryParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Contains a list of parameters for JAX-RS constructors, (sub) resource methods * and sub resource locators. * * @author Stephan Koops */ public class ParameterList { /** * Abstract super class for access to @*Param. */ abstract static class AbstractParamGetter implements ParamGetter { /** * The type of the collection. null, if this parameter do not represent * a collection. */ protected final Class> collType; /** * The class to convert to. If this object getter represents an *Param * annotated parameter, and it should be to an array or collection of * something, this value contains not the collection/array type, but the * generic type of it. */ protected final Class convertTo; /** * The default value for this parameter (if given) */ protected final DefaultValue defaultValue; /** * True, if this parameter should be an array, otherwise false. If true, * the {@link #collType} must be set to a {@link List}. */ protected final boolean isArray; protected final ThreadLocalizedContext tlContext; @SuppressWarnings({ "unchecked", "rawtypes" }) AbstractParamGetter(DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext) { this.tlContext = tlContext; this.defaultValue = defaultValue; if (convToCl.isArray()) { this.convertTo = convToCl.getComponentType(); this.collType = (Class) ArrayList.class; this.isArray = true; } else if (convToGen instanceof ParameterizedType) { final ParameterizedType parametrizedType = (ParameterizedType) convToGen; final Type[] argTypes = parametrizedType .getActualTypeArguments(); if (argTypes[0] instanceof Class) { this.convertTo = (Class) argTypes[0]; } else { throw new NotYetImplementedException( "Sorry, only Class is supported, but is " + argTypes[0]); } // TEST @*Param with array/collection and generic parameter this.collType = collType(parametrizedType); this.isArray = false; } else { this.convertTo = convToCl; this.collType = null; this.isArray = false; } } protected Object convertParamValue(String firstHeader) throws ConvertParameterException { return convertParamValue(firstHeader, this.defaultValue); } /** * Converts the given paramValue (found in the path, query, matrix or * header) into the given paramClass. * * @param paramValue * @param defaultValue * @return * @throws ConvertParameterException * @see PathParam * @see MatrixParam * @see QueryParam * @see HeaderParam * @see CookieParam */ protected Object convertParamValue(String paramValue, DefaultValue defaultValue) throws ConvertParameterException { if (decode() && (paramValue != null)) { paramValue = Reference.decode(paramValue); } else if ((paramValue == null) && (defaultValue != null)) { paramValue = defaultValue.value(); } if (this.convertTo.equals(String.class)) { return paramValue; } if (this.convertTo.isPrimitive()) { if ((paramValue != null) && (paramValue.length() <= 0)) { paramValue = defaultValue.value(); } return getParamValueForPrimitive(paramValue); } return convertParamValueInner(paramValue, defaultValue); } /** * Converts the given value without any decoding. * * @param paramValue * @param defaultValue * @return * @throws ConvertParameterException * @throws WebApplicationException * if the conversion method throws an * WebApplicationException. */ private Object convertParamValueInner(String paramValue, DefaultValue defaultValue) throws ConvertParameterException, WebApplicationException { WebApplicationException constructorWae = null; try { final Constructor constr = this.convertTo .getConstructor(String.class); return constr.newInstance(paramValue); } catch (WebApplicationException wae) { constructorWae = wae; } catch (Exception e) { // try valueOf(String) as next step } Method valueOf; try { valueOf = this.convertTo.getMethod("valueOf", String.class); } catch (SecurityException e) { throw ConvertParameterException.object(this.convertTo, paramValue, e); } catch (NoSuchMethodException e) { throw ConvertParameterException.object(this.convertTo, paramValue, e); } try { return valueOf.invoke(null, paramValue); } catch (IllegalArgumentException e) { if (constructorWae != null) { throw constructorWae; } throw ConvertParameterException.object(this.convertTo, paramValue, e); } catch (IllegalAccessException e) { if (constructorWae != null) { throw constructorWae; } throw ConvertParameterException.object(this.convertTo, paramValue, e); } catch (InvocationTargetException ite) { if (constructorWae != null) { throw constructorWae; } final Throwable cause = ite.getCause(); if (cause instanceof WebApplicationException) { throw (WebApplicationException) cause; } if (((paramValue == null) || (paramValue.length() <= 0)) && (ite.getCause() instanceof IllegalArgumentException)) { if (defaultValue == null) { return null; } final String dfv = defaultValue.value(); return convertParamValueInner(dfv, null); } throw ConvertParameterException.object(this.convertTo, paramValue, ite); } } protected Object convertParamValues(Iterator paramValueIter) throws ConvertParameterException { final Collection coll = createColl(); while (paramValueIter.hasNext()) { final String queryParamValue = paramValueIter.next(); final Object convertedValue = convertParamValue( queryParamValue, null); if (convertedValue != null) { coll.add(convertedValue); } } if (coll.isEmpty()) { coll.add(convertParamValue(null)); } if (this.isArray) { return Util.toArray(coll, this.convertTo); } return unmodifiable(coll); } /** * @return an new created instance of {@link #collType}. Returns null, * if collType is null. */ @SuppressWarnings("unchecked") protected Collection createColl() { try { if (this.collType != null) { return (Collection) this.collType.newInstance(); } return null; } catch (Exception e) { throw new RuntimeException( "Could not instantiate the collection type " + this.collType, e); } } protected Collection unmodifiable(Collection coll) { if (coll instanceof List) return Collections.unmodifiableList((List) coll); if (coll instanceof SortedSet) return Collections.unmodifiableSortedSet((SortedSet) coll); if (coll instanceof Set) return Collections.unmodifiableSet((Set) coll); return Collections.unmodifiableCollection(coll); } /** * * @return * @deprecated Use {@link #decoding()} instead. */ protected boolean decode() { return decoding(); } protected abstract boolean decoding(); /** * @return the concrete value of this parameter for the current request. */ public abstract Object getParamValue(); protected Object getParamValueForPrimitive(String paramValue) throws ConvertParameterException { try { if (this.convertTo == Integer.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_INT; } return new Integer(paramValue); } if (this.convertTo == Double.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_DOUBLE; } return new Double(paramValue); } if (this.convertTo == Float.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_FLOAT; } return new Float(paramValue); } if (this.convertTo == Byte.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_BYTE; } return new Byte(paramValue); } if (this.convertTo == Long.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_LONG; } return new Long(paramValue); } if (this.convertTo == Short.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_SHORT; } return new Short(paramValue); } if (this.convertTo == Character.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_CHAR; } if (paramValue.length() == 1) { return paramValue.charAt(0); } throw ConvertParameterException.primitive(this.convertTo, paramValue, null); } if (this.convertTo == Boolean.TYPE) { if (((paramValue == null) || (paramValue.length() <= 0))) { return DEFAULT_BOOLEAN; } if (paramValue.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (paramValue.equalsIgnoreCase("false")) { return Boolean.FALSE; } throw ConvertParameterException.primitive(this.convertTo, paramValue, null); } } catch (IllegalArgumentException e) { throw ConvertParameterException.primitive(this.convertTo, paramValue, e); } String warning; if (this.convertTo == Void.TYPE) { warning = "an object should be converted to a void; but this could not be here"; } else { warning = "an object should be converted to a " + this.convertTo + ", but here are only primitives allowed."; } localLogger.warning(warning); final ResponseBuilder rb = javax.ws.rs.core.Response.serverError(); rb.entity(warning); throw new WebApplicationException(rb.build()); } public Object getValue() { return getParamValue(); } } static class CookieParamGetter extends NoEncParamGetter { private final CookieParam cookieParam; /** * @param annoSaysLeaveClassEncoded * to check if the annotation is available, but should not * be. */ CookieParamGetter(CookieParam cookieParam, DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean annoSaysLeaveClassEncoded) { super(defaultValue, convToCl, convToGen, tlContext, annoSaysLeaveClassEncoded); this.cookieParam = cookieParam; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Object getParamValue() { final String cookieName = this.cookieParam.value(); Series cookies; cookies = this.tlContext.get().getRequest().getCookies(); if (this.convertTo.equals(Cookie.class)) { final Collection coll = createColl(); for (final org.restlet.data.Cookie rc : cookies) { if (!rc.getName().equals(cookieName)) { continue; } final Cookie cookie = Converter.toJaxRsCookie(rc); if (coll == null) { return cookie; } coll.add(cookie); } if (coll == null) { return null; } if (coll.isEmpty()) { final String value = this.defaultValue.value(); coll.add(new Cookie(cookieName, value)); } if (this.isArray) { return Util.toArray(coll, Cookie.class); } return coll; } try { if (this.collType == null) { // no collection parameter final String firstCookieValue = WrapperUtil .getValue(cookies.getFirst(cookieName)); return convertParamValue(firstCookieValue); } return convertParamValues(new ParamValueIter( (Series) cookies.subList(cookieName))); } catch (ConvertParameterException e) { throw new ConvertCookieParamException(e); } } } /** * Abstract super class for access to the entity or to @*Param where * encoded is allowed (@{@link PathParam}, @{@link MatrixParam} and * @{@link QueryParam}). */ abstract static class EncParamGetter extends AbstractParamGetter { private final boolean decoding; EncParamGetter(DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean leaveEncoded) { super(defaultValue, convToCl, convToGen, tlContext); this.decoding = !leaveEncoded; } @Override protected boolean decoding() { return this.decoding; } } static abstract class FormOrQueryParamGetter extends EncParamGetter { FormOrQueryParamGetter(DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean leaveEncoded) { super(defaultValue, convToCl, convToGen, tlContext, leaveEncoded); } /** * @param form * @param paramName * @return * @throws ConvertQueryParamException */ Object getParamValue(final Form form, final String paramName) throws ConvertParameterException { final List parameters = form.subList(paramName); if (this.collType == null) { // no collection parameter final Parameter firstFormParam = form.getFirst(paramName); final String queryParamValue = WrapperUtil .getValue(firstFormParam); return convertParamValue(queryParamValue); } ParamValueIter queryParamValueIter; queryParamValueIter = new ParamValueIter(parameters); return convertParamValues(queryParamValueIter); } } static class FormParamGetter extends FormOrQueryParamGetter { private final FormParam formParam; private static Form form; FormParamGetter(FormParam formParam, DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean leaveEncoded) { super(defaultValue, convToCl, convToGen, tlContext, leaveEncoded); this.formParam = formParam; } @Override public Object getParamValue() { Representation entity = this.tlContext.get().getRequest() .getEntity(); if (entity != null && entity.isAvailable()) { form = new Form(entity); } final String paramName = this.formParam.value(); try { return super.getParamValue(form, paramName); } catch (ConvertParameterException e) { throw new ConvertQueryParamException(e); } } } static class HeaderParamGetter extends NoEncParamGetter { private final HeaderParam headerParam; /** * @param annoSaysLeaveClassEncoded * to check if the annotation is available. */ HeaderParamGetter(HeaderParam headerParam, DefaultValue defaultValue, Class convToCl, Type paramGenericType, ThreadLocalizedContext tlContext, boolean annoSaysLeaveClassEncoded) { super(defaultValue, convToCl, paramGenericType, tlContext, annoSaysLeaveClassEncoded); this.headerParam = headerParam; } @Override public Object getParamValue() { final Form httpHeaders = Util.getHttpHeaders(this.tlContext.get() .getRequest()); final String headerName = this.headerParam.value(); try { if (this.collType == null) { // no collection parameter final String firstHeader = WrapperUtil.getValue(httpHeaders .getFirst(headerName, true)); return convertParamValue(firstHeader); } return convertParamValues(new ParamValueIter( httpHeaders.subList(headerName, true))); } catch (ConvertParameterException e) { throw new ConvertHeaderParamException(e); } } } static class MatrixParamGetter extends EncParamGetter { private final MatrixParam matrixParam; MatrixParamGetter(MatrixParam matrixParam, DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean leaveEncoded) { super(defaultValue, convToCl, convToGen, tlContext, leaveEncoded); this.matrixParam = matrixParam; } @Override public Object getParamValue() { final CallContext callContext = this.tlContext.get(); try { if (this.collType == null) { // no collection parameter final String matrixParamValue = callContext .getLastMatrixParamEnc(this.matrixParam); return convertParamValue(matrixParamValue); } Iterator matrixParamValues; matrixParamValues = callContext .matrixParamEncIter(this.matrixParam); return convertParamValues(matrixParamValues); } catch (ConvertParameterException e) { throw new ConvertMatrixParamException(e); } } } /** * Abstract super class for access to the entity or to @*Param where * encoded is allowed (@{@link PathParam}, @{@link MatrixParam} and * @{@link QueryParam}). */ abstract static class NoEncParamGetter extends AbstractParamGetter { /** * @param annoSaysLeaveEncoded * to check if the annotation is available. */ NoEncParamGetter(DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean annoSaysLeaveEncoded) { super(defaultValue, convToCl, convToGen, tlContext); checkForEncodedAnno(annoSaysLeaveEncoded); } /** * Checks if the annotation @{@link Encoded} is available on the * given field or bean setter. If yes, a warning is logged. */ void checkForEncodedAnno(AccessibleObject fieldOrBeanSetter) { checkForEncodedAnno(fieldOrBeanSetter .isAnnotationPresent(Encoded.class)); } /** * Checks if the annotation @{@link Encoded} is available on the * given field or bean setter. If yes, this method logs a warning. */ void checkForEncodedAnno(boolean annoSaysLeaveEncoded) { if (annoSaysLeaveEncoded) { localLogger .warning("You should not use @Encoded on a @HeaderParam or @CookieParam. Will ignore it"); } } @Override protected boolean decoding() { return false; } } static interface ParamGetter { /** * Returns the value for this param. * * @return the value for this param. * @throws InvocationTargetException * @throws ConvertRepresentationException * @throws WebApplicationException */ public Object getValue() throws InvocationTargetException, ConvertRepresentationException, WebApplicationException; } static class PathParamGetter extends EncParamGetter { private final PathParam pathParam; PathParamGetter(PathParam pathParam, DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean leaveEncoded) throws IllegalPathParamTypeException { super(defaultValue, convToCl, convToGen, tlContext, leaveEncoded); if ((this.collType != null) && (!this.convertTo.equals(PathSegment.class))) { throw new IllegalPathParamTypeException( "The type of a @PathParam annotated parameter etc. must not be a collection type or array, if the type parameter is not PathSegment"); } this.pathParam = pathParam; } /** * Creates a {@link PathSegment}. * * @param pathSegmentEnc * @return * @throws IllegalArgumentException */ private PathSegment createPathSegment(final String pathSegmentEnc) throws IllegalArgumentException { return new PathSegmentImpl(pathSegmentEnc, this.decode(), -1); } @Override public Object getParamValue() { final CallContext callContext = this.tlContext.get(); if (this.convertTo.equals(PathSegment.class)) { if (this.collType == null) { // no collection parameter final String pathSegmentEnc = callContext .getLastPathSegmentEnc(this.pathParam); return createPathSegment(pathSegmentEnc); } final Iterator pathSegmentEncIter; pathSegmentEncIter = callContext .pathSegementEncIter(this.pathParam); final Collection coll = createColl(); while (pathSegmentEncIter.hasNext()) { final String pathSegmentEnc = pathSegmentEncIter.next(); coll.add(createPathSegment(pathSegmentEnc)); } if (this.isArray) { return Util.toArray(coll, this.convertTo); } return unmodifiable(coll); } try { final String pathParamValue; pathParamValue = callContext.getLastPathParamEnc(pathParam); return convertParamValue(pathParamValue); } catch (ConvertParameterException e) { throw new ConvertPathParamException(e); } } } static class QueryParamGetter extends FormOrQueryParamGetter { private final QueryParam queryParam; QueryParamGetter(QueryParam queryParam, DefaultValue defaultValue, Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, boolean leaveEncoded) { super(defaultValue, convToCl, convToGen, tlContext, leaveEncoded); this.queryParam = queryParam; } @Override public Object getParamValue() { final Reference resourceRef = this.tlContext.get().getRequest() .getResourceRef(); final String queryString = resourceRef.getQuery(); final Form form = Converter.toFormEncoded(queryString); final String paramName = this.queryParam.value(); try { return super.getParamValue(form, paramName); } catch (ConvertParameterException e) { throw new ConvertQueryParamException(e); } } } /** * @author Stephan Koops */ private static class UriInfoGetter implements ParamGetter { private final boolean availableMandatory; private final ThreadLocalizedUriInfo uriInfo; private UriInfoGetter(ThreadLocalizedContext tlContext, boolean availableMandatory) { this.uriInfo = new ThreadLocalizedUriInfo(tlContext); this.availableMandatory = availableMandatory; } public Object getValue() throws InvocationTargetException, ConvertRepresentationException, WebApplicationException { this.uriInfo.saveStateForCurrentThread(this.availableMandatory); return this.uriInfo; } } private static final String COLL_PARAM_NOT_DEFAULT = "The collection type Collection is not supported for parameters. Use List, Set or SortedSet"; private static final Boolean DEFAULT_BOOLEAN = Boolean.FALSE; private static final Byte DEFAULT_BYTE = (byte) 0; private static final Character DEFAULT_CHAR = new Character('\0'); private static final Double DEFAULT_DOUBLE = 0d; private static final Float DEFAULT_FLOAT = 0.0f; private static final Integer DEFAULT_INT = 0; private static final Long DEFAULT_LONG = new Long(0); private static final Short DEFAULT_SHORT = 0; private static final Logger localLogger = org.restlet.Context .getCurrentLogger(); private static final Collection> VALID_ANNOTATIONS = createValidAnnotations(); /** * @return the collection type for the given {@link ParameterizedType * parametrized Type}.
* If the given type do not represent an collection, null is * returned. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Class> collType(ParameterizedType type) { final Type rawType = type.getRawType(); if (rawType.equals(List.class)) { return (Class) ArrayList.class; } else if (rawType.equals(Set.class)) { return (Class) HashSet.class; } else if (rawType.equals(SortedSet.class)) { return (Class) TreeSet.class; } else if (rawType.equals(Collection.class)) { localLogger.config(ParameterList.COLL_PARAM_NOT_DEFAULT); return (Class) ArrayList.class; } return null; } @SuppressWarnings("unchecked") static Collection> createValidAnnotations() { return Arrays.asList(Context.class, HeaderParam.class, MatrixParam.class, QueryParam.class, PathParam.class, CookieParam.class); } /** * Returns the given annotation, if it is available in the given array of * annotations. */ @SuppressWarnings("unchecked") static A getAnno(Annotation[] annotations, Class annoType) { for (final Annotation annot : annotations) { final Class annotationType = annot .annotationType(); if (annotationType.equals(annoType)) { return (A) annot; } } return null; } /** * Returns true, if one of the annotations is @{@link Encoded} */ static boolean getLeaveEncoded(Annotation[] annotations) { for (final Annotation annot : annotations) { final Class annotationType = annot .annotationType(); if (annotationType.equals(Encoded.class)) { return true; } } return false; } /** * must call the {@link EntityGetter} first, if @{@link FormParam} is * used. A value less than zero means, that no special handling is needed. */ private final int entityPosition; /** shortcut for {@link #parameters}.length */ private final int paramCount; /** @see #paramCount */ private final ParamGetter[] parameters; /** * @param parameterTypes * @param genParamTypes * @param paramAnnoss * @param tlContext * @param leaveAllEncoded * @param jaxRsProviders * @param extensionBackwardMapping * @param paramsAllowed * true, if @*Params are allowed as parameter, otherwise * false. * @param entityAllowed * true, if the entity is allowed as parameter, otherwise false. * @param logger * @param allMustBeAvailable * if true, all values must be available (for singeltons creation * it must be false) * @throws MissingAnnotationException * @throws IllegalTypeException * if the given class is not valid to be annotated with @ * {@link Context}. * @throws IllegalPathParamTypeException */ private ParameterList(Class[] parameterTypes, Type[] genParamTypes, Annotation[][] paramAnnoss, ThreadLocalizedContext tlContext, boolean leaveAllEncoded, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, boolean paramsAllowed, boolean entityAllowed, Logger logger, boolean allMustBeAvailable) throws MissingAnnotationException, IllegalTypeException, IllegalPathParamTypeException { this.paramCount = parameterTypes.length; this.parameters = new ParamGetter[this.paramCount]; boolean entityAlreadyRead = false; int entityPosition = -1; for (int i = 0; i < this.paramCount; i++) { final Class parameterType = parameterTypes[i]; final Type genParamType = genParamTypes[i]; final Annotation[] paramAnnos = paramAnnoss[i]; final Context conntextAnno = getAnno(paramAnnos, Context.class); if (conntextAnno != null) { if (parameterType.equals(UriInfo.class)) { this.parameters[i] = new UriInfoGetter(tlContext, allMustBeAvailable); } else { this.parameters[i] = new ContextHolder( ContextInjector.getInjectObject(parameterType, tlContext, jaxRsProviders, extensionBackwardMapping)); } continue; } if (paramsAllowed) { final boolean leaveThisEncoded = getLeaveEncoded(paramAnnos); final DefaultValue defValue = getAnno(paramAnnos, DefaultValue.class); final CookieParam cookieParam = getAnno(paramAnnos, CookieParam.class); final HeaderParam headerParam = getAnno(paramAnnos, HeaderParam.class); final MatrixParam matrixParam = getAnno(paramAnnos, MatrixParam.class); final PathParam pathParam = getAnno(paramAnnos, PathParam.class); final QueryParam queryParam = getAnno(paramAnnos, QueryParam.class); final FormParam formParam = getAnno(paramAnnos, FormParam.class); if (pathParam != null) { this.parameters[i] = new PathParamGetter(pathParam, defValue, parameterType, genParamType, tlContext, leaveAllEncoded || leaveThisEncoded); continue; } else if (cookieParam != null) { this.parameters[i] = new CookieParamGetter(cookieParam, defValue, parameterType, genParamType, tlContext, leaveThisEncoded); continue; } else if (headerParam != null) { this.parameters[i] = new HeaderParamGetter(headerParam, defValue, parameterType, genParamType, tlContext, leaveThisEncoded); continue; } else if (matrixParam != null) { this.parameters[i] = new MatrixParamGetter(matrixParam, defValue, parameterType, genParamType, tlContext, leaveAllEncoded || leaveThisEncoded); continue; } else if (queryParam != null) { this.parameters[i] = new QueryParamGetter(queryParam, defValue, parameterType, genParamType, tlContext, leaveAllEncoded || leaveThisEncoded); continue; } else if (formParam != null) { this.parameters[i] = new FormParamGetter(formParam, defValue, parameterType, genParamType, tlContext, leaveAllEncoded || leaveThisEncoded); continue; } } // could only be the entity here if (!entityAllowed) { throw new MissingAnnotationException( "All parameters requires one of the following annotations: " + VALID_ANNOTATIONS); } if (entityAlreadyRead) { throw new MissingAnnotationException( "The entity is already read. The " + i + ". parameter requires one of " + "the following annotations: " + VALID_ANNOTATIONS); } if (Representation.class.isAssignableFrom(parameterType)) { this.parameters[i] = ReprEntityGetter.create(parameterType, genParamType, logger); } if (this.parameters[i] == null) { this.parameters[i] = new EntityGetter(parameterType, genParamType, tlContext, jaxRsProviders, paramAnnos); } entityPosition = i; entityAlreadyRead = true; } this.entityPosition = entityPosition; } /** * @param constr * @param tlContext * @param leaveEncoded * @param jaxRsProviders * @param extensionBackwardMapping * @param paramsAllowed * @param logger * @param allMustBeAvailable * @throws MissingAnnotationException * @throws IllegalTypeException * if one of the parameters contains a @{@link Context} on * an type that must not be annotated with @{@link Context}. * @throws IllegalPathParamTypeException */ public ParameterList(Constructor constr, ThreadLocalizedContext tlContext, boolean leaveEncoded, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, boolean paramsAllowed, Logger logger, boolean allMustBeAvailable) throws MissingAnnotationException, IllegalTypeException, IllegalPathParamTypeException { this(constr.getParameterTypes(), constr.getGenericParameterTypes(), constr.getParameterAnnotations(), tlContext, leaveEncoded, jaxRsProviders, extensionBackwardMapping, paramsAllowed, false, logger, allMustBeAvailable); } /** * @param executeMethod * @param annotatedMethod * @param tlContext * @param leaveEncoded * @param jaxRsProviders * @param extensionBackwardMapping * @param entityAllowed * @param logger * @throws MissingAnnotationException * @throws IllegalTypeException * if one of the parameters contains a @{@link Context} on * an type that must not be annotated with @{@link Context}. * @throws IllegalPathParamTypeException */ public ParameterList(Method executeMethod, Method annotatedMethod, ThreadLocalizedContext tlContext, boolean leaveEncoded, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, boolean entityAllowed, Logger logger) throws MissingAnnotationException, IllegalTypeException, IllegalPathParamTypeException { this(executeMethod.getParameterTypes(), executeMethod .getGenericParameterTypes(), annotatedMethod .getParameterAnnotations(), tlContext, leaveEncoded, jaxRsProviders, extensionBackwardMapping, true, entityAllowed, logger, true); } /** * Returns the concrete parameter array for the current request. * * @return the concrete parameter array for the current request. * @throws InvocationTargetException * @throws ConvertRepresentationException * @throws WebApplicationException */ public Object[] get() throws ConvertRepresentationException, InvocationTargetException, WebApplicationException { final Object[] args = new Object[this.parameters.length]; if (this.entityPosition >= 0) { args[entityPosition] = this.parameters[entityPosition].getValue(); } for (int i = 0; i < this.paramCount; i++) { if (i != this.entityPosition) { args[i] = this.parameters[i].getValue(); } } return args; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ContextInjector.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ContextInjec0000664000175000017500000004520711757206350034420 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.params; import static org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil.isBeanSetter; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Request; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Providers; import org.restlet.ext.jaxrs.ExtendedUriInfo; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedExtendedUriInfo; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.AbstractParamGetter; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; /** * Helper class to inject into fields annotated with @{@link Context}. * * @author Stephan Koops * @see IntoRrcInjector */ public class ContextInjector { static class BeanSetter implements InjectionAim { private final Method beanSetter; private BeanSetter(Method beanSetter) { this.beanSetter = beanSetter; this.beanSetter.setAccessible(true); } /** * @throws InvocationTargetException * @throws InjectException * @throws IllegalArgumentException * @see InjectionAim#injectInto(Object, Object, boolean) */ public void injectInto(Object resource, Object toInject, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException { Util.inject(resource, this.beanSetter, toInject); } } /** * {@link Injector}, that injects the same object in every resource. Is is * used for the @{@link Context} objects. */ private static class EverSameInjector implements Injector { private final Object injectable; private final InjectionAim injectionAim; private EverSameInjector(InjectionAim injectionAim, Object injectable) { this.injectionAim = injectionAim; this.injectable = injectable; } /** * @see Injector#injectInto(java.lang.Object, boolean) */ public void injectInto(Object resource, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException { this.injectionAim.injectInto(resource, this.injectable, allMustBeAvailable); } } static class FieldWrapper implements InjectionAim { private final Field field; private FieldWrapper(Field field) { this.field = field; this.field.setAccessible(true); } /** * @throws InvocationTargetException * @throws InjectException * @throws IllegalArgumentException * @see InjectionAim#injectInto(Object, Object, boolean) */ public void injectInto(Object resource, Object toInject, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException { Util.inject(resource, this.field, toInject); } } private static class GetLastPathSegment implements PathSegment { private final ThreadLocalizedContext tlContext; GetLastPathSegment(ThreadLocalizedContext tlContext) { this.tlContext = tlContext; } private PathSegment getLast() { final List pss = this.tlContext.getPathSegments(); return pss.get(pss.size() - 1); } /** * @see javax.ws.rs.core.PathSegment#getMatrixParameters() */ public MultivaluedMap getMatrixParameters() { return getLast().getMatrixParameters(); } /** * @see javax.ws.rs.core.PathSegment#getPath() */ public String getPath() { return getLast().getPath(); } } /** * Represents a field or a bean setter, where the runtime injects something * in. */ static interface InjectionAim { /** * Inject the toInject into this field or bean setter on object * resource. * * @param resource * @param toInject * @param allMustBeAvailable * @throws IllegalArgumentException * @throws InjectException * @throws InvocationTargetException * @see FieldWrapper#set(Object, Object) * @see Method#invoke(Object, Object...) */ void injectInto(Object resource, Object toInject, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException; } static interface Injector { /** * @param resource * @param allMustBeAvailable * @throws InvocationTargetException * @throws InjectException * @throws IllegalArgumentException * @see InjectionAim#injectInto(Object, Object, boolean) */ public abstract void injectInto(Object resource, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException; } private class ParamValueInjector implements Injector { private final AccessibleObject fieldOrBeanSetter; private final AbstractParamGetter iog; ParamValueInjector(AccessibleObject fieldOrBeanSetter, AbstractParamGetter iog) { this.fieldOrBeanSetter = fieldOrBeanSetter; this.fieldOrBeanSetter.setAccessible(true); this.iog = iog; } /** * @see org.restlet.ext.jaxrs.internal.wrappers.params.ContextInjector.Injector#injectInto(java.lang.Object, * boolean) */ public void injectInto(Object resource, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException { Util.inject(resource, this.fieldOrBeanSetter, this.iog .getParamValue()); } } /** * @author Stephan Koops */ private static final class UriInfoInjector implements Injector { private final InjectionAim aim; private final ThreadLocalizedUriInfo uriInfo; UriInfoInjector(InjectionAim aim, ThreadLocalizedContext tlContext) { this.aim = aim; this.uriInfo = new ThreadLocalizedUriInfo(tlContext); } public void injectInto(Object resource, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException { this.uriInfo.saveStateForCurrentThread(allMustBeAvailable); this.aim.injectInto(resource, this.uriInfo, allMustBeAvailable); } } /** * @author Stephan Koops */ private static final class ExtendedUriInfoInjector implements Injector { private final InjectionAim aim; private final ThreadLocalizedExtendedUriInfo uriInfo; ExtendedUriInfoInjector(InjectionAim aim, ThreadLocalizedContext tlContext) { this.aim = aim; this.uriInfo = new ThreadLocalizedExtendedUriInfo(tlContext); } public void injectInto(Object resource, boolean allMustBeAvailable) throws IllegalArgumentException, InjectException, InvocationTargetException { this.uriInfo.saveStateForCurrentThread(allMustBeAvailable); this.aim.injectInto(resource, this.uriInfo, allMustBeAvailable); } } private static Logger logger = org.restlet.Context.getCurrentLogger(); /** * @param declaringClass * the class / interface to injecto into; must not be * {@link UriInfo} * @param tlContext * @param providers * @param extensionBackwardMapping * @param aim * @return * @throws IllegalTypeException * if the given class is not valid to be annotated with @ * {@link Context}. * @throws ImplementationException * the declaringClass must not be {@link UriInfo} */ static Object getInjectObject(Class declaringClass, ThreadLocalizedContext tlContext, Providers providers, ExtensionBackwardMapping extensionBackwardMapping) throws IllegalTypeException, ImplementationException { if (declaringClass.equals(Providers.class)) { return providers; } if (declaringClass.equals(ContextResolver.class)) { // NICE also throw, where the error occurs. throw new IllegalTypeException( "The ContextResolver is not allowed for @Context annotated fields yet. Use javax.ws.rs.ext.Providers#getContextResolver(...)"); } if (declaringClass.equals(ExtensionBackwardMapping.class)) { return extensionBackwardMapping; } if (declaringClass.equals(PathSegment.class)) { String msg = "The use of PathSegment annotated with @Context is not standard."; logger.config(msg); return new GetLastPathSegment(tlContext); } if (declaringClass.equals(SecurityContext.class) || declaringClass.equals(HttpHeaders.class) || declaringClass.equals(Request.class)) { return tlContext; } if (declaringClass.equals(UriInfo.class)) { throw new ImplementationException( "You must not call the method ContextInjector.getInjectObject(.......) with class UriInfo"); } String declaringClassName = declaringClass.getName(); // compare names to avoid ClassNotFoundExceptions, if the Servlet-API is // not in the classpath if (declaringClassName.equals("javax.servlet.http.HttpServletRequest") || declaringClassName .equals("javax.servlet.http.HttpServletResponse")) { throw new NotYetImplementedException( "The returnin of Servlet depending Context is not implemented for now."); } // NICE also allow injection of ClientInfo and Conditions. Proxies are // required, because the injected objects must be thread local. throw new IllegalTypeException(declaringClass + " must not be annotated with @Context"); } /** * * @param declaringClass * @param aim * @param tlContext * @param allProviders * @param extensionBackwardMapping * @return * @throws IllegalTypeException * if the given class is not valid to be annotated with @ * {@link Context}. */ static Injector getInjector(Class declaringClass, InjectionAim aim, ThreadLocalizedContext tlContext, Providers allProviders, ExtensionBackwardMapping extensionBackwardMapping) throws IllegalTypeException { if (declaringClass.equals(UriInfo.class)) { return new UriInfoInjector(aim, tlContext); } if (declaringClass.equals(ExtendedUriInfo.class)) { return new ExtendedUriInfoInjector(aim, tlContext); } return new EverSameInjector(aim, getInjectObject(declaringClass, tlContext, allProviders, extensionBackwardMapping)); } /** * This {@link List} contains the fields in this class which are annotated * to inject ever the same object. * * @see javax.ws.rs.ext.ContextResolver * @see Providers */ private final List injEverSameAims = new ArrayList(); /** * @param jaxRsClass * @param tlContext * @param providers * all entity providers. * @param extensionBackwardMapping * the extension backward mapping * @throws IllegalBeanSetterTypeException * if one of the bean setters annotated with @ * {@link Context} has a type that must not be annotated with * @{@link Context}. * @throws IllegalFieldTypeException * if one of the fields annotated with @{@link Context} has * a type that must not be annotated with @{@link Context}. * @throws ImplementationException */ public ContextInjector(Class jaxRsClass, ThreadLocalizedContext tlContext, Providers providers, ExtensionBackwardMapping extensionBackwardMapping) throws IllegalFieldTypeException, IllegalBeanSetterTypeException { this.init(jaxRsClass, tlContext, providers, extensionBackwardMapping); } protected void add(AccessibleObject fieldOrBeanSetter, AbstractParamGetter iog) { this.injEverSameAims .add(new ParamValueInjector(fieldOrBeanSetter, iog)); } /** * initiates the fields to cache the fields that needs injection. * * @param tlContext * the {@link ThreadLocalizedContext} of the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * @param allProviders * all entity providers. * @param extensionBackwardMapping * the extension backward mapping * * @throws IllegalFieldTypeException * if one of the fields annotated with @{@link Context} has * a type that must not be annotated with @{@link Context}. * @throws IllegalBeanSetterTypeException * if one of the bean setters annotated with @ * {@link Context} has a type that must not be annotated with * @{@link Context}. */ private void init(Class jaxRsClass, ThreadLocalizedContext tlContext, Providers allProviders, ExtensionBackwardMapping extensionBackwardMapping) throws IllegalFieldTypeException, IllegalBeanSetterTypeException { do { try { for (final Field field : jaxRsClass.getDeclaredFields()) { if (field.isAnnotationPresent(Context.class)) { InjectionAim aim = new FieldWrapper(field); Class declaringClass = field.getType(); Injector injector = getInjector(declaringClass, aim, tlContext, allProviders, extensionBackwardMapping); this.injEverSameAims.add(injector); } } } catch (SecurityException e) { // NICE handle SecurityException throw e; } catch (IllegalTypeException e) { throw new IllegalFieldTypeException(e); } try { for (final Method method : jaxRsClass.getDeclaredMethods()) { if (isBeanSetter(method, Context.class)) { BeanSetter aim = new BeanSetter(method); Class paramClass = method.getParameterTypes()[0]; Injector injector = getInjector(paramClass, aim, tlContext, allProviders, extensionBackwardMapping); this.injEverSameAims.add(injector); } } } catch (SecurityException e) { // NICE handle SecurityException throw e; } catch (IllegalTypeException e) { throw new IllegalBeanSetterTypeException(e); } jaxRsClass = jaxRsClass.getSuperclass(); } while (jaxRsClass != null); } /** * Injects all the supported dependencies into the the given resource object * of this class. * * @param jaxRsResObj * @param allMustBeAvailable * if true, all information in @{@link Context} annotated * objects must be available, especially the ancestor resource * info (false for singelton lifecycle) * @throws InjectException * if the injection was not possible. See * {@link InjectException#getCause()} for the reason. * @throws InvocationTargetException * if a setter throws an exception */ public void injectInto(Object jaxRsResObj, boolean allMustBeAvailable) throws InjectException, InvocationTargetException { for (final Injector injectAim : this.injEverSameAims) { injectAim.injectInto(jaxRsResObj, allMustBeAvailable); } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ReprEntityGetter.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ReprEntityGe0000664000175000017500000002026111757206350034375 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.params; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import org.restlet.Request; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.ParamGetter; import org.restlet.representation.Representation; /** * An {@link EntityGetter} for Restlet {@link Representation}s. * * @author Stephan Koops */ public abstract class ReprEntityGetter implements ParamGetter { /** * EntityGetter, if there is a constructor with two arguments: Class and * Representation */ static class ClassReprEntityGetter extends ReprEntityGetter { private final Class clazz; ClassReprEntityGetter(Class genClass, Constructor constructor) { super(constructor); this.clazz = genClass; } @Override Representation createInstance(Representation entity) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { return this.constr.newInstance(this.clazz, entity); } } /** * EntityGetter, if Representation could directly be injected */ static class DirectReprEntityGetter implements ParamGetter { /** * @see org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.ParamGetter#getValue() */ public Object getValue() throws InvocationTargetException, ConvertRepresentationException, WebApplicationException { return Request.getCurrent().getEntity(); } } /** * EntityGetter, if there is a constructor with two arguments: * Representation and Class */ static class ReprClassEntityGetter extends ReprEntityGetter { private final Class clazz; ReprClassEntityGetter(Constructor constructor, Class genClass) { super(constructor); this.clazz = genClass; } @Override Representation createInstance(Representation entity) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { return this.constr.newInstance(entity, this.clazz); } } /** * EntityGetter, if there is a constructor for only the entity. */ static class ReprOnlyEntityGetter extends ReprEntityGetter { /** * @param constructor */ ReprOnlyEntityGetter(Constructor constructor) { super(constructor); } @Override Representation createInstance(Representation entity) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { return this.constr.newInstance(entity); } } /** * Creates an EntityGetter for the given values, or null, if it is not * available. * * @param representationType * @param convToGen * @param logger * @return the ParamGetter */ public static ParamGetter create(Class representationType, Type convToGen, Logger logger) { if (representationType.equals(Representation.class)) { return new DirectReprEntityGetter(); } try { return new ReprOnlyEntityGetter( representationType.getConstructor(Representation.class)); } catch (SecurityException e) { logger.warning("The constructor " + representationType + "(Representation) is not accessable."); } catch (NoSuchMethodException e) { // try next } if (!(convToGen instanceof ParameterizedType)) { return null; } final ParameterizedType pType = (ParameterizedType) convToGen; final Type[] typeArgs = pType.getActualTypeArguments(); if (typeArgs.length != 1) { return null; } final Type typeArg = typeArgs[0]; if (!(typeArg instanceof Class)) { return null; } final Class genClass = (Class) typeArg; try { return new ReprClassEntityGetter(representationType.getConstructor( Representation.class, Class.class), genClass); } catch (SecurityException e) { logger.warning("The constructor " + representationType + "(Representation) is not accessable."); } catch (NoSuchMethodException e) { // try next } try { return new ClassReprEntityGetter(genClass, representationType.getConstructor(Class.class, Representation.class)); } catch (SecurityException e) { logger.warning("The constructor " + representationType + "(Representation) is not accessable."); return null; } catch (NoSuchMethodException e) { return null; } } final Constructor constr; @SuppressWarnings("unchecked") ReprEntityGetter(Constructor constr) { this.constr = (Constructor) constr; } abstract Representation createInstance(Representation entity) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException; /** * @return the class of the {@link Representation}. */ private Class getReprClass() { return this.constr.getDeclaringClass(); } /** * @see org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.ParamGetter#getValue() */ public Object getValue() throws InvocationTargetException, ConvertRepresentationException, WebApplicationException { try { final Request request = Request.getCurrent(); if (!request.isEntityAvailable() || request.getEntity().getSize() == 0) { return null; } final Representation entity = request.getEntity(); if ((entity == null)/* || (entity is not empty) */) { return null; } return createInstance(entity); } catch (IllegalArgumentException e) { throw ConvertRepresentationException.object(getReprClass(), "the message body", e); } catch (InstantiationException e) { throw ConvertRepresentationException.object(getReprClass(), "the message body", e); } catch (IllegalAccessException e) { throw ConvertRepresentationException.object(getReprClass(), "the message body", e); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ContextHolder.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ContextHolde0000664000175000017500000000310211757206350034407 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.params; class ContextHolder implements ParameterList.ParamGetter { private final Object toInject; ContextHolder(Object toInject) { this.toInject = toInject; } /** * @see ContextInjector.ParamGetter#get */ public Object getValue() { return this.toInject; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/IntoRrcInjector.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/IntoRrcInjec0000664000175000017500000002260211757206350034346 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.params; import static org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil.isBeanSetter; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import javax.ws.rs.CookieParam; import javax.ws.rs.DefaultValue; import javax.ws.rs.Encoded; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.ext.Providers; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.CookieParamGetter; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.HeaderParamGetter; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.MatrixParamGetter; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.PathParamGetter; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.QueryParamGetter; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; /** * Helper class to inject into fields for @*Param into root resource * classes. * * @author Stephan Koops */ public class IntoRrcInjector extends ContextInjector { /** * @param jaxRsClass * @param tlContext * @param leaveClassEncoded * @param allProviders * all entity providers. * @param extensionBackwardMapping * @throws IllegalBeanSetterTypeException * @throws IllegalFieldTypeException * @throws IllegalPathParamTypeException */ public IntoRrcInjector(Class jaxRsClass, ThreadLocalizedContext tlContext, boolean leaveClassEncoded, Providers allProviders, ExtensionBackwardMapping extensionBackwardMapping) throws IllegalFieldTypeException, IllegalBeanSetterTypeException, IllegalPathParamTypeException { super(jaxRsClass, tlContext, allProviders, extensionBackwardMapping); init(jaxRsClass, tlContext, leaveClassEncoded); } private Type getConvGenTo(AccessibleObject fieldOrBeanSetter) { if (fieldOrBeanSetter instanceof Field) { final Field field = ((Field) fieldOrBeanSetter); return field.getGenericType(); } else if (fieldOrBeanSetter instanceof Method) { final Method beanSetter = ((Method) fieldOrBeanSetter); return beanSetter.getGenericParameterTypes()[0]; } else { throw new IllegalArgumentException( "The fieldOrBeanSetter must be a Field or a method"); } } private Class getConvTo(AccessibleObject fieldOrBeanSetter) { if (fieldOrBeanSetter instanceof Field) { final Field field = ((Field) fieldOrBeanSetter); return field.getType(); } else if (fieldOrBeanSetter instanceof Method) { final Method beanSetter = ((Method) fieldOrBeanSetter); return beanSetter.getParameterTypes()[0]; } else { throw new IllegalArgumentException( "The fieldOrBeanSetter must be a Field or a method"); } } /** * initiates the fields to cache the fields that needs injection. * * @param lcEnc * leave class encoded * @throws IllegalPathParamTypeException */ private void init(Class jaxRsClass, ThreadLocalizedContext tlContext, boolean lcEnc) throws IllegalPathParamTypeException { do { for (final Field field : jaxRsClass.getDeclaredFields()) { if (field.isAnnotationPresent(PathParam.class)) { add(field, newPathParamGetter(field, tlContext, lcEnc)); } else if (field.isAnnotationPresent(CookieParam.class)) { add(field, newCookieParamGetter(field, tlContext, lcEnc)); } else if (field.isAnnotationPresent(HeaderParam.class)) { add(field, newHeaderParamGetter(field, tlContext, lcEnc)); } else if (field.isAnnotationPresent(MatrixParam.class)) { add(field, newMatrixParamGetter(field, tlContext, lcEnc)); } else if (field.isAnnotationPresent(QueryParam.class)) { add(field, newQueryParamGetter(field, tlContext, lcEnc)); } } for (final Method method : jaxRsClass.getDeclaredMethods()) { if (isBeanSetter(method, PathParam.class)) { add(method, newPathParamGetter(method, tlContext, lcEnc)); } else if (isBeanSetter(method, CookieParam.class)) { add(method, newCookieParamGetter(method, tlContext, lcEnc)); } else if (isBeanSetter(method, HeaderParam.class)) { add(method, newHeaderParamGetter(method, tlContext, lcEnc)); } else if (isBeanSetter(method, MatrixParam.class)) { add(method, newMatrixParamGetter(method, tlContext, lcEnc)); } else if (isBeanSetter(method, QueryParam.class)) { add(method, newQueryParamGetter(method, tlContext, lcEnc)); } } jaxRsClass = jaxRsClass.getSuperclass(); } while (jaxRsClass != null); } private CookieParamGetter newCookieParamGetter( AccessibleObject fieldOrBeanSetter, ThreadLocalizedContext tlContext, boolean annoSaysLeaveClassEncoded) { return new CookieParamGetter(fieldOrBeanSetter .getAnnotation(CookieParam.class), fieldOrBeanSetter .getAnnotation(DefaultValue.class), getConvTo(fieldOrBeanSetter), getConvGenTo(fieldOrBeanSetter), tlContext, annoSaysLeaveClassEncoded); } private HeaderParamGetter newHeaderParamGetter( AccessibleObject fieldOrBeanSetter, ThreadLocalizedContext tlContext, boolean annoSaysLeaveClassEncoded) { return new HeaderParamGetter(fieldOrBeanSetter .getAnnotation(HeaderParam.class), fieldOrBeanSetter .getAnnotation(DefaultValue.class), getConvTo(fieldOrBeanSetter), getConvGenTo(fieldOrBeanSetter), tlContext, annoSaysLeaveClassEncoded); } private MatrixParamGetter newMatrixParamGetter( AccessibleObject fieldOrBeanSetter, ThreadLocalizedContext tlContext, boolean leaveClassEncoded) { return new MatrixParamGetter(fieldOrBeanSetter .getAnnotation(MatrixParam.class), fieldOrBeanSetter .getAnnotation(DefaultValue.class), getConvTo(fieldOrBeanSetter), getConvGenTo(fieldOrBeanSetter), tlContext, leaveClassEncoded || fieldOrBeanSetter.isAnnotationPresent(Encoded.class)); } private PathParamGetter newPathParamGetter( AccessibleObject fieldOrBeanSetter, ThreadLocalizedContext tlContext, boolean leaveClassEncoded) throws IllegalPathParamTypeException { return new PathParamGetter(fieldOrBeanSetter .getAnnotation(PathParam.class), fieldOrBeanSetter .getAnnotation(DefaultValue.class), getConvTo(fieldOrBeanSetter), getConvGenTo(fieldOrBeanSetter), tlContext, leaveClassEncoded || fieldOrBeanSetter.isAnnotationPresent(Encoded.class)); } private QueryParamGetter newQueryParamGetter( AccessibleObject fieldOrBeanSetter, ThreadLocalizedContext tlContext, boolean leaveClassEncoded) { return new QueryParamGetter(fieldOrBeanSetter .getAnnotation(QueryParam.class), fieldOrBeanSetter .getAnnotation(DefaultValue.class), getConvTo(fieldOrBeanSetter), getConvGenTo(fieldOrBeanSetter), tlContext, leaveClassEncoded || fieldOrBeanSetter.isAnnotationPresent(Encoded.class)); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/EntityGetter.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/EntityGetter0000664000175000017500000001075411757206350034451 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.params; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.lang.reflect.InvocationTargetException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; import org.restlet.Request; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.NoMessageBodyReaderException; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.ParamGetter; import org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyReader; import org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyReaderSet; import org.restlet.representation.Representation; /** * An EntityGetter converts the given entity from the request to the type * requested by the resource method.
* This class is not used, if a subclass of {@link Representation} is requested, * see {@link ReprEntityGetter} and its subclasses. * * @author Stephan Koops */ public class EntityGetter implements ParamGetter { private final Annotation[] annotations; /** * The class to convert to, directly as the type in the parameter list. */ protected volatile Class convToCl; private final Type convToGen; private final MessageBodyReaderSet mbrs; protected final ThreadLocalizedContext tlContext; EntityGetter(Class convToCl, Type convToGen, ThreadLocalizedContext tlContext, MessageBodyReaderSet mbrs, Annotation[] annotations) { this.tlContext = tlContext; this.mbrs = mbrs; this.convToCl = convToCl; this.convToGen = convToGen; this.annotations = annotations; } /** * @throws ConvertRepresentationException * @throws WebApplicationException * @throws NoMessageBodyReaderException * @see IntoRrcInjector.AbstractInjectObjectGetter#getValue(String) */ public Object getValue() throws ConvertRepresentationException, InvocationTargetException { final Request request = this.tlContext.get().getRequest(); final Representation entity = request.getEntity(); if (entity == null) { return null; } final MediaType mediaType = entity.getMediaType(); final MessageBodyReader mbr = this.mbrs.getBestReader(this.convToCl, this.convToGen, this.annotations, mediaType); if (mbr == null) { throw new NoMessageBodyReaderException(mediaType, this.convToCl); } final MultivaluedMap httpHeaders = Util .getJaxRsHttpHeaders(request); try { return mbr.readFrom(this.convToCl, this.convToGen, this.annotations, mediaType, entity.getCharacterSet(), httpHeaders, entity .getStream()); } catch (WebApplicationException wae) { throw wae; } catch (IOException e) { throw ConvertRepresentationException.object(this.convToCl, "the message body", e); } finally { entity.release(); } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ParamValueIter.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/params/ParamValueIt0000664000175000017500000000372511757206350034354 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers.params; import java.util.Iterator; import org.restlet.data.Parameter; import org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil; class ParamValueIter implements Iterator { private final Iterator paramIter; ParamValueIter(Iterable parameters) { this.paramIter = parameters.iterator(); } /** @see java.util.Iterator#hasNext() */ public boolean hasNext() { return this.paramIter.hasNext(); } /** @see java.util.Iterator#next() */ public String next() { return WrapperUtil.getValue(this.paramIter.next()); } /** @see java.util.Iterator#remove() */ public void remove() { this.paramIter.remove(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceMethodOrLocator.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceMethodOrLoc0000664000175000017500000000363111757206350034422 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import org.restlet.ext.jaxrs.internal.util.PathRegExp; /** * This interface describes a resource method, a sub resource method or a sub * resource locator. See section 1.5 and 3.3.1 of JAX-RS specification. * * @author Stephan Koops */ public interface ResourceMethodOrLocator extends RrcOrRml { /** * @return returns the name of the java method or sub resource locator */ public String getName(); /** * @return Returns the Regular Expression of the path. */ public PathRegExp getPathRegExp(); /** * @return Returns the wrapped resource class */ public ResourceClass getResourceClass(); } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/RrcOrRml.java0000664000175000017500000000315411757206350033155 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import org.restlet.ext.jaxrs.internal.util.PathRegExp; /** * Super interface or {@link RootResourceClass} and * {@link ResourceMethodOrLocator} for implementation reasons. * * @author Stephan Koops */ public interface RrcOrRml { /** * @return Returns the Regular Expression of the path. */ public PathRegExp getPathRegExp(); } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java0000664000175000017500000002674311757206350033742 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.ws.rs.HeaderParam; import javax.ws.rs.HttpMethod; import javax.ws.rs.MatrixParam; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.restlet.Request; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalTypeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingConstructorException; /** * Utility methods for the wrappers. * * @author Stephan Koops */ public class WrapperUtil { private static final String JAX_RS_PACKAGE_PREFIX = "javax.ws.rs"; /** * Checks, if the given annotation is annotated with at least one JAX-RS * related annotation. * * @param javaMethod * Java method, class or something like that. * @return true, if the given accessible object is annotated with any * JAX-RS-Annotation. */ static boolean checkForJaxRsAnnotations(Method javaMethod) { for (final Annotation annotation : javaMethod.getAnnotations()) { final Class annoType = annotation .annotationType(); if (annoType.getName().startsWith(JAX_RS_PACKAGE_PREFIX)) { return true; } if (annoType.isAnnotationPresent(HttpMethod.class)) { return true; } } return false; } /** * Checks if the parameters for the constructor are valid for a JAX-RS root * resource class. * * @param paramAnnotationss * @param parameterTypes * @returns true, if the * @throws IllegalTypeException * If a parameter is annotated with {@link Context}, but the * type is invalid (must be UriInfo, Request or HttpHeaders). */ private static boolean checkParamAnnotations(Constructor constr) { final Annotation[][] paramAnnotationss = constr .getParameterAnnotations(); final Class[] parameterTypes = constr.getParameterTypes(); for (int i = 0; i < paramAnnotationss.length; i++) { final Annotation[] parameterAnnotations = paramAnnotationss[i]; final Class parameterType = parameterTypes[i]; final boolean ok = checkParameterAnnotation(parameterAnnotations, parameterType); if (!ok) { return false; } } return true; } /** * Checks, if the annotations are valid for a runtime environment handled * constructor. * * @param parameterAnnotations * @param parameterType * @return */ private static boolean checkParameterAnnotation( Annotation[] parameterAnnotations, Class parameterType) { if (parameterAnnotations.length == 0) { return false; } for (final Annotation annotation : parameterAnnotations) { final Class annotationType = annotation .annotationType(); if (annotationType.equals(HeaderParam.class)) { continue; } else if (annotationType.equals(PathParam.class)) { continue; } else if (annotationType.equals(Context.class)) { if (parameterType.equals(UriInfo.class)) { continue; } if (parameterType.equals(Request.class)) { continue; } if (parameterType.equals(HttpHeaders.class)) { continue; } if (parameterType.equals(SecurityContext.class)) { continue; } return false; } else if (annotationType.equals(MatrixParam.class)) { continue; } else if (annotationType.equals(QueryParam.class)) { continue; } return false; } return true; } /** * Converts the given mimes to a List of MediaTypes. Will never returns * null. * * @param mimes * @return Returns an unmodifiable List of MediaTypes */ public static List convertToMediaTypes(String[] mimes) { final List mediaTypes; mediaTypes = new ArrayList(mimes.length); for (String mime : mimes) { if (mime == null) { mediaTypes.add(MediaType.ALL); } else { mediaTypes.add(MediaType.valueOf(mime)); } } return Collections.unmodifiableList(mediaTypes); } /** * Creates an instance of the root resource class. * * @param constructor * @param args * @return the created instance * @throws InvocationTargetException * @throws InstantiateException */ public static Object createInstance(Constructor constructor, Object... args) throws InvocationTargetException, InstantiateException { try { return constructor.newInstance(args); } catch (IllegalArgumentException e) { throw new InstantiateException("Could not instantiate " + constructor.getDeclaringClass(), e); } catch (InstantiationException e) { throw new InstantiateException("Could not instantiate " + constructor.getDeclaringClass(), e); } catch (IllegalAccessException e) { throw new InstantiateException("Could not instantiate " + constructor.getDeclaringClass(), e); } } /** * Finds the constructor to use by the JAX-RS runtime. * * @param jaxRsClass * the root resource or provider class. * @param rrcOrProvider * "root resource class" or "provider" * @return Returns the constructor to use for the given root resource class * or provider. If no constructor could be found, null is returned. * Than try {@link Class#newInstance()} * @throws MissingConstructorException */ public static Constructor findJaxRsConstructor(Class jaxRsClass, String rrcOrProvider) throws MissingConstructorException { Constructor constructor = null; int constructorParamNo = Integer.MIN_VALUE; for (final Constructor constr : jaxRsClass.getConstructors()) { if (!Modifier.isPublic(constr.getModifiers())) { continue; } final int constrParamNo = constr.getParameterTypes().length; // TODo warn if multiple constrs are possible (see spec f. details) if (constrParamNo <= constructorParamNo) { continue; // ignore this constructor } if (!checkParamAnnotations(constr)) { continue; // ignore this constructor } constructor = constr; constructorParamNo = constrParamNo; } if (constructor != null) { return constructor; } throw new MissingConstructorException(jaxRsClass, rrcOrProvider); } /** * Returns the HTTP method related to the given java method. * * @param javaMethod * @return */ static org.restlet.data.Method getHttpMethod(Method javaMethod) { for (final Annotation annotation : javaMethod.getAnnotations()) { final Class annoType = annotation .annotationType(); final HttpMethod httpMethodAnnot = annoType .getAnnotation(HttpMethod.class); if (httpMethodAnnot != null) { // Annotation of Annotation of the method is the HTTP-Method final String httpMethodName = httpMethodAnnot.value(); return org.restlet.data.Method.valueOf(httpMethodName); // NICE check if another designator is available: reject or warn } } return null; } /** * Returns the value from the given Parameter. If the given parameter is * null, null will returned. If the parameter is not null, but it's value, * "" is returned. * * @param parameter * @return the value from the given Parameter. If the given parameter is * null, null will returned. If the parameter is not null, but it's * value, "" is returned. */ public static String getValue(Parameter parameter) { if (parameter == null) { return null; } final String paramValue = parameter.getValue(); if (paramValue == null) { return ""; } return paramValue; } /** * Checks, if the given method is a bean setter and annotated with the given * annotation. If it is a bean setter, the accessible attribute of is set * the method is set to true. * * @param method * @param annotationClass * @return true, if the method is a bean setter, or false if not * @throws SecurityException */ public static boolean isBeanSetter(Method method, Class annotationClass) throws SecurityException { if (method.isAnnotationPresent(annotationClass) && method.getName().startsWith("set") && (method.getParameterTypes().length == 1)) { return true; } return false; } /** * Checks, if the method is volatile(the return type of a sub class differs * from the return type of the superclass, but is compatibel). * * @param javaMethod * @return true, if the method is volatile, otherwise false. */ static boolean isVolatile(Method javaMethod) { return Modifier.isVolatile(javaMethod.getModifiers()); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/PerRequestRootResourceClass.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/PerRequestRootResou0000664000175000017500000001213211757206350034510 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalBeanSetterTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalConstrParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalFieldTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.MissingConstructorException; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; /** * @author Stephan * */ public class PerRequestRootResourceClass extends RootResourceClass { /** * @param jaxRsClass * @param tlContext * @param jaxRsProviders * @param extensionBackwardMapping * @param logger * @throws IllegalArgumentException * @throws MissingAnnotationException * @throws IllegalPathOnClassException * @throws MissingConstructorException * @throws IllegalConstrParamTypeException * @throws IllegalFieldTypeException * @throws IllegalBeanSetterTypeException * @throws IllegalPathParamTypeException */ PerRequestRootResourceClass(Class jaxRsClass, ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalArgumentException, MissingAnnotationException, IllegalPathOnClassException, MissingConstructorException, IllegalConstrParamTypeException, IllegalFieldTypeException, IllegalBeanSetterTypeException, IllegalPathParamTypeException { super(jaxRsClass, tlContext, jaxRsProviders, extensionBackwardMapping, logger); } /** * Creates an or gets the instance of this root resource class. * * @param objectFactory * object responsible for instantiating the root resource * class. Optional, thus can be null. * @return the instantiated root resource object. * @throws InvocationTargetException * @throws InstantiateException * @throws MissingAnnotationException * @throws WebApplicationException */ @Override public ResourceObject getInstance(ObjectFactory objectFactory) throws InstantiateException, InvocationTargetException { Object instance = null; if (objectFactory != null) { instance = objectFactory.getInstance(this.jaxRsClass); } if (instance == null) { try { final Object[] args = this.constructorParameters.get(); instance = WrapperUtil.createInstance(this.constructor, args); } catch (ConvertRepresentationException e) { // is (or should be :-) ) not possible throw new ImplementationException("Must not be possible", e); } } final ResourceObject rootResourceObject; rootResourceObject = new ResourceObject(instance, this); try { this.injectHelper.injectInto(instance, true); } catch (InjectException e) { throw new InstantiateException(e); } return rootResourceObject; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceMethod.java0000664000175000017500000003612511757206350034407 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.wrappers; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Variant; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertCookieParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertHeaderParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertMatrixParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertPathParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertQueryParamException; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalMethodParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathParamTypeException; import org.restlet.ext.jaxrs.internal.exceptions.MethodInvokeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.NoMessageBodyReaderException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.SortedMetadata; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; /** * This class wraps JAX-RS resource methods and sub resource methods.
* It does not wrap sub resource locators; see {@link SubResourceLocator} * * @author Stephan Koops */ public class ResourceMethod extends AbstractMethodWrapper implements ResourceMethodOrLocator { // NICE a subset of MessageBodyReaders could be cached here. // . . . . . . . . . . (the concrete media type of the request could differ) // NICE check, which subset of MessageBodyWriters could be cached here. // . . (the media type is available via @Produces on the entity provider) /** * the Java method that should be referenced for annotations. This method * could be different from the method is called for executing, see section * 3.6 "Annotation Inheritance" of JSR-311-spec. * * @see AbstractMethodWrapper#executeMethod */ private final Method annotatedMethod; /** @see Consumes */ private final List consumedMimes; private final org.restlet.data.Method httpMethod; /** @see Produces */ private final List producedMimes; /** * Contains the list of supported {@link Variant}s (lazy initialized by * {@link #getSupportedVariants()}. */ private final Collection supportedVariants; /** * Creates a wrapper for a resource method. * * @param executeMethod * the Java method to wrap. * @param annotatedMethod * the java method that contains the annotations for this method. * @param resourceClass * the wrapped class of the method. * @param httpMethod * the HTTP method of the Java method. It will be checked be the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}, so avoiding double * work. It will be requested from the javaMethod. * @param tlContext * the {@link ThreadLocalizedContext} of the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * @param jaxRsProviders * all entity providers * @param extensionBackwardMapping * the extension backward mapping * @param logger * @throws IllegalPathOnMethodException * @throws MissingAnnotationException * @throws IllegalArgumentException * if the annotated method is null * @throws IllegalMethodParamTypeException * if one of the method parameters annotated with @ * {@link Context} has a type that must not be annotated with * @{@link Context}. * @throws IllegalPathParamTypeException */ ResourceMethod(Method executeMethod, Method annotatedMethod, ResourceClass resourceClass, org.restlet.data.Method httpMethod, ThreadLocalizedContext tlContext, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, Logger logger) throws IllegalPathOnMethodException, IllegalArgumentException, MissingAnnotationException, IllegalMethodParamTypeException, IllegalPathParamTypeException { super(executeMethod, annotatedMethod, resourceClass, tlContext, jaxRsProviders, extensionBackwardMapping, true, logger); this.annotatedMethod = annotatedMethod; if (httpMethod != null) { this.httpMethod = httpMethod; } else { this.httpMethod = WrapperUtil.getHttpMethod(this.annotatedMethod); } this.consumedMimes = createConsumedMimes(); this.producedMimes = createProducedMimes(); this.supportedVariants = createSupportedVariants(); } /** * Creates the list of the consumed mimes from the * {@link AbstractMethodWrapper#annotatedMethod} and the * {@link AbstractMethodWrapper#executeMethod} to be stored in the final * instance variable {@link #consumedMimes}. */ private List createConsumedMimes() { Consumes consumes = this.annotatedMethod.getAnnotation(Consumes.class); if (consumes == null) { consumes = this.executeMethod.getDeclaringClass().getAnnotation( Consumes.class); } if (consumes != null) { return WrapperUtil.convertToMediaTypes(consumes.value()); } return Collections.singletonList(MediaType.ALL); } /** * Creates the list of the produced mimes from the * {@link AbstractMethodWrapper#annotatedMethod} and the * {@link AbstractMethodWrapper#executeMethod} to be stored in the final * instance variable {@link #producedMimes}. */ private List createProducedMimes() { Produces produces; produces = this.annotatedMethod.getAnnotation(Produces.class); if (produces == null) { produces = this.executeMethod.getDeclaringClass().getAnnotation( Produces.class); } if (produces != null) { return WrapperUtil.convertToMediaTypes(produces.value()); } return Collections.emptyList(); } /** * Creates the list of the supported variants from the * {@link #getProducedMimes()}to be stored in the final instance variable * {@link #supportedVariants}. */ private Collection createSupportedVariants() { final Collection supportedVariants = new ArrayList(); for (final MediaType mediaType : getProducedMimes()) { javax.ws.rs.core.MediaType mt; mt = Converter.toJaxRsMediaType(mediaType); supportedVariants.add(new Variant(mt, null, null)); } return supportedVariants; } /** * Returns the array of the annotations on the Java method * * @return the array of the annotations on the Java method * @see Method#getAnnotations() */ public Annotation[] getAnnotations() { return this.annotatedMethod.getAnnotations(); } /** * @return Returns an unmodifiable List with the MediaTypes the given * resourceMethod consumes. If no consumeMime is given, this method * returns a List with MediaType.ALL. Will never return null. */ public List getConsumedMimes() { return this.consumedMimes; } /** * Returns the generic return type of the wrapped method. * * @return the generic return type of the wrapped method. * @see Method#getGenericReturnType() */ public Type getGenericReturnType() { return this.executeMethod.getGenericReturnType(); } /** * @return Returns the HTTP method supported by the wrapped java method. */ public org.restlet.data.Method getHttpMethod() { return this.httpMethod; } /** * @return Returns an unmodifiable List of MediaTypes the given Resource * Method. if the method is not annotated with {@link Produces}, * than the {@link Produces} of the Resource class is returned. If * no {@link Produces} can be found, an empty (also unmodifiable) * List will returned.
* This method never returns null. */ public List getProducedMimes() { return this.producedMimes; } /** * Returns the {@link Variant}s supported by this resource method. * * @return the {@link Variant}s supported by this resource method. */ public Collection getSupportedVariants() { return this.supportedVariants; } /** * Invokes the method and returned the created representation for the * response. * * @param resourceObject * @return the unwrapped returned object by the wrapped method. * @throws MethodInvokeException * @throws InvocationTargetException * @throws NoMessageBodyReaderException * @throws MissingAnnotationException * @throws ConvertCookieParamException * @throws ConvertQueryParamException * @throws ConvertMatrixParamException * @throws ConvertPathParamException * @throws ConvertHeaderParamException * @throws ConvertRepresentationException * @throws WebApplicationException */ public Object invoke(ResourceObject resourceObject) throws MethodInvokeException, InvocationTargetException, ConvertRepresentationException, WebApplicationException { try { return internalInvoke(resourceObject); } catch (IllegalArgumentException e) { throw new MethodInvokeException("Could not invoke " + this.executeMethod, e); } catch (IllegalAccessException e) { throw new MethodInvokeException("Could not invoke " + this.executeMethod, e); } } /** * Check if this method supports the media type to produce for a request. * * @param accMediaTypess * The Media Types the client would accept, ordered by quality. * See {@link SortedMetadata} * @return Returns true, if the give MediaType is supported by the method, * or no MediaType is given for the method, otherweise false. */ public boolean isAcceptedMediaTypeSupported( SortedMetadata accMediaTypess) { if ((accMediaTypess == null) || accMediaTypess.isEmpty()) { return true; } final List prodMimes = getProducedMimes(); if (prodMimes.isEmpty()) { return true; } for (final MediaType producedMediaType : prodMimes) { for (final MediaType accMediaType : accMediaTypess) { if (accMediaType.isCompatible(producedMediaType)) { return true; } } } return false; } /** * @param resourceMethod * the resource method to check * @param givenMediaType * the MediaType of the request entity * @return Returns true, if the given MediaType is supported by the method, * or no MediaType is given for the method, otherweise false; */ public boolean isGivenMediaTypeSupported(MediaType givenMediaType) { if (givenMediaType == null) { return true; } for (final MediaType consumedMime : getConsumedMimes()) { if (consumedMime.includes(givenMediaType)) { return true; } } return false; } /** * * @param resourceMethod * @param requestedMethod * @return true, if the gien java method is annotated with a runtime * designator for the given requested Method. If the requested * method is null, than the method returns true, when the method is * annotated with any runtime desginator. * @see #annotatedWithMethodDesignator(Method) */ public boolean isHttpMethodSupported(org.restlet.data.Method requestedMethod) { return isHttpMethodSupported(requestedMethod, false); } /** * Checks, if this method suppors the given HTTP method. * * @param requestedMethod * the requested Method * @param alsoGet * if true, than this method returns also true, if this method is * GET. This functionality is needed for HEAD. * @return true, if this method supports the given HTTP method. Returns also * true, if alsoGet is true and this method is true. * @throws IllegalArgumentException */ public boolean isHttpMethodSupported( org.restlet.data.Method requestedMethod, boolean alsoGet) throws IllegalArgumentException { if (requestedMethod == null) { throw new IllegalArgumentException( "null is not a valid HTTP method"); } if (alsoGet && this.httpMethod.equals(org.restlet.data.Method.GET)) { return true; } return this.httpMethod.equals(requestedMethod); } @Override public String toString() { return this.getClass().getSimpleName() + "[" + this.executeMethod.toString() + ", " + this.httpMethod + "]"; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/0000775000175000017500000000000011757206350031123 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/NoMessageBodyReaderException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/NoMessageBodyRead0000664000175000017500000000604611757206350034347 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.MessageBodyReader; import org.restlet.data.MediaType; /** * This kind of Exception is thrown, if MessageBodyReaders are used, but are not * available. Normally this does not occurs. * * @author Stephan Koops */ public class NoMessageBodyReaderException extends WebApplicationException { private static final long serialVersionUID = 9177449724300611418L; private final Class paramType; private final MediaType mediaType; /** * @param paramType * @param mediaType */ public NoMessageBodyReaderException(MediaType mediaType, Class paramType) { super(Status.UNSUPPORTED_MEDIA_TYPE); // NICE super("No MessageBodyR found for "+mediaType+" and "+paramType); this.mediaType = mediaType; this.paramType = paramType; } /** * Returns the media type for which (in combination with the java parameter * type, see {@link #getParamType()}) no {@link MessageBodyReader} was * found. * * @return the media type for which (in combination with the java parameter * type, see {@link #getParamType()}) no {@link MessageBodyReader} * was found. */ public MediaType getMediaType() { return this.mediaType; } /** * Returns the java parameter type for which (in combination with the media * type, see {@link #getMediaType()}) no {@link MessageBodyReader} was * found. * * @return the java parameter type for which (in combination with the media * type, see {@link #getMediaType()}) no {@link MessageBodyReader} * was found. */ public Class getParamType() { return this.paramType; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertParameterException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertParameterE0000664000175000017500000000641511757206350034442 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * Thrown if a value for an instance field or a parameter for a constructor, a * resource method or a bean setter could not be instantiated. * * @author Stephan Koops */ public class ConvertParameterException extends JaxRsException { private static final long serialVersionUID = 951579935427584482L; /** * Throws a message, that the given String value could not be converted to a * primitive. * * @param paramType * @param unparseableValue * @param cause * @return (static the created ConvertParameterException for the * compiler) * @throws ConvertParameterException */ public static ConvertParameterException object(Class paramType, Object unparseableValue, Throwable cause) throws ConvertParameterException { throw new ConvertParameterException("Could not convert " + unparseableValue + " to a " + paramType.getName(), cause); } /** * Throws a message, that the given String value could not be converted to a * primitive. * * @param paramType * @param unparseableValue * @param cause * @return (static the created ConvertParameterException for the * compiler) * @throws ConvertParameterException */ public static ConvertParameterException primitive(Class paramType, String unparseableValue, Throwable cause) throws ConvertParameterException { throw new ConvertParameterException("Could not convert the String \"" + unparseableValue + "\" to a " + paramType, cause); } /** * @param message */ private ConvertParameterException(String message) { super(message); } /** * @param message * @param cause */ private ConvertParameterException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ private ConvertParameterException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertFormParamException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertFormParamE0000664000175000017500000000356011757206350034404 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; /** * This kind of exception is thrown, if a query parameter could not be * converted. * * @author Stephan Koops * @see QueryParam */ public class ConvertFormParamException extends WebApplicationException { private static final long serialVersionUID = 131640120766355816L; /** * @param cpe */ public ConvertFormParamException(ConvertParameterException cpe) { super(cpe.getCause(), Status.BAD_REQUEST); setStackTrace(cpe.getStackTrace()); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertCookieParamException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertCookiePara0000664000175000017500000000371111757206350034426 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.CookieParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; /** * This kind of exception is thrown, if a query parameter could not be * converted. * * @author Stephan Koops * @see CookieParam */ public class ConvertCookieParamException extends WebApplicationException { private static final long serialVersionUID = 9098614715395362234L; // REQUESTED allow subclass of WebAppExc in algorithms for special handling? /** * @param cpe */ public ConvertCookieParamException(ConvertParameterException cpe) { super(cpe.getCause(), Status.BAD_REQUEST); setStackTrace(cpe.getStackTrace()); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathOnMethodException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathOnMeth0000664000175000017500000000343711757206350034356 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.Path; /** * This kind of exception is thrown, when an @{@link Path} annotation of a * method contains illegal charactres. * * @author Stephan Koops */ public class IllegalPathOnMethodException extends IllegalPathException { private static final long serialVersionUID = -6655373875338074948L; /** * @param ipe */ public IllegalPathOnMethodException(IllegalPathException ipe) { super(ipe.getPath(), ipe.getMessage()); setStackTrace(ipe.getStackTrace()); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalFieldTypeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalFieldTypeE0000664000175000017500000000337211757206350034337 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This kind of exception is thrown, when a type of a field to inject must not * be annotated with the given JAX-RS annotation * * @author Stephan Koops */ public class IllegalFieldTypeException extends IllegalTypeException { private static final long serialVersionUID = 6423619202690501704L; /** * @param ite */ public IllegalFieldTypeException(IllegalTypeException ite) { super(ite.getMessage()); setStackTrace(ite.getStackTrace()); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertQueryParamException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertQueryParam0000664000175000017500000000356011757206350034501 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; /** * This kind of exception is thrown, if a query parameter could not be * converted. * * @author Stephan Koops * @see QueryParam */ public class ConvertQueryParamException extends WebApplicationException { private static final long serialVersionUID = 131640120766355816L; /** * @param cpe */ public ConvertQueryParamException(ConvertParameterException cpe) { super(cpe.getCause(), Status.NOT_FOUND); setStackTrace(cpe.getStackTrace()); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalConstrParamTypeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalConstrPara0000664000175000017500000000334411757206350034420 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This kind of exception is thrown, when a type of a parameter of constructor * is illegal. * * @author Stephan Koops */ public class IllegalConstrParamTypeException extends IllegalTypeException { private static final long serialVersionUID = 6423619202690501704L; /** * @param ite */ public IllegalConstrParamTypeException(IllegalTypeException ite) { super(ite.getMessage()); setStackTrace(ite.getStackTrace()); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathExcept0000664000175000017500000000673111757206350034414 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.Path; /** * This kind of exception is thrown, when an @{@link Path} annotation * contains illegal characters. * * @author Stephan Koops */ public class IllegalPathException extends JaxRsException { private static final long serialVersionUID = 6796414811480666857L; private static String createMessage(IllegalArgumentException iae, Path path) { if (iae != null) { final Throwable cause = iae.getCause(); if (cause != null) { final String message = cause.getMessage(); if ((message == null) || (message.length() == 0)) { return "The given path (" + path + ") is invalid"; } } } return null; } private final Path path; /** * * @param path * the invalid path * @param iae */ public IllegalPathException(Path path, IllegalArgumentException iae) { super(createMessage(iae, path), iae); this.path = path; } /** * * @param path * @param message */ public IllegalPathException(Path path, String message) { super(message); this.path = path; } /** * * @param path * @param message * @param iae */ public IllegalPathException(Path path, String message, IllegalArgumentException iae) { super(message, iae); this.path = path; } /** * Returns the cause {@link IllegalArgumentException}. If not available, it * is created. * * @see java.lang.Throwable#getCause() */ @Override public IllegalArgumentException getCause() { final Throwable cause = super.getCause(); if (cause instanceof IllegalArgumentException) { return (IllegalArgumentException) cause; } final IllegalArgumentException iae = new IllegalArgumentException( getMessage()); if (cause != null) { iae.setStackTrace(cause.getStackTrace()); } return iae; } /** * Returns the Illegal Path. * * @return the Illegal Path. */ public Path getPath() { return this.path; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalMethodParamTypeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalMethodPara0000664000175000017500000000347311757206350034373 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This kind of exception is thrown, when a type of a method ((sub) resource * method or asub resource locator) parameter must not be annotated with the * given JAX-RS annotation * * @author Stephan Koops */ public class IllegalMethodParamTypeException extends IllegalTypeException { private static final long serialVersionUID = 6423619202690501704L; /** * @param ite */ public IllegalMethodParamTypeException(IllegalTypeException ite) { super(ite.getMessage()); setStackTrace(ite.getStackTrace()); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/MissingAnnotationException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/MissingAnnotation0000664000175000017500000000364211757206350034517 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This exception is thrown, if an required annotation is missing. * * @author Stephan Koops */ public class MissingAnnotationException extends JaxRsException { private static final long serialVersionUID = -1900088092745095670L; /** * @param message */ public MissingAnnotationException(String message) { super(message); } /** * @param message * @param cause */ public MissingAnnotationException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public MissingAnnotationException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/UnsupportedMediaTypeWebAppException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/UnsupportedMediaT0000664000175000017500000000505011757206350034462 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import java.util.Collection; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.Status; /** * The server is refusing to service the request because the entity of the * request is in a format not accepted by the requested resource for the * requested method. * * @author Stephan Koops * @see
RFC 2616, * Section 10.4.16, "415 Unsupported Media Type" */ public class UnsupportedMediaTypeWebAppException extends WebApplicationException { private static final long serialVersionUID = 767927925135821476L; private final Collection accepted; /** * @param accepted * the accepted Variants. */ public UnsupportedMediaTypeWebAppException(Collection accepted) { super(Status.UNSUPPORTED_MEDIA_TYPE); if (accepted == null) { throw new IllegalArgumentException( "You have to give a collection of accepted Variants."); } this.accepted = accepted; } /** * Returns the accepted {@link Variant}s. * * @return the accepted MediaTypes. */ public Collection getAccepted() { return this.accepted; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/NotAcceptableWebAppException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/NotAcceptableWebA0000664000175000017500000000510111757206350034306 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import java.util.Collection; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.Status; /** * The resource identified by the request is only capable of generating response * entities which have content characteristics not acceptable according to the * accept headers sent in the request. * * @author Stephan Koops * @see RFC 2616, * Section 10.4.7, "406 Not Acceptable" */ public class NotAcceptableWebAppException extends WebApplicationException { private static final long serialVersionUID = 6895779829973209211L; private final Collection supported; /** * @param supported * the supported variants, selectable by the accept headers. */ public NotAcceptableWebAppException(Collection supported) { super(Status.NOT_ACCEPTABLE); if (supported == null) { throw new IllegalArgumentException( "The allowed variants must not be null"); } this.supported = supported; } /** * Returns the supported {@link Variant}s. * * @return the supported variants. */ public Collection getSupported() { return this.supported; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/InjectException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/InjectException.j0000664000175000017500000000371411757206350034376 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.core.Context; /** * This kind of exception is thrown, when an object could not be injected in a * field or bean setter annotated with {@link Context} or other annotations. * * @author Stephan Koops */ public class InjectException extends JaxRsException { private static final long serialVersionUID = 6796414811480666857L; /** * @param mie */ public InjectException(MethodInvokeException mie) { super(mie.getMessage(), mie.getCause()); setStackTrace(mie.getStackTrace()); } /** * @param message * @param cause */ public InjectException(String message, Throwable cause) { super(message, cause); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathParamTypeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathParamT0000664000175000017500000000403011757206350034336 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.PathParam; /** * Thrown, if a type of a @{@link PathParam} annotated parameter, field or * bean setter is not valid. * * @author Stephan Koops */ public class IllegalPathParamTypeException extends IllegalParamTypeException { private static final long serialVersionUID = 6438816194995561330L; /** * @param message */ public IllegalPathParamTypeException(String message) { super(message); } /** * @param message * @param throwable */ public IllegalPathParamTypeException(String message, Throwable throwable) { super(message, throwable); } /** * @param throwable */ public IllegalPathParamTypeException(Throwable throwable) { super(throwable); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertRepresentationException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertRepresenta0000664000175000017500000000511111757206350034515 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * Thrown if the entity could not be deserialized. * * @author Stephan Koops */ public class ConvertRepresentationException extends JaxRsException { private static final long serialVersionUID = 951579935427584482L; /** * Throws a message, that the given String value could not be converted to a * primitive. * * @param paramType * @param unparseableValue * @param cause * @return (static the created ConvertRepresentationException for the * compiler) * @throws ConvertRepresentationException */ public static ConvertRepresentationException object(Class paramType, Object unparseableValue, Throwable cause) throws ConvertRepresentationException { throw new ConvertRepresentationException("Could not convert " + unparseableValue + " to a " + paramType.getName(), cause); } /** * @param message */ private ConvertRepresentationException(String message) { super(message); } /** * @param message * @param cause */ private ConvertRepresentationException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ private ConvertRepresentationException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertMatrixParamException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertMatrixPara0000664000175000017500000000356611757206350034471 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.MatrixParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; /** * This kind of exception is thrown, if a matrix parameter could not be * converted. * * @author Stephan Koops * @see MatrixParam */ public class ConvertMatrixParamException extends WebApplicationException { private static final long serialVersionUID = 6704339151884788476L; /** * @param cpe */ public ConvertMatrixParamException(ConvertParameterException cpe) { super(cpe.getCause(), Status.NOT_FOUND); setStackTrace(cpe.getStackTrace()); } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ProviderNotInitializableException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ProviderNotInitia0000664000175000017500000000323411757206350034461 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * Indicates, that a povider could not be used. The reason exception is already * logged or whatever. * * @author Stephan Koops */ public class ProviderNotInitializableException extends JaxRsException { private static final long serialVersionUID = 5567215105027326112L; /** * @param message */ public ProviderNotInitializableException() { super(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ImplementationException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ImplementationExc0000664000175000017500000000376211757206350034503 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * Indicates, that the JAX-RS implementation observed, that it contains an error * in itself. An example is, if a default provider could not be loaded. * * @author Stephan Koops */ public class ImplementationException extends JaxRsRuntimeException { private static final long serialVersionUID = 5635188228961655076L; /** * @param message */ public ImplementationException(String message) { super(message); } /** * @param message * @param cause */ public ImplementationException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public ImplementationException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/MissingConstructorException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/MissingConstructo0000664000175000017500000000363511757206350034552 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This exception is thrown, if a root resource class or a provider has no valid * contructor * * @author Stephan Koops */ public class MissingConstructorException extends JaxRsException { private static final long serialVersionUID = 8213720039895185212L; /** * @param jaxRsClass * the root resource or provider class. * @param rrcOrProvider * "root resource class" or "provider" */ public MissingConstructorException(Class jaxRsClass, String rrcOrProvider) { super("the " + rrcOrProvider + " " + jaxRsClass.getName() + " has no valid constructor"); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathOnClassException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalPathOnClas0000664000175000017500000000345511757206350034343 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.Path; /** * This kind of exception is thrown, when an @{@link Path} annotation of a * root resource class contains illegal characters. * * @author Stephan Koops * */ public class IllegalPathOnClassException extends IllegalPathException { private static final long serialVersionUID = 6423619202690501704L; /** * @param ipe */ public IllegalPathOnClassException(IllegalPathException ipe) { super(ipe.getPath(), ipe.getMessage()); setStackTrace(ipe.getStackTrace()); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalBeanSetterTypeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalBeanSetter0000664000175000017500000000340011757206350034371 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This kind of exception is thrown, when a type of a bean setter must not be * annotated with the given JAX-RS annotation * * @author Stephan Koops */ public class IllegalBeanSetterTypeException extends IllegalTypeException { private static final long serialVersionUID = 6423619202690501704L; /** * @param ite */ public IllegalBeanSetterTypeException(IllegalTypeException ite) { super(ite.getMessage()); setStackTrace(ite.getStackTrace()); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalAnnotationException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalAnnotation0000664000175000017500000000322511757206350034454 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import java.lang.annotation.Annotation; /** * @author Stephan Koops * */ public class IllegalAnnotationException extends Exception { private static final long serialVersionUID = -6746568704260973210L; /** * @param annotation */ public IllegalAnnotationException(Annotation annotation) { super("The annotation " + annotation + " is not allowed"); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/JaxRsRuntimeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/JaxRsRuntimeExcep0000664000175000017500000000364211757206350034433 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This class is the super class for the runtime exception in this * implementation. * * @author Stephan Koops */ public class JaxRsRuntimeException extends RuntimeException { private static final long serialVersionUID = -7662465289573982489L; /** * @param message */ public JaxRsRuntimeException(String message) { super(message); } /** * @param message * @param cause */ public JaxRsRuntimeException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public JaxRsRuntimeException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertHeaderParamException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertHeaderPara0000664000175000017500000000357111757206350034411 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.HeaderParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; /** * This kind of exception is thrown, if a header parameter could not be * converted. * * @author Stephan Koops * @see HeaderParam */ public class ConvertHeaderParamException extends WebApplicationException { private static final long serialVersionUID = -2880948194279374251L; /** * @param cpe */ public ConvertHeaderParamException(ConvertParameterException cpe) { super(cpe.getCause(), Status.BAD_REQUEST); setStackTrace(cpe.getStackTrace()); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertPathParamException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/ConvertPathParamE0000664000175000017500000000355111757206350034375 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; /** * This kind of exception is thrown, if a path parameter could not be converted. * * @author Stephan Koops * @see PathParam */ public class ConvertPathParamException extends WebApplicationException { private static final long serialVersionUID = 7259271064216490329L; /** * @param cpe */ public ConvertPathParamException(ConvertParameterException cpe) { super(cpe.getCause(), Status.NOT_FOUND); setStackTrace(cpe.getStackTrace()); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalTypeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalTypeExcept0000664000175000017500000000366411757206350034443 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This kind of exception is thrown, when an annotated constructor or method * parameter has an illegal type. * * @author Stephan Koops */ public class IllegalTypeException extends JaxRsException { private static final long serialVersionUID = 6796414811480666857L; /** * @param message */ public IllegalTypeException(String message) { super(message); } /** * @param message * @param cause */ public IllegalTypeException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public IllegalTypeException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/JaxRsException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/JaxRsException.ja0000664000175000017500000000374711757206350034360 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * This class is the super class for the most exception classes in this * implementation. * * @author Stephan Koops */ public abstract class JaxRsException extends Exception { private static final long serialVersionUID = -7662465289573982489L; /** * For subclasses only */ JaxRsException() { super(); } /** * @param message */ public JaxRsException(String message) { super(message); } /** * @param message * @param cause */ public JaxRsException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public JaxRsException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/MethodInvokeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/MethodInvokeExcep0000664000175000017500000000404711757206350034434 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; import java.lang.reflect.InvocationTargetException; /** * Indicates, that an invoke of a resource method was not possible. If the * invoked method throws a Throwable, the {@link InvocationTargetException} must * be used. * * @author Stephan Koops */ public class MethodInvokeException extends JaxRsException { private static final long serialVersionUID = 1766085431784085073L; /** * @param message */ public MethodInvokeException(String message) { super(message); } /** * @param message * @param cause */ public MethodInvokeException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public MethodInvokeException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalParamTypeException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/IllegalParamTypeE0000664000175000017500000000373511757206350034357 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * Superclass for Exceptions, if a type of a @*Param annotated parameter, * field or bean setter is not valid. * * @author Stephan Koops */ public abstract class IllegalParamTypeException extends JaxRsException { private static final long serialVersionUID = 1L; /** * @param message */ public IllegalParamTypeException(String message) { super(message); } /** * @param message * @param throwable */ public IllegalParamTypeException(String message, Throwable throwable) { super(message, throwable); } /** * @param throwable */ public IllegalParamTypeException(Throwable throwable) { super(throwable); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/RequestHandledException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/exceptions/RequestHandledExc0000664000175000017500000000345611757206350034426 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.exceptions; /** * A RequestHandledException is thrown when an this request is already handled, * for example because of an handled exception resulting in an error while * method invocation. The Exception or whatever was handled and the necessary * data in {@link org.restlet.Response} were set, so that the JaxRsRestlet * must not do anything.
* This Exception only indicates this. * * @author Stephan Koops */ public class RequestHandledException extends Exception { private static final long serialVersionUID = 2765454873472711005L; } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/todo/0000775000175000017500000000000011757206350027707 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/todo/NotYetImplementedException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/todo/NotYetImplementedExcept0000664000175000017500000000426611757206350034421 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.todo; /** * A NotYetImplementedException is thrown, when a method is not yet implemented * and should be implemented later. On the final implementation this class will * be removed, because than there is nothing not implemented. * * @author Stephan Koops */ public class NotYetImplementedException extends UnsupportedOperationException { private static final long serialVersionUID = -746394839280273085L; /** * */ public NotYetImplementedException() { super(); } /** * * @param message */ public NotYetImplementedException(String message) { super(message); } /** * * @param message * @param cause */ public NotYetImplementedException(String message, Throwable cause) { super(message, cause); } /** * * @param cause */ public NotYetImplementedException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/todo/WillNotBeImplementedException.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/todo/WillNotBeImplementedExc0000664000175000017500000000430511757206350034317 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.todo; /** * A NotYetImplementedException is thrown, when a method is not yet implemented * and should be implemented later. On the final implementation this class will * be removed, because than there is nothing not implemented. * * @author Stephan Koops */ public class WillNotBeImplementedException extends UnsupportedOperationException { private static final long serialVersionUID = -746394839280273085L; /** * */ public WillNotBeImplementedException() { super(); } /** * * @param message */ public WillNotBeImplementedException(String message) { super(message); } /** * * @param message * @param cause */ public WillNotBeImplementedException(String message, Throwable cause) { super(message, cause); } /** * * @param cause */ public WillNotBeImplementedException(Throwable cause) { super(cause); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/todo/Notices.java0000664000175000017500000000502311757206350032156 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.todo; /** * Here are notices for the implementation. * * @author Stephan Koops */ public class Notices { // TESTEN do not decode @FormParam, @MatrixParam, @QueryParam // TESTEN do not encode keys of Form entity // TESTEN what happens, if ".." or "." in @Path? // run tests again Jersey. // TEST, if the URIs are normaized, see spec, sect. 3.7.1 "Request // Preprocessing" // TESTEN *ExceptionWriter, see JSR311-dev-mail 1225 // https://jsr311.dev.java.net/servlets/ReadMsg?list=dev&msgNo=1225 // NICE Provider for File-Upload by a browser (multipart/form-data) // NICE warn if primitve on @*Param: perhaps null? // NICE look for warnings in tests and put them away. // NICE When writing responses, implementations SHOULD respect // application-supplied character set metadata and SHOULD use UTF-8 if a // character set is not specified by the application or if the application // specifies a character set that is unsupported. // NICE JaxRsComponent // http://restlet.tigris.org/issues/show_bug.cgi?id=464#desc17 // http://restlet.tigris.org/issues/show_bug.cgi?id=464#desc19 // NICE Entity-Provider for org.restlet.data.Representation // NICE ResourceException-ExceptionMapper as WebAppExcMapper ? } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/0000775000175000017500000000000011757206350027535 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/DateHeaderDelegate.java0000664000175000017500000000613611757206350034027 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.spi; import java.util.Date; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate; import org.restlet.engine.util.DateUtils; /** * {@link HeaderDelegate} for {@link MediaType}. * * @author Stephan Koops */ public class DateHeaderDelegate implements HeaderDelegate { // TODO DateHeaderDelegate // TODO use headerDelegates, if one is available /** * Obtain an instance of a HeaderDelegate for the MediTape class. * * @see RuntimeDelegate#createHeaderDelegate(Class) */ public DateHeaderDelegate() { } /** * Parse the supplied value and create an instance of T. * * @param contentType * the contentType * @return the newly created instance of T * @throws IllegalArgumentException * if the supplied string cannot be parsed * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#fromString(java.lang.String) */ public Date fromString(String date) throws IllegalArgumentException { // This method could be extended, if you have problems. Send an email to // discuss@restlet.tigris.org return DateUtils.parse(date); } /** * Convert the supplied value to a String. * * @param value * the value of type T * @return a String representation of the value * @throws IllegalArgumentException * if the supplied object cannot be serialized * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#toString(java.lang.Object) */ public String toString(Date date) { // This method could be extended, if you have problems. Send an email to // discuss@restlet.tigris.org return DateUtils.format(date); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/CacheControlHeaderDelegate.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/CacheControlHeaderDelega0000664000175000017500000000641011757206350034240 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.spi; import java.util.List; import javax.ws.rs.core.CacheControl; import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate; import org.restlet.data.CacheDirective; import org.restlet.engine.http.header.CacheDirectiveReader; import org.restlet.engine.http.header.CacheDirectiveWriter; import org.restlet.ext.jaxrs.internal.util.Converter; /** * {@link HeaderDelegate} for {@link CacheControl}. * * @author Stephan Koops */ public class CacheControlHeaderDelegate implements HeaderDelegate { /** * Obtain an instance of a HeaderDelegate for the CacheControl class. * * @see RuntimeDelegate#createHeaderDelegate(Class) */ CacheControlHeaderDelegate() { } /** * Parse the supplied value and create an instance of T. * * @param value * the string value * @return the newly created instance of T * @throws IllegalArgumentException * if the supplied string cannot be parsed * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#fromString(java.lang.String) */ public CacheControl fromString(String value) throws IllegalArgumentException { CacheDirectiveReader ccr = new CacheDirectiveReader(value); List cacheDirectives = ccr.readValues(); return Converter.toJaxRsCacheControl(cacheDirectives); } /** * Convert the supplied value to a String. * * @param value * the value of type T * @return a String representation of the value * @throws IllegalArgumentException * if the supplied object cannot be serialized * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#toString(java.lang.Object) */ public String toString(CacheControl cacheControl) { List directives = Converter .toRestletCacheDirective(cacheControl); return CacheDirectiveWriter.write(directives); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/NewCookieHeaderDelegate.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/NewCookieHeaderDelegate.0000664000175000017500000000575511757206350034201 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.spi; import javax.ws.rs.core.NewCookie; import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate; import org.restlet.engine.http.header.CookieSettingReader; import org.restlet.engine.http.header.CookieSettingWriter; import org.restlet.ext.jaxrs.internal.util.Converter; /** * {@link HeaderDelegate} for {@link NewCookie} * * @author Stephan Koops */ public class NewCookieHeaderDelegate implements HeaderDelegate { /** * Obtain an instance of a HeaderDelegate for the NewCookie class. * * @see RuntimeDelegate#createHeaderDelegate(Class) */ NewCookieHeaderDelegate() { } /** * Parse the supplied value and create an instance of T. * * @param value * the string value * @return the newly created instance of T * @throws IllegalArgumentException * if the supplied string cannot be parsed * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#fromString(java.lang.String) */ public NewCookie fromString(String string) throws IllegalArgumentException { return Converter.toJaxRsNewCookie(CookieSettingReader.read(string)); } /** * Convert the supplied value to a String. * * @param value * the value of type T * @return a String representation of the value * @throws IllegalArgumentException * if the supplied object cannot be serialized * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#toString(java.lang.Object) */ public String toString(NewCookie newCookie) { return CookieSettingWriter.write(Converter .toRestletCookieSetting(newCookie)); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/EntityTagHeaderDelegate.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/EntityTagHeaderDelegate.0000664000175000017500000000552711757206350034223 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.spi; import javax.ws.rs.core.EntityTag; import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate; import org.restlet.data.Tag; import org.restlet.ext.jaxrs.internal.util.Converter; /** * {@link HeaderDelegate} for {@link EntityTag} * * @author Stephan Koops */ public class EntityTagHeaderDelegate implements HeaderDelegate { /** * Obtain an instance of a HeaderDelegate for the EnityTag class. * * @see RuntimeDelegate#createHeaderDelegate(Class) */ EntityTagHeaderDelegate() { } /** * Parse the supplied value and create an instance of T. * * @param value * the string value * @return the newly created instance of T * @throws IllegalArgumentException * if the supplied string cannot be parsed * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#fromString(java.lang.String) */ public EntityTag fromString(String string) throws IllegalArgumentException { return Converter.toJaxRsEntityTag(Tag.parse(string)); } /** * Convert the supplied value to a String. * * @param value * the value of type T * @return a String representation of the value * @throws IllegalArgumentException * if the supplied object cannot be serialized * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#toString(java.lang.Object) */ public String toString(EntityTag entityTag) { return Converter.toRestletTag(entityTag).format(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/RuntimeDelegateImpl.java0000664000175000017500000001064511757206350034306 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.spi; import java.util.Date; import javax.ws.rs.core.Application; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Variant.VariantListBuilder; import org.restlet.ext.jaxrs.internal.core.ResponseBuilderImpl; import org.restlet.ext.jaxrs.internal.core.UriBuilderImpl; import org.restlet.ext.jaxrs.internal.core.VariantListBuilderImpl; /** * Implementation of abstract JAX-RS class * {@link javax.ws.rs.ext.RuntimeDelegate}. * * @author Stephan Koops */ public class RuntimeDelegateImpl extends javax.ws.rs.ext.RuntimeDelegate { /** * This method is not supported by this implementation. * * @throws UnsupportedOperationException * ever. */ @Override public T createEndpoint(Application application, Class endpointType) throws UnsupportedOperationException { throw new UnsupportedOperationException( "The method RuntimeDelegate.createEndpoint() is not available by the Restlet JAX-RS extension"); } /** * Obtain an instance of a HeaderDelegate for the supplied class. An * implementation is required to support the following values for type: * Cookie, CacheControl, EntityTag, NewCookie, MediaType, Date. * * @param type * the class of the header * @return an instance of HeaderDelegate for the supplied type * @see javax.ws.rs.ext.RuntimeDelegate#createHeaderDelegate(Class) */ @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public HeaderDelegate createHeaderDelegate(Class type) throws IllegalArgumentException { if (type.equals(Cookie.class)) { return new CookieHeaderDelegate(); } if (type.equals(CacheControl.class)) { return new CacheControlHeaderDelegate(); } if (type.equals(EntityTag.class)) { return new EntityTagHeaderDelegate(); } if (type.equals(NewCookie.class)) { return new NewCookieHeaderDelegate(); } if (type.equals(MediaType.class)) { return new MediaTypeHeaderDelegate(); } if (type.equals(Date.class)) { return new DateHeaderDelegate(); } throw new IllegalArgumentException( "This method supports only the Types Cookie, CacheControl, EntityTag, NewCookie and MediaType"); } /** * @see javax.ws.rs.ext.RuntimeDelegate#createResponseBuilder() */ @Override public ResponseBuilder createResponseBuilder() { return new ResponseBuilderImpl(); } /** * @see javax.ws.rs.ext.RuntimeDelegate#createUriBuilder() */ @Override public UriBuilder createUriBuilder() { return new UriBuilderImpl(); } /** * @see javax.ws.rs.ext.RuntimeDelegate#createVariantListBuilder() */ @Override public VariantListBuilder createVariantListBuilder() { return new VariantListBuilderImpl(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/CookieHeaderDelegate.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/CookieHeaderDelegate.jav0000664000175000017500000000564411757206350034225 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.spi; import javax.ws.rs.core.Cookie; import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate; import org.restlet.engine.http.header.CookieReader; import org.restlet.engine.http.header.CookieWriter; import org.restlet.ext.jaxrs.internal.util.Converter; /** * {@link HeaderDelegate} for {@link Cookie}s. * * @author Stephan Koops */ public class CookieHeaderDelegate implements HeaderDelegate { /** * Obtain an instance of a HeaderDelegate for the Cookie class. * * @see RuntimeDelegate#createHeaderDelegate(Class) */ CookieHeaderDelegate() { } /** * Parse the supplied value and create an instance of T. * * @param value * the string value * @return the newly created instance of T * @throws IllegalArgumentException * if the supplied string cannot be parsed * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#fromString(java.lang.String) */ public Cookie fromString(String string) throws IllegalArgumentException { return Converter.toJaxRsCookie(CookieReader.read(string)); } /** * Convert the supplied value to a String. * * @param value * the value of type T * @return a String representation of the value * @throws IllegalArgumentException * if the supplied object cannot be serialized * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#toString(java.lang.Object) */ public String toString(Cookie jaxRsCookie) { return CookieWriter.write(Converter.toRestletCookie(jaxRsCookie)); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/MediaTypeHeaderDelegate.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/spi/MediaTypeHeaderDelegate.0000664000175000017500000000617311757206350034172 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.spi; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate; import org.restlet.engine.http.header.ContentType; import org.restlet.ext.jaxrs.internal.util.Converter; /** * {@link HeaderDelegate} for {@link MediaType}. * * @author Stephan Koops */ public class MediaTypeHeaderDelegate implements HeaderDelegate { /** * Obtain an instance of a HeaderDelegate for the MediTape class. * * @see RuntimeDelegate#createHeaderDelegate(Class) */ public MediaTypeHeaderDelegate() { } /** * Parse the supplied value and create an instance of T. * * @param contentType * the contentType * @return the newly created instance of T * @throws IllegalArgumentException * if the supplied string cannot be parsed * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#fromString(java.lang.String) */ public MediaType fromString(String contentType) throws IllegalArgumentException { // if(true) // throw new NotYetImplementedException("waiting for an Engine patch"); final org.restlet.data.MediaType restletMediaType = ContentType .readMediaType(contentType); return Converter.toJaxRsMediaType(restletMediaType, null); } /** * Convert the supplied value to a String. * * @param value * the value of type T * @return a String representation of the value * @throws IllegalArgumentException * if the supplied object cannot be serialized * @see javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate#toString(java.lang.Object) */ public String toString(MediaType jaxRsMediaType) { return Converter.toRestletMediaType(jaxRsMediaType).toString(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/0000775000175000017500000000000011757206350027717 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java0000664000175000017500000020301211757206350031475 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE; import static org.restlet.data.CharacterSet.UTF_8; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.nio.charset.Charset; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import javax.ws.rs.Path; import javax.ws.rs.core.MultivaluedMap; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.data.Dimension; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Parameter; import org.restlet.engine.http.header.ContentType; import org.restlet.engine.http.header.DimensionWriter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.util.DateUtils; import org.restlet.ext.jaxrs.internal.core.UnmodifiableMultivaluedMap; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.JaxRsRuntimeException; import org.restlet.ext.jaxrs.internal.exceptions.MethodInvokeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * This class contains utility methods. * * @author Stephan Koops */ public class Util { /** * The default character set to be used, if no character set is given. */ public static final CharacterSet JAX_RS_DEFAULT_CHARACTER_SET = UTF_8; /** * The default character set to be used, if no character set is given, as * String * * @see #JAX_RS_DEFAULT_CHARACTER_SET */ public static final String JAX_RS_DEFAULT_CHARACTER_SET_AS_STRING = JAX_RS_DEFAULT_CHARACTER_SET .toString(); /** * This comparator sorts the concrete MediaTypes to the beginning and the * unconcrete to the end. The last is '*/*' */ public static final Comparator MEDIA_TYPE_COMP = new Comparator() { public int compare(org.restlet.data.MediaType mediaType1, org.restlet.data.MediaType mediaType2) { if (mediaType1 == null) { return mediaType2 == null ? 0 : 1; } if (mediaType2 == null) { return -1; } if (mediaType1.equals(mediaType2, false)) { return 0; } final int specNess1 = specificness(mediaType1); final int specNess2 = specificness(mediaType2); final int rt = specNess1 - specNess2; if (rt != 0) { return rt; } return mediaType1.toString().compareToIgnoreCase( mediaType2.toString()); } }; private static final byte NAME_READ = 2; private static final byte NAME_READ_READY = 3; private static final byte NAME_READ_START = 1; /** * The name of the header {@link MultivaluedMap}<String, String> in * the attribute map. * */ public static final String ORG_RESTLET_EXT_JAXRS_HTTP_HEADERS = "org.restlet.ext.jaxrs.http.headers"; /** * The name of the header {@link Form} in the attribute map. * * @see #getHttpHeaders(Request) * @see #getHttpHeaders(Response) */ public static final String ORG_RESTLET_HTTP_HEADERS = "org.restlet.http.headers"; /** * appends the given String to the StringBuilder. If convertBraces is true, * all "{" and "}" are converted to "%7B" and "%7D" * * @param stb * the Appendable to append on * @param string * the CharSequence to append * @param convertBraces * if true, all braces are converted, if false then not. * @throws IOException * If the Appendable have a problem */ public static void append(Appendable stb, CharSequence string, boolean convertBraces) throws IOException { append(stb, string, convertBraces, 0, string.length()); } /** * appends the given String to the StringBuilder. If convertBraces is true, * all "{" and "}" are converted to "%7B" and "%7D" * * @param stb * the Appendable to append on * @param string * the CharSequence to append * @param convertBraces * if true, all braces are converted, if false then not. * @param startIndex * @throws IOException * If the Appendable have a problem */ public static void append(Appendable stb, CharSequence string, boolean convertBraces, int startIndex) throws IOException { append(stb, string, convertBraces, startIndex, string.length()); } /** * appends the given String to the StringBuilder. If convertBraces is true, * all "{" and "}" are converted to "%7B" and "%7D" * * @param stb * the Appendable to append on * @param string * the CharSequence to append * @param convertBraces * if true, all braces are converted, if false then not. * @param startIndex * @param endIndex * @throws IOException * If the Appendable have a problem */ public static void append(Appendable stb, CharSequence string, boolean convertBraces, int startIndex, int endIndex) throws IOException { if (!convertBraces) { stb.append(string, startIndex, endIndex); return; } for (int i = startIndex; i < endIndex; i++) { final char c = string.charAt(i); if (c == '{') { stb.append("%7B"); } else if (c == '}') { stb.append("%7D"); } else { stb.append(c); } } } /** * appends the array elements to the {@link StringBuilder}, separated by * ", ". * * @param stb * The {@link StringBuilder} to append the array elements. * @param array * The array to append to the {@link StringBuilder}. */ public static void append(StringBuilder stb, Object[] array) { if ((array == null) || (array.length == 0)) { return; } stb.append(array[0]); for (int i = 1; i < array.length; i++) { stb.append(", "); stb.append(array[i]); } } /** * Indicates if the given class (and its implemented interfaces) are * annotated with the given annotation. * * @param jaxRsClass * The class to check. * @param annotationClass * The class of the annotation . * @return True if the given class (and its implemented interfaces) are * annotated with the given annotation. */ private static boolean checkClassAndInterfacesForAnnotation( Class jaxRsClass, Class annotationClass) { boolean found = jaxRsClass.isAnnotationPresent(annotationClass); if (!found) { Class[] interfaces = jaxRsClass.getInterfaces(); for (int i = 0; !found && i < interfaces.length; i++) { found = interfaces[i].isAnnotationPresent(annotationClass); } } return found; } /** * Checks, if the class is concrete. * * @param jaxRsClass * JAX-RS root resource class or JAX-RS provider. * @param typeName * for the exception message "root resource class" or "provider" * @throws IllegalArgumentException * if the class is not concrete. */ public static void checkClassConcrete(Class jaxRsClass, String typeName) throws IllegalArgumentException { final int modifiers = jaxRsClass.getModifiers(); if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)) { throw new IllegalArgumentException("The " + typeName + " " + jaxRsClass.getName() + " is not concrete"); } } /** * Copies headers into a response. * * @param jaxRsHeaders * Headers of an JAX-RS-Response. * @param restletResponse * Restlet Response to copy the headers in. * @see javax.ws.rs.core.Response#getMetadata() */ public static void copyResponseHeaders( final MultivaluedMap jaxRsHeaders, Response restletResponse) { Series headers = new Form(); for (Map.Entry> m : jaxRsHeaders.entrySet()) { String headerName = m.getKey(); for (Object headerValue : m.getValue()) { String hValue; if (headerValue == null) { hValue = null; } else if (headerValue instanceof Date) { hValue = formatDate((Date) headerValue, false); } else { hValue = headerValue.toString(); } headers.add(new Parameter(headerName, hValue)); } } if (restletResponse.getEntity() == null) { restletResponse.setEntity(new EmptyRepresentation()); } HeaderUtils.copyResponseTransportHeaders(headers, restletResponse); HeaderUtils.extractEntityHeaders(headers, restletResponse.getEntity()); // Copy extension headers @SuppressWarnings("unchecked") Series extensionHeaders = (Series) jaxRsHeaders .getFirst(HeaderConstants.ATTRIBUTE_HEADERS); if (extensionHeaders != null) { Map attributes = new HashMap(); attributes.put(HeaderConstants.ATTRIBUTE_HEADERS, extensionHeaders); restletResponse.setAttributes(attributes); } } /** * Copies the headers of the given {@link Response} into the given * {@link Series}. * * @param restletResponse * The response to update. Should contain a * {@link Representation} to copy the representation headers from * it. * @return The copied headers. */ public static Series copyResponseHeaders(Response restletResponse) { final Series headers = new Form(); HeaderUtils.addResponseHeaders(restletResponse, headers); HeaderUtils.addEntityHeaders(restletResponse.getEntity(), headers); return headers; } /** * Creates an modifiable Collection with the given Objects in it, and no * other objects. nulls will be ignored. * * @param objects * @param * @return Returns the created list with the given objects in it. */ public static Collection createColl(A... objects) { return createList(objects); } /** * Creates an modifiable List with the given Object in it, and no other * objects. If the given object is null, than an empty List will returned * * @param objects * @param * @return Returns the created list with the given object in it or an empty * list, if the given object is null. */ public static List createList(A... objects) { final List list = new ArrayList(); final int l = objects.length; for (int i = 0; i < l; i++) { final A o = objects[i]; if (o != null) { list.add(o); } } return list; } /** * Creates a map with the given keys and values. * * @param keysAndValues * first element is key1, second element value1, third element * key2, forth element value2 and so on. * @return the created Map */ public static Map createMap(String... keysAndValues) { final Map map = new HashMap(); for (int i = 0; i < keysAndValues.length; i += 2) { map.put(keysAndValues[i], keysAndValues[i + 1]); } return map; } /** * Creates an modifiable Set with the given Object in it, and no other * objects. If the given object is null, than an empty Set will returned. * * @param * @param objects * @return the created Set */ public static Set createSet(A... objects) { final Set set = new HashSet(); final int l = objects.length; for (int i = 0; i < l; i++) { final A o = objects[i]; if (o != null) { set.add(o); } } return set; } /** * Checks, if the given class implements the given interface. * * @param clazz * @param interfaze * @return true, if the class implements the given interface, otherwise * false. if the clazz or interfaze is null, false is returned */ public static boolean doesImplement(Class clazz, Class interfaze) { if (clazz == null || interfaze == null) return false; if (doesImplement(clazz.getSuperclass(), interfaze)) return true; for (Class interf : clazz.getInterfaces()) { if (interf.equals(interfaze)) return true; if (doesImplement(interf, interfaze)) return true; } return false; } /** * Checks, if the given CharSequence ends with the given character. * * @param charSequence * @param character * @return true, if the given charSequence ends with the given character, * otherwise false. * @see #notEndsWith(CharSequence, char) * @see #startsWith(CharSequence, char) */ public static boolean endsWith(CharSequence charSequence, char character) { if (charSequence == null) return false; if (charSequence.length() == 0) return false; return charSequence.charAt(charSequence.length() - 1) == character; } /** * Check if the given objects are equal. Can deal with null references. if * both elements are null, than the result is true. * * @param object1 * @param object2 * @return true, if the objects are equal. */ public static boolean equals(Object object1, Object object2) { if (object1 == null) { return object2 == null; } return object1.equals(object2); } /** * Converts the given Date into a String. Copied from * {@link org.restlet.engine.Call}. * * @param date * Date to format * @param cookie * if true, using RFC 1036 format, otherwise RFC 1123 format. * @return The formated date */ public static String formatDate(Date date, boolean cookie) { if (cookie) { return DateUtils.format(date, DateUtils.FORMAT_RFC_1036.get(0)); } return DateUtils.format(date, DateUtils.FORMAT_RFC_1123.get(0)); } /** * Formats the given {@link Set} of {@link Dimension}s to a String for the * HTTP Vary header. * * @param dimensions * the dimensions to format. * @return the Vary header or null, if dimensions is null or empty. */ public static String formatDimensions(Set dimensions) { return DimensionWriter.write(dimensions); } /** * @param genCompType * @param forMessage * @throws NegativeArraySizeException * @throws ImplementationException */ private static Class getArrayClass(Type genCompType, Type forMessage) throws NegativeArraySizeException, ImplementationException { if (genCompType.equals(Byte.TYPE)) { return (new byte[0]).getClass(); } if (genCompType.equals(Short.TYPE)) { return (new short[0]).getClass(); } if (genCompType.equals(Integer.TYPE)) { return (new int[0]).getClass(); } if (genCompType.equals(Long.TYPE)) { return (new long[0]).getClass(); } if (genCompType.equals(Float.TYPE)) { return (new float[0]).getClass(); } if (genCompType.equals(Double.TYPE)) { return (new double[0]).getClass(); } if (genCompType.equals(Character.TYPE)) { return (new char[0]).getClass(); } if (genCompType.equals(Boolean.TYPE)) { return (new boolean[0]).getClass(); } if (genCompType instanceof Class) { return Array.newInstance((Class) genCompType, 0).getClass(); } throw new ImplementationException("Sorry, could not handle a " + forMessage.getClass()); // LATER could not handle all classes } /** * Returns the character set as String of the given http headers (e.g. from * a JAX-RS {@link javax.ws.rs.core.Response}). * * @param httpHeaders * the JAX-RS {@link javax.ws.rs.core.Response} * @param defaultCs * the character set to return, if no one could be found. * @return the Restlet {@link CharacterSet} of the given http headers, or * the given defaultCs as String if the header "Content-Type" is not * available or has no parameter "charset". Returns only null, if * the given defaultCs is null. * @see #getSupportedCharSet(MultivaluedMap) */ public static String getCharsetName( MultivaluedMap httpHeaders, CharacterSet defaultCs) { String result = null; CharacterSet charSet = null; final Object contentType = httpHeaders.getFirst(CONTENT_TYPE); if (contentType == null) { charSet = defaultCs; } else { charSet = ContentType.readCharacterSet(contentType.toString()); if (charSet == null) { charSet = defaultCs; } } if (charSet != null) { result = charSet.getName(); } return result; } /** * Returns the first element of the given collection. Throws an exception if * the collection is empty. * * @param coll * @param * @return Returns the first Element of the collection * @throws NoSuchElementException * If the collection is empty. */ public static A getFirstElement(Collection coll) throws NoSuchElementException { if (coll.isEmpty()) { throw new NoSuchElementException( "The Collection is empty; you can't get the first element of it."); } if (coll instanceof LinkedList) { return ((LinkedList) coll).getFirst(); } if (coll instanceof List) { return ((List) coll).get(0); } return coll.iterator().next(); } /** * Returns the first element of the given {@link Iterable}. Throws an * exception if the {@link Iterable} is empty. * * @param coll * @param * @return Returns the first Element of the collection * @throws NoSuchElementException * If the collection is empty */ public static A getFirstElement(Iterable coll) throws NoSuchElementException { if (coll instanceof LinkedList) { return ((LinkedList) coll).getFirst(); } if (coll instanceof List) { return ((List) coll).get(0); } return coll.iterator().next(); } /** * Returns the first element of the {@link List}. Throws an exception if the * list is empty. * * @param list * @param * @return Returns the first Element of the collection * @throws IndexOutOfBoundsException * If the list is empty */ public static A getFirstElement(List list) throws IndexOutOfBoundsException { if (list.isEmpty()) { throw new IndexOutOfBoundsException( "The Collection is empty; you can't get the first element of it."); } if (list instanceof LinkedList) { return ((LinkedList) list).getFirst(); } return list.get(0); } /** * Returns the first element of the given {@link Iterable}. Returns null, if * the {@link Iterable} is empty. * * @param coll * @param * @return the first element of the collection, or null if the iterable is * empty. */ public static A getFirstElementOrNull(Iterable coll) { if (coll instanceof LinkedList) { final LinkedList linkedList = ((LinkedList) coll); if (linkedList.isEmpty()) { return null; } return linkedList.getFirst(); } if (coll instanceof List) { final List list = ((List) coll); if (list.isEmpty()) { return null; } return list.get(0); } if (coll instanceof Collection) { if (((Collection) coll).isEmpty()) { return null; } } return coll.iterator().next(); } /** * Returns the first entry of the given {@link Map}. Throws an exception if * the Map is empty. * * @param map * @param * @param * @return the first entry of the given {@link Map}. * @throws NoSuchElementException * If the map is empty. */ public static Map.Entry getFirstEntry(Map map) throws NoSuchElementException { return map.entrySet().iterator().next(); } /** * Returns the key of the first entry of the given {@link Map}. Throws an * exception if the Map is empty. * * @param map * @param * @param * @return the key of the first entry of the given {@link Map}. * @throws NoSuchElementException * If the map is empty. */ public static K getFirstKey(Map map) throws NoSuchElementException { return map.keySet().iterator().next(); } /** * Returns the value of the first entry of the given {@link Map}. Throws an * exception if the Map is empty. * * @param map * @param * @param * @return the value of the first entry of the given {@link Map}. * @throws NoSuchElementException * If the map is empty. */ public static V getFirstValue(Map map) throws NoSuchElementException { return map.values().iterator().next(); } /** * * @param clazz * The class which implemented interface should be checked. * @param implInterface * the interface from which the generic type should be returned. * @return the type parameter of the given class. */ public static Class getGenericClass(Class clazz, Class implInterface) { if (clazz == null) throw new IllegalArgumentException("The class must not be null"); if (implInterface == null) throw new IllegalArgumentException( "The interface to b eimplemented must not be null"); return getGenericClass(clazz, implInterface, null); } private static Class getGenericClass(Class clazz, Class implInterface, Type[] gsatp) { for (Type ifGenericType : clazz.getGenericInterfaces()) { if (!(ifGenericType instanceof ParameterizedType)) { continue; } final ParameterizedType pt = (ParameterizedType) ifGenericType; Type ptRawType = pt.getRawType(); if (ptRawType == null) continue; if (!ptRawType.equals(implInterface)) continue; final Type[] atps = pt.getActualTypeArguments(); if (atps == null || atps.length == 0) continue; final Type atp = atps[0]; if (atp instanceof Class) { return (Class) atp; } if (atp instanceof ParameterizedType) { final Type rawType = ((ParameterizedType) atp).getRawType(); if (rawType instanceof Class) { return (Class) rawType; } } if (atp instanceof TypeVariable) { TypeVariable tv = (TypeVariable) atp; String name = tv.getName(); if (name == null) continue; // clazz = AbstractProvider // implInterface = MessageBodyReader // name = "T" // pt = MessageBodyReader for (int i = 0; i < atps.length; i++) { TypeVariable tv2 = (TypeVariable) atps[i]; String tv2Name = tv2.getName(); if (tv2Name == null) continue; if (tv2Name.equals(name)) { Type gsatpn = gsatp[i]; if (gsatpn instanceof Class) { return (Class) gsatpn; } if (gsatpn instanceof ParameterizedType) { final Type rawType = ((ParameterizedType) gsatpn) .getRawType(); if (rawType instanceof Class) return (Class) rawType; throw new ImplementationException( "Sorry, don't know how to return the class here"); } if (gsatpn instanceof GenericArrayType) { Type genCompType = ((GenericArrayType) gsatpn) .getGenericComponentType(); return getArrayClass(genCompType, gsatpn); } // if(gsatpn instanceof TypeVariable) { // TypeVariable> tvn = (TypeVariable)gsatpn; // Class cl = tvn.getGenericDeclaration(); // Type[] boulds = tvn.getBounds(); // cl.toString(); // } // throw new // ImplementationException("Sorry, could not handle a " // +gsatpn.getClass()); } } } } Class superClass = clazz.getSuperclass(); Type genericSuperClass = clazz.getGenericSuperclass(); if ((genericSuperClass instanceof Class)) { if (!implInterface.isAssignableFrom((Class) genericSuperClass)) { // if the superclass doesn't implemented the // required interface, give up here ... return null; } } // ... otherwise, obtain type arguments from // superclass if it's a parameterized type ... if ((gsatp == null) && (genericSuperClass instanceof ParameterizedType)) { // LATER this is a hack gsatp = ((ParameterizedType) genericSuperClass) .getActualTypeArguments(); } // ... or make a recursion for a non-parameterized superclass. if (superClass != null) return getGenericClass(superClass, implInterface, gsatp); return null; } /** * Example: in List<String> -> out: String.class * * @param genericType * @return otherwise null */ public static Class getGenericClass(Type genericType) { if (!(genericType instanceof ParameterizedType)) { return null; } final ParameterizedType pt = (ParameterizedType) genericType; Type[] actualTypeArguments = pt.getActualTypeArguments(); if (actualTypeArguments == null || actualTypeArguments.length == 0) return null; final Type atp = actualTypeArguments[0]; if (atp instanceof Class) { return (Class) atp; } if (atp instanceof ParameterizedType) { final Type rawType = ((ParameterizedType) atp).getRawType(); if (rawType instanceof Class) { return (Class) rawType; } return null; } return null; } /** * Returns the HTTP headers of the Restlet {@link Request} as {@link Form}. * * @param request * @return Returns the HTTP headers of the Request. */ public static Form getHttpHeaders(Request request) { Form headers = (Form) request.getAttributes().get( ORG_RESTLET_HTTP_HEADERS); if (headers == null) { headers = new Form(); request.getAttributes().put(ORG_RESTLET_HTTP_HEADERS, headers); } return headers; } /** * Returns the HTTP headers of the Restlet {@link Response} as {@link Form}. * * @param response * @return Returns the HTTP headers of the Response. */ public static Form getHttpHeaders(Response response) { Form headers = (Form) response.getAttributes().get( ORG_RESTLET_HTTP_HEADERS); if (headers == null) { headers = new Form(); response.getAttributes().put(ORG_RESTLET_HTTP_HEADERS, headers); } return headers; } /** * Returns the request headers as {@link MultivaluedMap}. * * @param request * @return the request headers as {@link MultivaluedMap}. */ public static MultivaluedMap getJaxRsHttpHeaders( Request request) { final Map attrsOfRequ = request.getAttributes(); @SuppressWarnings("unchecked") MultivaluedMap headers = (MultivaluedMap) attrsOfRequ .get(ORG_RESTLET_EXT_JAXRS_HTTP_HEADERS); if (headers == null) { headers = UnmodifiableMultivaluedMap.getFromForm( getHttpHeaders(request), false); attrsOfRequ.put(ORG_RESTLET_EXT_JAXRS_HTTP_HEADERS, headers); } return headers; } /** * Returns the last element of the given {@link Iterable}. Throws an * exception if the given iterable is empty. * * @param iterable * @param * @return Returns the last element of the {@link Iterable} * @throws IndexOutOfBoundsException * If the {@link Iterable} is a {@link List} and its is empty. * @throws NoSuchElementException * If the {@link Iterable} is empty and the {@link Iterable} is * not a {@link List}. */ public static A getLastElement(Iterable iterable) throws IndexOutOfBoundsException, NoSuchElementException { if (iterable instanceof LinkedList) { return ((LinkedList) iterable).getLast(); } if (iterable instanceof List) { final List list = ((List) iterable); return list.get(list.size() - 1); } return getLastElement(iterable.iterator()); } /** * Returns the last element of the given {@link Iterator}. Throws an * exception if the given iterator is empty. * * @param iter * @param * @return Returns the last element of the {@link Iterator}. * @throws NoSuchElementException * If the {@link Iterator} is empty. */ public static A getLastElement(Iterator iter) throws NoSuchElementException { A e = iter.next(); while (iter.hasNext()) { e = iter.next(); } return e; } /** * Returns the last element of the given {@link List}. Throws an exception * if the given list is empty. * * @param list * @param * @return Returns the last element of the list * @throws IndexOutOfBoundsException * If the list is empty */ public static A getLastElement(List list) throws IndexOutOfBoundsException { if (list instanceof LinkedList) { return ((LinkedList) list).getLast(); } return list.get(list.size() - 1); } /** * Returns the last element of the given {@link Iterable}, or null, if the * iterable is empty. Returns null, if the iterable is empty. * * @param iterable * @param * @return Returns the last Element of the {@link Iterable}, or null if it * is empty. */ public static A getLastElementOrNull(Iterable iterable) { if (iterable instanceof LinkedList) { final LinkedList linkedList = ((LinkedList) iterable); if (linkedList.isEmpty()) { return null; } return linkedList.getLast(); } if (iterable instanceof List) { final List list = ((List) iterable); if (list.isEmpty()) { return null; } return list.get(list.size() - 1); } if (iterable instanceof Collection) { if (((Collection) iterable).isEmpty()) { return null; } } return getLastElementOrNull(iterable.iterator()); } /** * Returns the last element of the given {@link Iterator}, or null, if the * iterator is empty. Returns null, if the iterator is empty. * * @param iter * @param * @return Returns the last Element of the {@link Iterator}. */ public static A getLastElementOrNull(Iterator iter) { A e = null; while (iter.hasNext()) { e = iter.next(); } return e; } /** * Returns the Restlet {@link MediaType} of the given http headers (e.g. * from a JAX-RS {@link javax.ws.rs.core.Response}). * * @param httpHeaders * the JAX-RS {@link javax.ws.rs.core.Response} * @return the Restlet {@link MediaType} of the given http headers, or null, * if the header "Content-Type" is not available. */ public static MediaType getMediaType( MultivaluedMap httpHeaders) { final Object contentType = httpHeaders.getFirst(CONTENT_TYPE); if (contentType == null) { return null; } if (contentType instanceof MediaType) { return (MediaType) contentType; } if (contentType instanceof javax.ws.rs.core.MediaType) { return Converter .toRestletMediaType((javax.ws.rs.core.MediaType) contentType); } return ContentType.readMediaType(contentType.toString()); } /** * Returns all public {@link Method}s of the class with the given name * (case-sensitive) * * @param clazz * The {@link Class} to search the {@link Method}s. * @param methodName * The name of the {@link Method} to search. * @return Returns a {@link Collection} all of {@link Method}s with the * given name. Never returns null. If no methods are found an empty * Collection will be returned. The method {@link Iterator#remove()} * of this collection is supported. * @throws IllegalArgumentException * if the clazz or the method name is null. */ public static Collection getMethodsByName(Class clazz, String methodName) throws IllegalArgumentException { if (clazz == null) { throw new IllegalArgumentException("The class must not be null"); } if (methodName == null) { throw new IllegalArgumentException( "The method name must not be null"); } final Collection methods = new ArrayList(2); for (final Method method : clazz.getMethods()) { if (method.getName().equals(methodName)) { methods.add(method); } } return methods; } /** * Returns the only element of the list, or null, if the List is null or * empty. * * @param * @param list * a List with at most one element * @return The element of the List, or null, if there is no element. * @throws IllegalArgumentException * if the list contains more than one element. */ public static A getOnlyElement(Collection list) throws IllegalArgumentException { if (list == null) { return null; } if (list.isEmpty()) { return null; } if (list.size() > 1) { throw new IllegalArgumentException( "The list must have exactly one element"); } if (list instanceof List) { return ((List) list).get(0); } return list.iterator().next(); } /** * Returns the Name of the only element of the list of the given Metadata. * Returns null, if the list is empty or null. * * @param metadatas * @return the name of the Metadata * @see #getOnlyElement(List) */ public static String getOnlyMetadataName(List metadatas) { final Metadata metadata = getOnlyElement(metadatas); if (metadata == null) { return null; } return metadata.getName(); } /** * Returns the @{@link Path} annotation of the given root resource * class. * * @param jaxRsClass * the root resource class. * @return the @{@link Path} annotation of the given root resource * class. * @throws MissingAnnotationException * if the path annotation is missing * @throws IllegalArgumentException * if the jaxRsClass is null. */ public static Path getPathAnnotation(Class jaxRsClass) throws MissingAnnotationException, IllegalArgumentException { if (jaxRsClass == null) { throw new IllegalArgumentException( "The jaxRsClass must not be null"); } Path path = jaxRsClass.getAnnotation(Path.class); if (path == null) { Class[] interfaces = jaxRsClass.getInterfaces(); for (int i = 0; (path == null) && i < interfaces.length; i++) { path = interfaces[i].getAnnotation(Path.class); } } if (path == null) { throw new MissingAnnotationException( "The root resource class does not have a @Path annotation"); } return path; } /** * Returns the @{@link Path} annotation of the given sub resource * locator. Throws an exception if no @{@link Path} annotation is * available. * * @param method * the java method to get the @Path from * @return the @Path annotation. * @throws IllegalArgumentException * if null was given. * @throws MissingAnnotationException * if the annotation is not present. */ public static Path getPathAnnotation(Method method) throws IllegalArgumentException, MissingAnnotationException { if (method == null) { throw new IllegalArgumentException( "The root resource class must not be null"); } final Path path = method.getAnnotation(Path.class); if (path == null) { throw new MissingAnnotationException("The method " + method.getName() + " does not have an annotation @Path"); } return path; } /** * Returns the @{@link Path} annotation of the given sub resource * locator. Returns null if no @{@link Path} annotation is available. * * @param method * the java method to get the @Path from * @return the @Path annotation or null, if not present. * @throws IllegalArgumentException * if the method is null. */ public static Path getPathAnnotationOrNull(Method method) throws IllegalArgumentException { if (method == null) { throw new IllegalArgumentException( "The root resource class must not be null"); } return method.getAnnotation(Path.class); } /** * Returns the perhaps decoded template of the path annotation. * * @param resource * @return Returns the path template as String. Never returns null. * @throws IllegalPathOnClassException * @throws MissingAnnotationException * @throws IllegalArgumentException */ public static String getPathTemplateWithoutRegExps(Class resource) throws IllegalPathOnClassException, MissingAnnotationException, IllegalArgumentException { try { return getPathTemplateWithoutRegExps(Util .getPathAnnotation(resource)); } catch (IllegalPathException e) { throw new IllegalPathOnClassException(e); } } /** * Returns the path template of the given sub resource locator or sub * resource method. It is encoded (if necessary) and valid. * * @param method * the java method * @return the path template * @throws IllegalPathOnMethodException * @throws IllegalArgumentException * @throws MissingAnnotationException */ public static String getPathTemplateWithoutRegExps(Method method) throws IllegalArgumentException, IllegalPathOnMethodException, MissingAnnotationException { final Path path = getPathAnnotation(method); try { return getPathTemplateWithoutRegExps(path); } catch (IllegalPathException e) { throw new IllegalPathOnMethodException(e); } } /** * Returns the path from the annotation. It will be encoded if necessary. If * it should not be encoded, this method checks, if all characters are * valid. * * @param path * The {@link Path} annotation. Must not be null. * @return the encoded path template * @throws IllegalPathException * @see Path#encode() */ public static String getPathTemplateWithoutRegExps(final Path path) throws IllegalPathException { return getPathTemplateWithoutRegExps(path.value(), path); } /** * @param pathTemplate * @param pathForExcMess * @return   * @throws IllegalPathException */ public static String getPathTemplateWithoutRegExps( final String pathTemplate, final Path pathForExcMess) throws IllegalPathException { final StringBuilder stb = new StringBuilder(); final int l = pathTemplate.length(); for (int i = 0; i < l; i++) { final char c = pathTemplate.charAt(i); if (c == '{') { i = processTemplVarname(pathTemplate, i, stb, pathForExcMess); } else if (c == '%') { try { EncodeOrCheck.processPercent(i, true, pathTemplate, stb); } catch (IllegalArgumentException e) { throw new IllegalPathException(pathForExcMess, e); } } else if (c == '}') { throw new IllegalPathException(pathForExcMess, "'}' is only allowed as " + "end of a variable name in \"" + pathTemplate + "\""); } else if (c == ';') { throw new IllegalPathException(pathForExcMess, "A semicolon is not allowed in a path"); } else if (c == '/') { stb.append(c); } else { EncodeOrCheck.encode(c, stb); } } return stb.toString(); } /** * Returns the given character set, if it is supported on this system. * Returns UTF-8 otherwise. * * @param characterSet * the wished {@link CharacterSet} * @return a supported {@link CharacterSet}, never null. * @see #getCharsetName(MultivaluedMap, CharacterSet) */ public static CharacterSet getSupportedCharSet(CharacterSet characterSet) { if (characterSet == null) { return JAX_RS_DEFAULT_CHARACTER_SET; } if (Charset.isSupported(characterSet.toString())) { return characterSet; } return logUnsupportedCharSet(characterSet.toString()); } /** * Returns the character set of the http response headers. If no character * set is available or it is not supported, UFT-8 is returned. * * @param httpResponseHeaders * @return a supported {@link CharacterSet}, never null. * @see #getCharsetName(MultivaluedMap, CharacterSet) */ public static CharacterSet getSupportedCharSet( MultivaluedMap httpResponseHeaders) { final String csn = getCharsetName(httpResponseHeaders, JAX_RS_DEFAULT_CHARACTER_SET); if (Charset.isSupported(csn)) { return CharacterSet.valueOf(csn); } return logUnsupportedCharSet(csn); } /** * Returns the index of the first ";" in the last path segment. * * @param path * the path, without a query. * @return the index of the first ";" in the last path segment. Returns -1, * if no ';' is available. */ public static int indexBeginMatrixOfLastSegment(CharSequence path) { // NICE optimize for speed; avoid conversion to String, if it is faster. String pathStr = path.toString(); return pathStr.indexOf(';', pathStr.lastIndexOf('/')); } /** * Returns the index of the first occurrence of the given character between * the given indexes. * * @param charSequence * the char sequence to look in * @param c * the character to look for. * @param beginIndex * @param endIndex * @return the index of the given character between the given indexes, or -1 * if the character could not be found in the given range. * @see String#indexOf(String, int) * @see String#substring(int, int) */ public static int indexOfBetween(CharSequence charSequence, char c, int beginIndex, int endIndex) { if (beginIndex < 0) { beginIndex = 0; } if (endIndex < 0) { endIndex = 0; } for (int i = beginIndex; i < endIndex; i++) { char csc = charSequence.charAt(i); if (csc == c) { return i; } } return -1; } /** * Injects the given toInject in the resource field or the given bean * setter. * * @param resource * @param fieldOrBeanSetter * @param toInject * @throws InvocationTargetException * @throws IllegalArgumentException * @throws InjectException */ public static void inject(Object resource, AccessibleObject fieldOrBeanSetter, Object toInject) throws InvocationTargetException, IllegalArgumentException, InjectException { if (fieldOrBeanSetter instanceof Field) { inject(resource, (Field) fieldOrBeanSetter, toInject); } else if (fieldOrBeanSetter instanceof Method) { inject(resource, (Method) fieldOrBeanSetter, toInject); } else { throw new IllegalArgumentException( "The fieldOrBeanSetter must be a java.lang.reflect.Field or a java.lang.reflect.Method"); } } /** * Inject the given toInject into the given field in the given resource (or * whatever) * * @param resource * the concrete Object to inject the other object in. If the * field is static, thsi object may be null. * @param field * the field to inject the third parameter in. * @param toInject * the object to inject in the first parameter object. * @throws InjectException * if the injection was not possible. See * {@link InjectException#getCause()} for the reason. */ public static void inject(final Object resource, final Field field, final Object toInject) throws InjectException { try { final IllegalAccessException iae = AccessController .doPrivileged(new PrivilegedAction() { public IllegalAccessException run() { try { field.set(resource, toInject); return null; } catch (IllegalAccessException e) { return e; } } }); if (iae != null) { throw new InjectException("Could not inject the " + toInject.getClass() + " into field " + field + " of object " + resource, iae); } } catch (RuntimeException e) { throw new InjectException("Could not inject the " + toInject.getClass() + " into field " + field + " of object " + resource, e); } } /** * Injects the given toInject in the resource with the given bean setter. * * @param resource * @param beanSetter * @param toInject * @throws InvocationTargetException * @throws IllegalArgumentException * @throws InjectException */ public static void inject(Object resource, Method beanSetter, Object toInject) throws InvocationTargetException, IllegalArgumentException, InjectException { try { invokeMethod(resource, beanSetter, toInject); } catch (MethodInvokeException mie) { throw new InjectException(mie); } } /** * Invokes the given method without parameters. This constraint is not * checked; but the method could also be called, if access is normally not * allowed.
* If no javaMethod is given, nothing happens. * * @param object * the object to call the method on. * @param javaMethod * the method to call * @param args * the arguments of the method * @throws MethodInvokeException * @throws InvocationTargetException * @throws IllegalArgumentException * if at least one argument does not match the required method * parameters. * @see #inject(Object, Field, Object) * @see #findPostConstructMethod(Class) * @see #findPreDestroyMethod(Class) */ public static void invokeMethod(final Object object, final Method javaMethod, final Object... args) throws MethodInvokeException, InvocationTargetException, IllegalArgumentException { if (javaMethod == null) { return; } try { AccessController .doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { javaMethod.invoke(object, args); return null; } }); } catch (PrivilegedActionException e) { final Throwable cause = e.getCause(); if (cause instanceof IllegalAccessException) { throw new MethodInvokeException( "Not allowed to invoke post construct method " + javaMethod, cause); } if (cause instanceof InvocationTargetException) { throw (InvocationTargetException) cause; } if (cause instanceof ExceptionInInitializerError) { throw new MethodInvokeException( "Could not invoke post construct method " + javaMethod, cause); } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new JaxRsRuntimeException( "Error while invoking post construct method " + javaMethod, cause); } } /** * Checks, if the list is empty or null. * * @param list * @return true, if the list is empty or null, or false, if the list * contains elements. * @see #isEmpty(Object[]) */ public static boolean isEmpty(List list) { return ((list == null) || list.isEmpty()); } /** * Tests, if the given array is empty or null. Will not throw a * NullPointerException. * * @param array * @return Returns true, if the given array ist null or has zero elements, * otherwise false. * @see #isEmpty(List) */ public static boolean isEmpty(Object[] array) { if ((array == null) || (array.length == 0)) { return true; } return false; } /** * Tests, if the given String is null, empty or "/". Will not throw a * NullPointerException. * * @param string * @return Returns true, if the given string ist null, empty or equals "/", * otherwise false. */ public static boolean isEmptyOrSlash(String string) { return (string == null) || (string.length() == 0) || string.equals("/"); } /** * Checks, if the list contains elements. * * @param list * @return true, if the list contains elements, or false, if the list is * empty or null. */ public static boolean isNotEmpty(List list) { return ((list != null) && !list.isEmpty()); } /** * Checks, if the given class is a JAX-RS provider. * * @param jaxRsClass * the class to check * @return true, if the class is a JAX-RS provider, otherwise false. */ public static boolean isProvider(Class jaxRsClass) { return checkClassAndInterfacesForAnnotation(jaxRsClass, javax.ws.rs.ext.Provider.class); } /** * Checks, if the given class is a JAX-RS root resource class. * * @param jaxRsClass * the class to check * @return true, if the class is a JAX-RS root resource class, otherwise * false. */ public static boolean isRootResourceClass(Class jaxRsClass) { return checkClassAndInterfacesForAnnotation(jaxRsClass, javax.ws.rs.Path.class); } /** * Logs a message that the wished character set is not supported and UTF-8 * is used. * * @param csn * @return UFT-8 */ private static CharacterSet logUnsupportedCharSet(String charsetName) { Context.getCurrentLogger().warning( "The character set " + charsetName + " is not " + "available. Will use " + JAX_RS_DEFAULT_CHARACTER_SET_AS_STRING); return JAX_RS_DEFAULT_CHARACTER_SET; } /** * Checks, if the given CharSequence ends with the given character. * * @param charSequence * @param character * @return true, if the given charSequence ends with the given character, * otherwise false. * @see #endsWith(CharSequence, char) * @see #notStartsWith(CharSequence, char) */ public static boolean notEndsWith(CharSequence charSequence, char character) { if (charSequence == null) return true; if (charSequence.length() == 0) return true; return charSequence.charAt(charSequence.length() - 1) != character; } /** * Checks, if the given CharSequence starts with the given character. * * @param charSequence * @param character * @return true, if the given charSequence starts with the given character, * otherwise false. * @see #startsWith(CharSequence, char) * @see #notEndsWith(CharSequence, char) */ public static boolean notStartsWith(CharSequence charSequence, char character) { if (charSequence == null) return true; if (charSequence.length() == 0) return true; return charSequence.charAt(0) != character; } /** * @param pathTemplate * @param braceIndex * @param stb * @param pathForExcMess * @throws IllegalPathException */ private static int processTemplVarname(final String pathTemplate, final int braceIndex, final StringBuilder stb, final Path pathForExcMess) throws IllegalPathException { final int l = pathTemplate.length(); stb.append('{'); int state = NAME_READ_START; for (int i = braceIndex + 1; i < l; i++) { final char c = pathTemplate.charAt(i); if (c == '{') { throw new IllegalPathException(pathForExcMess, "A variable must not " + "contain an extra '{' in \"" + pathTemplate + "\""); } else if (c == ' ' || c == '\t') { if (state == NAME_READ) state = NAME_READ_READY; continue; } else if (c == ':') { if (state == NAME_READ_START) { throw new IllegalPathException(pathForExcMess, "The variable name at position must not be null at " + braceIndex + " of \"" + pathTemplate + "\""); } if (state == NAME_READ || state == NAME_READ_READY) { for (int j = i; j < l; j++) { if (pathTemplate.charAt(j) == '}') { stb.append('}'); return j; } } throw new IllegalPathException(pathForExcMess, "No '}' found after '{' at position " + braceIndex + " of \"" + pathTemplate + "\""); } } else if (c == '}') { if (state == NAME_READ_START) { throw new IllegalPathException(pathForExcMess, "The template variable name '{}' is not allowed in " + "\"" + pathTemplate + "\""); } stb.append('}'); return i; } if (state == NAME_READ_START) { state = NAME_READ; stb.append(c); } else if (state == NAME_READ) { stb.append(c); } else { throw new IllegalPathException(pathForExcMess, "Invalid character found at position " + i + " of \"" + pathTemplate + "\""); } } throw new IllegalPathException(pathForExcMess, "No '}' found after '{' " + "at position " + braceIndex + " of \"" + pathTemplate + "\""); } /** * Returns a new {@link List}, which contains all * {@link org.restlet.data.MediaType}s of the given List, sorted by it's * concreteness, the concrete {@link org.restlet.data.MediaType} at the * beginning. * * @param mediaTypes * @return the sorted media types * @see Util#specificness(org.restlet.data.MediaType) */ public static List sortByConcreteness( Collection mediaTypes) { final List newList = new ArrayList( mediaTypes.size()); for (final org.restlet.data.MediaType mediaType : mediaTypes) { if (specificness(mediaType) > 0) { newList.add(mediaType); } } for (final org.restlet.data.MediaType mediaType : mediaTypes) { if (specificness(mediaType) == 0) { newList.add(mediaType); } } for (final org.restlet.data.MediaType mediaType : mediaTypes) { if (specificness(mediaType) < 0) { newList.add(mediaType); } } return newList; } /** * Returns the specificness of the given {@link org.restlet.data.MediaType}: *
    *
  • 1 for any concrete type (contains no star)
  • *
  • 0 for the types (anything/*)
  • *
  • -1 for '*/*
  • *
* * @param mediaType * @return 1, 0 or -1 * @see #isConcrete(org.restlet.data.MediaType) * @see #sortByConcreteness(Collection) */ public static int specificness(org.restlet.data.MediaType mediaType) { if (mediaType.equals(org.restlet.data.MediaType.ALL, true)) { return -1; } if (mediaType.getSubType().equals("*")) { return 0; } return 1; } /** * Checks, if the given CharSequence starts with the given character. * * @param charSequence * @param character * @return true, if the given charSequence starts with the given character, * otherwise false. * @see #notStartsWith(CharSequence, char) * @see #endsWith(CharSequence, char) */ public static boolean startsWith(CharSequence charSequence, char character) { if (charSequence == null) return false; if (charSequence.length() == 0) return false; return charSequence.charAt(0) == character; } /** * Creates an Array of the given type. * * @param coll * @param arrayType * @return the object array * @throws NegativeArraySizeException */ public static Object[] toArray(Collection coll, Class arrayType) { final int collSize = coll.size(); final Object[] array = (Object[]) Array .newInstance(arrayType, collSize); return coll.toArray(array); } /** * Concatenate the members of the Set to a String, separated with the given * delimiter. * * @param collection * @param delimiter * @return the concatenated */ public static String toString(Collection collection, String delimiter) { if ((collection == null) || collection.isEmpty()) { return ""; } final Iterator iterator = collection.iterator(); if (collection.size() == 1) { return String.valueOf(iterator.next()); } final StringBuilder stb = new StringBuilder(); stb.append(iterator.next()); while (iterator.hasNext()) { final Object object = iterator.next(); stb.append(delimiter); stb.append(object); } return stb.toString(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/EmptyIterator.java0000664000175000017500000000466111757206350033401 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.Iterator; import java.util.NoSuchElementException; /** * Iterator without any elements. * * @author Stephan Koops * @param */ public final class EmptyIterator implements Iterator { /** * Iterator without any element. */ public static final EmptyIterator INSTANCE = new EmptyIterator(); /** * returns an Iterator with no elements. * * @param * @return an empty iterator */ @SuppressWarnings("unchecked") public static EmptyIterator get() { return (EmptyIterator) INSTANCE; } /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return false; } /** * @see java.util.Iterator#next() * @throws NoSuchElementException * immer, weil der EmptyIterator keine Werte hat */ public T next() throws NoSuchElementException { throw new NoSuchElementException("The EmptyIterator has no values"); } /** * @see java.util.Iterator#remove() */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/OrderedMap.java0000664000175000017500000002740311757206350032612 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; /** * This Map contains its values in the given order.
* Multiple values for one key is allowed. * * @author Stephan Koops * @param * @param */ public class OrderedMap implements Map { private static class Entry implements Map.Entry { private final K key; private V value; /** * @param key * @param value */ private Entry(K key, V value) { this.key = key; this.value = value; } /** * @see java.util.Map.Entry#getKey() */ public K getKey() { return this.key; } /** * @see java.util.Map.Entry#getValue() */ public V getValue() { return this.value; } /** * @see java.util.Map.Entry#setValue(java.lang.Object) */ public V setValue(V newValue) { V oldValue = this.value; this.value = newValue; return oldValue; } @Override public String toString() { return this.key + " -> " + this.value; } } private final class KeySetIterator extends KeyValueSetIterator implements Iterator { private KeySetIterator(Iterator> entryIter) { super(entryIter); } public KK next() { return this.entryIter.next().getKey(); } } /** * @author Stephan Koops */ private abstract class KeyValueSetIterator { final Iterator> entryIter; KeyValueSetIterator(Iterator> entryIter) { this.entryIter = entryIter; } /** @return the next element * @see Iterator#hasNext() */ public final boolean hasNext() { return this.entryIter.hasNext(); } /** @see Iterator#remove() */ public final void remove() { this.entryIter.remove(); } } /** * This list has the interface of a Set, but wraps a List * * @author Stephan Koops */ private static final class ListWrappingSet implements Set { private final List elements; private ListWrappingSet(List elements) { this.elements = elements; } public boolean add(E o) { return elements.add(o); } public boolean addAll(Collection c) { return elements.addAll(c); } public void clear() { elements.clear(); } public boolean contains(Object o) { return elements.contains(o); } public boolean containsAll(Collection c) { return elements.containsAll(c); } public boolean isEmpty() { return elements.isEmpty(); } public Iterator iterator() { return elements.iterator(); } public boolean remove(Object o) { return elements.remove(o); } public boolean removeAll(Collection c) { return elements.removeAll(c); } public boolean retainAll(Collection c) { return elements.retainAll(c); } public int size() { return elements.size(); } public Object[] toArray() { return elements.toArray(); } public T[] toArray(T[] a) { return elements.toArray(a); } } private final class ValueSetIterator extends KeyValueSetIterator implements Iterator { private ValueSetIterator(Iterator> entryIter) { super(entryIter); } public VV next() { return this.entryIter.next().getValue(); } } private final List> elements = new ArrayList>(); /** * adds the given entry. * * @param key * @param value * @return ever true (the value is added ever) */ public boolean add(K key, V value) { this.elements.add(new Entry(key, value)); return true; } /** * @see java.util.Map#clear() */ public void clear() { this.elements.clear(); } /** * @see java.util.Map#containsKey(java.lang.Object) */ public boolean containsKey(Object key) { // NICE OrderedMap.containsKey() throw new UnsupportedOperationException("OrderedMap.containsKey()"); } /** * @see java.util.Map#containsValue(java.lang.Object) */ public boolean containsValue(Object value) { // NICE OrderedMap.containsValue() throw new UnsupportedOperationException("OrderedMap.containsValue()"); } /** * @see java.util.Map#entrySet() */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> entrySet() { return new ListWrappingSet>((List) this.elements); } /** * @see java.util.Map#get(java.lang.Object) */ public V get(Object key) { // NICE OrderedMap.get() throw new UnsupportedOperationException("OrderedMap.get()"); } /** * @see java.util.Map#isEmpty() */ public boolean isEmpty() { return this.elements.isEmpty(); } /** * @see java.util.Map#keySet() */ public Set keySet() { return new Set() { public boolean add(K o) { throw new UnsupportedOperationException( "the addition of keys only to a map is not possible"); } public boolean addAll(Collection c) { throw new UnsupportedOperationException( "the addition of keys only to a map is not possible"); } public void clear() { elements.clear(); } public boolean contains(Object o) { return OrderedMap.this.containsKey(o); } public boolean containsAll(Collection c) { for (Object e : c) if (!OrderedMap.this.containsKey(e)) return false; return true; } public boolean isEmpty() { return elements.isEmpty(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public Iterator iterator() { return new KeySetIterator((Iterator) elements.iterator()); } public boolean remove(Object o) { throw new NotYetImplementedException(); } public boolean removeAll(Collection c) { throw new NotYetImplementedException(); } public boolean retainAll(Collection c) { throw new NotYetImplementedException(); } public int size() { return elements.size(); } public Object[] toArray() { throw new NotYetImplementedException(); } public T[] toArray(T[] a) { throw new NotYetImplementedException(); } }; } /** * adds the given entry. Will ever return {@code null}, also if there is an * element with the given value. * * @see Map#put(Object, Object) * @see #add(Object, Object) */ public V put(K key, V value) { this.add(key, value); return null; } /** * @see java.util.Map#putAll(java.util.Map) */ public void putAll(Map map) { for (Map.Entry e : map.entrySet()) { this.elements.add(e); } } /** * @see java.util.Map#remove(java.lang.Object) */ public V remove(Object key) { // NICE OrderedMap.remove() throw new UnsupportedOperationException("OrderedMap.remove()"); } /** * @see java.util.Map#size() */ public int size() { return this.elements.size(); } @Override public String toString() { return this.elements.toString(); } /** * @see java.util.Map#values() */ public Collection values() { return new Collection() { public boolean add(V o) { throw new UnsupportedOperationException( "the addition of values only to a map is not possible"); } public boolean addAll(Collection c) { throw new UnsupportedOperationException( "the addition of values only to a map is not possible"); } public void clear() { elements.clear(); } public boolean contains(Object value) { return OrderedMap.this.containsValue(value); } public boolean containsAll(Collection c) { for (Object v : c) if (!OrderedMap.this.containsValue(v)) return false; return true; } public boolean isEmpty() { return elements.isEmpty(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public Iterator iterator() { return new ValueSetIterator((Iterator) elements .iterator()); } public boolean remove(Object o) { throw new NotYetImplementedException(); } public boolean removeAll(Collection c) { boolean removed = false; for (Object o : c) removed |= this.remove(o); return removed; } public boolean retainAll(Collection c) { throw new NotYetImplementedException(); } public int size() { return elements.size(); } public Object[] toArray() { throw new NotYetImplementedException(); } public T[] toArray(T[] a) { throw new NotYetImplementedException(); } }; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Converter.java0000664000175000017500000004522111757206350032535 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import org.restlet.data.CacheDirective; import org.restlet.data.CharacterSet; import org.restlet.data.CookieSetting; import org.restlet.data.Encoding; import org.restlet.data.Form; import org.restlet.data.Language; import org.restlet.data.Parameter; import org.restlet.data.Tag; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.util.FormUtils; import org.restlet.util.Series; /** * This utility class converts Restlet objects to it correponding JAX-RS objects * and vice versa. * * @author Stephan Koops */ public class Converter { /** * Paramater in the JAX-RS MediaType for the charset. See MIME * specification. */ private static final String CHARSET_PARAM = "charset"; /** * Returns the charset of the MediaType as String * * @param mediaType * JaxRs-MediaType * @return the charset */ public static String getCharset(MediaType mediaType) { final Map parameters = mediaType.getParameters(); if (parameters == null) { return null; } return parameters.get(CHARSET_PARAM); } /** * Creates a MediaType without any parameters. * * @param mediaType * A MediaType, perhaps with parameters. * @return Creates a MediaType without any parameters. */ public static MediaType getMediaTypeWithoutParams(MediaType mediaType) { if (mediaType == null) { return null; } final Map parameters = mediaType.getParameters(); if ((parameters == null) || parameters.isEmpty()) { return mediaType; } return new MediaType(mediaType.getType(), mediaType.getSubtype()); } /** * Creates a MediaType without any parameters. * * @param mediaType * A MediaType, perhaps with parameters. * @return Creates a MediaType without any parameters. */ public static org.restlet.data.MediaType getMediaTypeWithoutParams( org.restlet.data.MediaType mediaType) { if (mediaType == null) { return null; } final Series parameters = mediaType.getParameters(); if ((parameters == null) || parameters.isEmpty()) { return mediaType; } return mediaType.getParent(); } /** * Returns the Charset of the MediaType as String * * @param mediaType * JaxRs-MediaType * @return the charset */ public static CharacterSet getRestletCharacterSet(MediaType mediaType) { final String charset = getCharset(mediaType); if (charset == null) { return null; } return CharacterSet.valueOf(charset); } /** * Copies the data in the {@link MultivaluedMap} to the {@link Form}. * * @param mmap * @return the converted Http headers or null, if null was given. */ public static Form toForm(MultivaluedMap mmap) { if (mmap == null) { return null; } final Form form = new Form(); for (final Map.Entry> entry : mmap.entrySet()) { final String name = entry.getKey(); for (final String value : entry.getValue()) { form.add(name, value); } } return form; } /** * Converts the given query String to a Form, but do not decode the data. * * @param queryString * @return the encoded form */ public static Form toFormEncoded(String queryString) { final Form form = new Form(); FormUtils.parse(form, queryString, null, false, '&'); return form; } /** * Converts a Restlet Cookie to a JAX-RS Cookie * * @param restletCookie * the Restlet Cookie * @return the JAX-RS Cookie */ public static Cookie toJaxRsCookie(org.restlet.data.Cookie restletCookie) { if (restletCookie == null) { return null; } return new Cookie(restletCookie.getName(), restletCookie.getValue(), restletCookie.getPath(), restletCookie.getDomain(), restletCookie.getVersion()); } /** * Converts a Restlet-EntityTag to a JAX-RS-EntityTag * * @param restletEntityTag * the Restlet-EntityTag to convert. * @return The corresponding JAX-RS-Entity-Tag */ public static EntityTag toJaxRsEntityTag(Tag restletEntityTag) { if (restletEntityTag == null) { return null; } return new EntityTag(restletEntityTag.getName(), restletEntityTag .isWeak()); } /** * Convert a Restlet MediaType to a JAX-RS MediaType. * * @param restletMediaType * the MediaType to convert. * @param restletCharacterSet * the CharacterSet for the MediaType; may be null. * @return the converted MediaType */ public static MediaType toJaxRsMediaType( org.restlet.data.MediaType restletMediaType) { return toJaxRsMediaType(restletMediaType, null); } /** * Convert a Restlet MediaType to a JAX-RS MediaType. * * @param restletMediaType * the MediaType to convert. * @param restletCharacterSet * the CharacterSet for the MediaType; may be null. * @return the converted MediaType */ public static MediaType toJaxRsMediaType( org.restlet.data.MediaType restletMediaType, org.restlet.data.CharacterSet restletCharacterSet) { if (restletMediaType == null) { return null; } final Map parameters = toMap(restletMediaType .getParameters()); if (restletCharacterSet != null) { parameters.put(Converter.CHARSET_PARAM, restletCharacterSet .getName()); } return new MediaType(restletMediaType.getMainType(), restletMediaType .getSubType(), parameters); } /** * Converts the Restlet CookieSettings to a JAX-RS NewCookie. * * @param cookieSetting * @return the JAX-RS NewCookie * @throws IllegalArgumentException */ public static NewCookie toJaxRsNewCookie(CookieSetting cookieSetting) throws IllegalArgumentException { if (cookieSetting == null) { return null; } return new NewCookie(cookieSetting.getName(), cookieSetting.getValue(), cookieSetting.getPath(), cookieSetting.getDomain(), cookieSetting.getVersion(), cookieSetting.getComment(), cookieSetting.getMaxAge(), cookieSetting.isSecure()); } /** * Converts the given Restlet Variant to a JAX-RS Variant * * @param restletVariant * @return the JAX-RS Variant * @throws IllegalArgumentException * If the given Variant does not contain exactly one language * and one */ public static javax.ws.rs.core.Variant toJaxRsVariant( org.restlet.representation.Variant restletVariant) throws IllegalArgumentException { final MediaType mediaType = Converter.toJaxRsMediaType(restletVariant .getMediaType(), restletVariant.getCharacterSet()); final Locale language = toLocale(Util .getOnlyMetadataName(restletVariant.getLanguages())); final String encoding = Util.getOnlyMetadataName(restletVariant .getEncodings()); return new javax.ws.rs.core.Variant(mediaType, language, encoding); } /** * * @param locale * @return the Restlet Language */ public static Language toLanguage(Locale locale) { return new Language(locale.toString()); } /** * * @param locale * @return the Restlet Language */ public static Language toLanguage(String locale) { return new Language(locale); } /** * @param locale * @return the language string * @see #toLanguage(Locale) */ public static String toLanguageString(Locale locale) { return locale.toString(); } /** * Converts a {@link Locale} to a Restlet {@link Language}. * * @param language * @return the Locale * @see #toLocale(String) * @see Locale */ public static Locale toLocale(Language language) { return toLocale(language.getName()); } /** * Converts a locale String to a Restlet {@link Language}. * * @param language * @return the Locale * @see #toLocale(Language) * @see Locale */ public static Locale toLocale(String language) { if ((language == null) || (language.length() == 0)) { return null; } final StringTokenizer stt = new StringTokenizer(language, "_", true); final String lang = stt.nextToken(); if (stt.hasMoreTokens()) { stt.nextToken(); // skip "_" } if (!stt.hasMoreTokens()) { return new Locale(lang); } String country = stt.nextToken(); if (country.equals("_")) { country = ""; } else if (stt.hasMoreTokens()) { stt.nextToken(); // skip "_" } if (!stt.hasMoreTokens()) { return new Locale(lang, country); } final String variant = stt.nextToken(); return new Locale(lang, country, variant); } /** * @param parameters * @return the Map */ public static Map toMap(Series parameters) { if (parameters == null) { return null; } final Map map = new HashMap(); for (final Parameter parameter : parameters) { map.put(parameter.getName(), parameter.getValue()); } return map; } /** * Converts a JAX-RS Cookie to a Restlet Cookie * * @param jaxRsCookie * the JAX-RS Cookie * @return the Restlet Cookie */ public static org.restlet.data.Cookie toRestletCookie(Cookie jaxRsCookie) { if (jaxRsCookie == null) { return null; } return new org.restlet.data.Cookie(jaxRsCookie.getVersion(), jaxRsCookie.getName(), jaxRsCookie.getValue(), jaxRsCookie .getPath(), jaxRsCookie.getDomain()); } /** * Converts the Restlet JAX-RS NewCookie to a CookieSettings. * * @param newCookie * @return the converted CookieSetting * @throws IllegalArgumentException */ public static CookieSetting toRestletCookieSetting(NewCookie newCookie) throws IllegalArgumentException { if (newCookie == null) { return null; } return new CookieSetting(newCookie.getVersion(), newCookie.getName(), newCookie.getValue(), newCookie.getPath(), newCookie .getDomain(), newCookie.getComment(), newCookie .getMaxAge(), newCookie.isSecure()); } /** * Convert a JAX-RS MediaType to a Restlet MediaType. * * @param jaxRsMediaType * @return the converted MediaType */ public static org.restlet.data.MediaType toRestletMediaType( MediaType jaxRsMediaType) { if (jaxRsMediaType == null) { return null; } final Series parameters = Converter .toRestletSeries(jaxRsMediaType.getParameters()); final String name = jaxRsMediaType.getType() + "/" + jaxRsMediaType.getSubtype(); return new org.restlet.data.MediaType(name, parameters); } /** * @param parameters * @return a form with the given parameters. Will never return null. */ public static Form toRestletSeries(Map parameters) { final Form form = new Form(); if (parameters == null) { return form; } for (final Map.Entry parameter : parameters.entrySet()) { form.add(parameter.getKey(), parameter.getValue()); } return form; } /** * Converts a JAX-RS-EntityTag to a Restlet-EntityTag * * @param jaxRsEntityTag * the JAX-RS-EntityTag to convert. * @return The corresponding Restlet-Entity-Tag */ public static Tag toRestletTag(EntityTag jaxRsEntityTag) { if (jaxRsEntityTag == null) { return null; } return new Tag(jaxRsEntityTag.getValue(), jaxRsEntityTag.isWeak()); } /** * Converts the given JAX-RS Variants to Restlet Variants. * * @param jaxRsVariants * @return the List of Restlet Variants */ public static List toRestletVariants( Collection jaxRsVariants) { final List restletVariants = new ArrayList( jaxRsVariants.size()); for (final javax.ws.rs.core.Variant jaxRsVariant : jaxRsVariants) { final org.restlet.representation.Variant restletVariant = new org.restlet.representation.Variant(); restletVariant.setCharacterSet(getRestletCharacterSet(jaxRsVariant .getMediaType())); restletVariant.setEncodings(Util.createList(Encoding .valueOf(jaxRsVariant.getEncoding()))); restletVariant.setLanguages(Util.createList(toLanguage(jaxRsVariant .getLanguage()))); restletVariant.setMediaType(toRestletMediaType(jaxRsVariant .getMediaType())); restletVariants.add(restletVariant); } return restletVariants; } /** * @param cacheDirectives * @return the converted JAX-RS {@link CacheControl} */ public static CacheControl toJaxRsCacheControl( List cacheDirectives) { CacheControl jaxRsCacheControl = new CacheControl(); for (CacheDirective cacheDirective : cacheDirectives) { if (cacheDirective.getName() == HeaderConstants.CACHE_MAX_AGE) jaxRsCacheControl.setMaxAge(Integer.valueOf(cacheDirective .getValue())); else if (cacheDirective.getName() == HeaderConstants.CACHE_MUST_REVALIDATE) jaxRsCacheControl.setMustRevalidate(true); else if (cacheDirective.getName() == HeaderConstants.CACHE_NO_CACHE) jaxRsCacheControl.setNoCache(true); else if (cacheDirective.getName() == HeaderConstants.CACHE_NO_STORE) jaxRsCacheControl.setNoStore(true); else if (cacheDirective.getName() == HeaderConstants.CACHE_NO_TRANSFORM) jaxRsCacheControl.setNoTransform(true); else if (cacheDirective.getName() == HeaderConstants.CACHE_PROXY_MUST_REVALIDATE) jaxRsCacheControl.setProxyRevalidate(true); else if (cacheDirective.getName() == HeaderConstants.CACHE_PUBLIC) jaxRsCacheControl.setPrivate(false); else jaxRsCacheControl.getCacheExtension().put( cacheDirective.getName(), cacheDirective.getValue()); } return jaxRsCacheControl; } /** * @param cacheControl * @return the converted {@link CacheDirective} */ public static List toRestletCacheDirective( CacheControl cacheControl) { List directives = new ArrayList(); if (cacheControl.getMaxAge() >= 0) directives.add(CacheDirective.maxAge(cacheControl.getMaxAge())); if (cacheControl.getSMaxAge() >= 0) directives.add(CacheDirective.sharedMaxAge(cacheControl .getSMaxAge())); if (!cacheControl.getNoCacheFields().isEmpty()) directives.add(CacheDirective.noCache(cacheControl .getNoCacheFields())); if (!cacheControl.getPrivateFields().isEmpty()) directives.add(CacheDirective.privateInfo(cacheControl .getPrivateFields())); if (cacheControl.isMustRevalidate()) directives.add(CacheDirective.mustRevalidate()); if (cacheControl.isNoCache()) directives.add(CacheDirective.noCache()); if (cacheControl.isNoStore()) directives.add(CacheDirective.noStore()); if (cacheControl.isNoTransform()) directives.add(CacheDirective.noTransform()); if (cacheControl.isPrivate()) directives.add(CacheDirective.privateInfo()); if (cacheControl.isProxyRevalidate()) directives.add(CacheDirective.proxyMustRevalidate()); for (Map.Entry c : cacheControl.getCacheExtension() .entrySet()) { directives.add(new CacheDirective(c.getKey(), c.getValue())); } return directives; } private Converter() { // no instance creation } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/WrappedRequestForHttpHeaders.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/WrappedRequestForHttpHe0000664000175000017500000002004711757206350034404 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import org.restlet.Response; import org.restlet.data.Parameter; import org.restlet.ext.jaxrs.internal.core.MultivaluedMapImpl; import org.restlet.util.Series; /** * This class wraps the request to get the headers from, if needed in a * {@link MessageBodyWriter}. The changing of the http headers is not supported * by this runtime environment, because it is not a good design and Restlet does * not support it.
* This class is not thread safe. * * @author Stephan Koops */ public class WrappedRequestForHttpHeaders implements MultivaluedMap { /** * may be null, f content was not already copied from the * {@link #restletResponse}. */ private Series headers; /** may be null */ private MultivaluedMap jaxRsRespHeaders; /** null, if content was copied to the {@link #headers}. */ private Response restletResponse; /** * * @param restletResponse * @param jaxRsRespHeaders */ public WrappedRequestForHttpHeaders(Response restletResponse, MultivaluedMap jaxRsRespHeaders) { if (restletResponse == null) { throw new IllegalArgumentException( "The Restlet Response must not be null"); } this.restletResponse = restletResponse; this.jaxRsRespHeaders = jaxRsRespHeaders; } public void add(String headerName, Object headerValue) { unsupported(); } /** * @return */ private MultivaluedMap allToJaxRsHeaders() { final MultivaluedMap jaxRsRespHeaders = getJaxRsRespHeaders(); final Series headers = getHeaders(); if (headers != null) { for (final Parameter p : headers) { final String name = p.getName(); final String value = p.getValue(); final List values = jaxRsRespHeaders.get(name); boolean contained = false; if (values != null) { for (final Object v : values) { if ((v != null) && v.toString().equals(value)) { contained = true; } } } if (!contained) { jaxRsRespHeaders.add(name, value); } } this.headers = null; } return jaxRsRespHeaders; } public void clear() { unsupported(); } public boolean containsKey(Object headerName) { if (headerName == null) { return false; } if (this.jaxRsRespHeaders != null) { if (this.jaxRsRespHeaders.containsKey(headerName)) { return true; } } final Series headers = getHeaders(); if (headers != null) { for (final Parameter p : headers) { if (headerName.equals(p.getName())) { return true; } } } return false; } public boolean containsValue(Object headerValue) { if (this.jaxRsRespHeaders != null) { if (this.jaxRsRespHeaders.containsValue(headerValue)) { return true; } } final Series headers = getHeaders(); if (headers != null) { for (final Parameter p : headers) { if (headerValue.equals(p.getValue())) { return true; } } } return false; } public Set>> entrySet() { final MultivaluedMap jaxRsRespHeaders = allToJaxRsHeaders(); return jaxRsRespHeaders.entrySet(); } public List get(Object headerName) { return allToJaxRsHeaders().get(headerName); } public Object getFirst(String headerName) { if (this.jaxRsRespHeaders != null) { final Object rt = this.jaxRsRespHeaders.getFirst(headerName); if (rt != null) { return rt; } } final Series headers = getHeaders(); if (headers != null) { final Parameter first = headers.getFirst(headerName); if (first == null) { return null; } return first.getValue(); } return null; } /** * gets the Restlet headers. If the Restlet headers are not available, but * the Restlet Response, the headers are copied from the Response headers. * If both is not available, null is returned. * * @return */ private Series getHeaders() { if ((this.headers == null) && (this.restletResponse != null)) { this.headers = Util.copyResponseHeaders(this.restletResponse); this.restletResponse = null; } return this.headers; } private MultivaluedMap getJaxRsRespHeaders() { if (this.jaxRsRespHeaders == null) { this.jaxRsRespHeaders = new MultivaluedMapImpl(); } return this.jaxRsRespHeaders; } public boolean isEmpty() { if ((this.jaxRsRespHeaders != null) && !this.jaxRsRespHeaders.isEmpty()) { return false; } final Series headers = getHeaders(); if (headers != null) { return headers.isEmpty(); } return true; } public Set keySet() { return allToJaxRsHeaders().keySet(); } public List put(String headerName, List headerValues) { throw unsupported(); } public void putAll(Map> t) { unsupported(); } public void putSingle(String headerName, Object headerValue) { unsupported(); } public List remove(Object headerName) { throw unsupported(); } public int size() { int size = 0; if (this.jaxRsRespHeaders != null) { size = this.jaxRsRespHeaders.size(); } final Series headers = getHeaders(); if (headers != null) { size += headers.size(); } return size; } private UnsupportedOperationException unsupported() throws UnsupportedOperationException { throw new UnsupportedOperationException( "The changing of the http headers is not supported by this runtime environment."); } public Collection> values() { return allToJaxRsHeaders().values(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/PathRegExp.java0000664000175000017500000004001411757206350032570 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.Path; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; /** * Wraps a regular expression of a @{@link Path}. Instances are immutable. * The regular expression has no '/' t the start. * * @author Stephan Koops */ public class PathRegExp { /** * Default regular expression to use, if no reg exp is given (matches every * character expect '/'). * * @see #defaultRegExp */ private static final String DEFAULT_REG_EXP = "[^/]+?"; /** * The PathRegExp with an empty path. */ public static final PathRegExp EMPTY; private static final byte NAME_READ = 2; private static final byte NAME_READ_READY = 3; private static final byte NAME_READ_START = 1; private static final byte REGEXP_READ = 12; private static final byte REGEXP_READ_READY = 13; private static final byte REGEXP_READ_START = 11; static { try { EMPTY = new PathRegExp("", null); } catch (IllegalPathException e) { throw new RuntimeException("This could not occur", e); } } /** * Creates a {@link PathRegExp} for a root resource class. * * @param rrc * the JAX-RS root resource class * @return the PathRegExp from the given root resource class * @throws MissingAnnotationException * if the {@link Path} annotation is missing. * @throws IllegalPathOnClassException * if the {@link Path} annotation is not valid. * @throws IllegalArgumentException * if the rrc is null. * @see {@link #EMPTY} */ public static PathRegExp createForClass(Class rrc) throws MissingAnnotationException, IllegalPathOnClassException, IllegalArgumentException { final Path path = Util.getPathAnnotation(rrc); try { return new PathRegExp(path.value(), path); } catch (IllegalPathException ipe) { throw new IllegalPathOnClassException(ipe); } } /** * Creates a {@link PathRegExp} for a sub resource method or sub resource * locator. Returns {@link #EMPTY}, if the method is not annotated with * @Path. * * @param annotatedMethod * @return the {@link PathRegExp}. Never returns null. * @throws IllegalPathOnMethodException * if the annotation on the method is invalid. * @throws IllegalArgumentException * if the method is null. */ public static PathRegExp createForMethod(Method annotatedMethod) throws IllegalPathOnMethodException, IllegalArgumentException { final Path pathAnno = Util.getPathAnnotationOrNull(annotatedMethod); if (pathAnno == null) { return EMPTY; } try { return new PathRegExp(pathAnno.value(), pathAnno); } catch (IllegalPathException ipe) { throw new IllegalPathOnMethodException(ipe); } } private final boolean emptyOrSlash; /** Contains the number of literal chars in this Regular Expression */ private final Integer noLitChars; /** * Contains the number of capturing groups with regular expressions that are * not the default. * * @see #DEFAULT_REG_EXP */ private int noNonDefaultRegExp = 0; private final int noOfCapturingGroups; private final String pathTemplateDec; private final String pathTemplateEnc; private final Pattern pattern; private final List varNames = new ArrayList(); /** * Is intended for internal use and testing. Otherwise use the static * methods {@link #createForClass(Class)} or * {@link #createForMethod(Method)}, or the constant {@link #EMPTY}. * * @param pathPattern * @param pathForExcMess */ private PathRegExp(String pathTemplate, Path pathForExcMess) throws IllegalPathException { // 1. URI encode the template, ignoring URI template variable specs. // 2. Escape any regular expression characters in the URI template, // again ignoring URI template variable specifications. // 3. Replace each URI template variable with a capturing group // containing the specified regular expression or "([^/]+?)" if no // regular expression is specified. // LATER regexp in @Path: @Path("{p}/abc/{p}") is allowed, p may be != p if (pathTemplate == null) { throw new IllegalArgumentException( "The path template must not be null"); } final int l = pathTemplate.length(); final StringBuilder pathPattern = new StringBuilder(); int forStart = 0; if (l > 0 && pathTemplate.charAt(0) == '/') forStart = 1; int noLitChars = 0; int numberOfCapturingGroups = 0; for (int i = forStart; i < l; i++) { final char c = pathTemplate.charAt(i); if (c == '{') { i = processTemplVarname(pathTemplate, i, pathPattern, pathForExcMess); numberOfCapturingGroups++; } else if (c == '%') { try { EncodeOrCheck.processPercent(i, true, pathTemplate, pathPattern); } catch (IllegalArgumentException e) { throw new IllegalPathException(pathForExcMess, e); } } else if (c == '}') { throw new IllegalPathException(pathForExcMess, "'}' is only allowed as " + "end of a variable name in \"" + pathTemplate + "\""); } else if (c == ';') { throw new IllegalPathException(pathForExcMess, "matrix parameters are not allowed in a @Path"); } else if (!false && (c == '/')) { pathPattern.append(c); noLitChars++; } else { noLitChars += EncodeOrCheck.encode(c, pathPattern); } } this.noLitChars = noLitChars; this.noOfCapturingGroups = numberOfCapturingGroups; // 4. If the resulting string ends with "/" then remove the final char. // 5. Append "(/.*)?" to the result. if (pathPattern.length() > 0 && pathPattern.charAt(pathPattern.length() - 1) != '/') { pathPattern.append('/'); } pathPattern.append("(.*)"); this.pattern = Pattern.compile(pathPattern.toString()); this.emptyOrSlash = Util.isEmptyOrSlash(pathTemplate); if (l > 0) { if (pathTemplate.charAt(0) != '/') { pathTemplate = '/' + pathTemplate; } if (l > 1 && pathTemplate.endsWith("/")) { pathTemplate = pathTemplate.substring(0, pathTemplate.length() - 2); } } this.pathTemplateEnc = pathTemplate; // LATER encode unencoded here this.pathTemplateDec = pathTemplate; // LATER decode here } /** * Compares this regular expression of a @{@link Path} with the given * Object by comparing given patterns. */ @Override public boolean equals(Object anotherObject) { if (this == anotherObject) { return true; } if (!(anotherObject instanceof PathRegExp)) { return false; } final PathRegExp otherRegExp = (PathRegExp) anotherObject; return this.pattern.pattern().equals(otherRegExp.pattern.pattern()); } /** * @return the number of capturing groups with regular expressions that are * not the default. */ public int getNoNonDefCaprGroups() { return this.noNonDefaultRegExp; } /** * @return Returns the number of capturing groups. */ public int getNoOfCapturingGroups() { return this.noOfCapturingGroups; } /** * See Footnode to JSR-311-Spec, Section 2.6, Algorithm, Part 1e * * @return Returns the number of literal chars in the path patern */ public int getNoOfLiteralChars() { return this.noLitChars; } /** * @return the decoded path template with a '/' at the beginning, and no one * at the end. */ public String getPathTemplateDec() { return this.pathTemplateDec; } /** * @return the encoded path template with a '/' at the beginning, and no one * at the end. */ public String getPathTemplateEnc() { return this.pathTemplateEnc; } @Override public int hashCode() { return this.pattern.pattern().hashCode(); } /** * Checks if the URI template is empty or only a slash. * * @return if this path regular expression is empty or "/" */ public boolean isEmptyOrSlash() { return this.emptyOrSlash; } /** * Checks if this regular expression matches the given remaining path. * * @param remainingPath * @return Returns an MatchingResult, if the remainingPath matches to this * template, or null, if not. */ public MatchingResult match(RemainingPath remainingPath) { String givenPath = remainingPath.getWithoutParams(); Matcher matcher = pattern.matcher(givenPath); if (!matcher.matches()) { return null; } final Map templateVars = new HashMap(); for (int i = 1; i < matcher.groupCount(); i++) { templateVars.put(this.varNames.get(i - 1), matcher.group(i)); } String finalCapturingGroup = matcher.group(matcher.groupCount()); // if (finalCapturingGroup.length() > 0) { // if (pathSuppl && finalCapturingGroup.endsWith("/")) { // finalCapturingGroup = finalCapturingGroup.substring(0, // finalCapturingGroup.length() - 1); // } // if (!finalCapturingGroup.startsWith("/")) { // finalCapturingGroup = "/" + finalCapturingGroup; // } // } int matchedChars = givenPath.length() - finalCapturingGroup.length(); if ((matchedChars > 0) && (givenPath.charAt(matchedChars - 1) == '/')) { matchedChars--; // ignore '/' at end } final String matchedPart = givenPath.substring(0, matchedChars); return new MatchingResult(matchedPart, templateVars, finalCapturingGroup); } /** * Checks, if this regular expression matches the given path with no final * matching group. * * @param remainingPath * @return true, if this regular expression matches exectly the given path, * without a final capturing group. */ public boolean matchesWithEmpty(RemainingPath remainingPath) { final MatchingResult matchingResult = match(remainingPath); if (matchingResult == null) { return false; } return matchingResult.getFinalCapturingGroup().isEmptyOrSlash(); } /** * @param pathTemplate * @param braceIndex * @param pathPattern * @param pathForExcMess * @throws IllegalPathException */ private int processTemplVarname(final String pathTemplate, final int braceIndex, final StringBuilder pathPattern, final Path pathForExcMess) throws IllegalPathException { pathPattern.append('('); final int l = pathTemplate.length(); final StringBuilder varName = new StringBuilder(); final StringBuilder regExp = new StringBuilder(); int state = NAME_READ_START; for (int i = braceIndex + 1; i < l; i++) { final char c = pathTemplate.charAt(i); if (c == '{') { throw new IllegalPathException(pathForExcMess, "A variable must not " + "contain an extra '{' in \"" + pathTemplate + "\""); } else if (c == ' ' || c == '\t') { if (state == NAME_READ) state = NAME_READ_READY; else if (state == REGEXP_READ) state = REGEXP_READ_READY; continue; } else if (c == ':') { if (state == NAME_READ_START) { throw new IllegalPathException(pathForExcMess, "The variable name at position must not be null at " + braceIndex + " of \"" + pathTemplate + "\""); } if (state == NAME_READ || state == NAME_READ_READY) { state = REGEXP_READ_START; } continue; } else if (c == '}') { if (state == NAME_READ_START) { throw new IllegalPathException(pathForExcMess, "The template variable name '{}' is not allowed in " + "\"" + pathTemplate + "\""); } else if ((state == REGEXP_READ) || (state == REGEXP_READ_READY)) { pathPattern.append(regExp); if (!regExp.equals(DEFAULT_REG_EXP)) { this.noNonDefaultRegExp++; } } else { pathPattern.append(DEFAULT_REG_EXP); } pathPattern.append(')'); this.varNames.add(varName.toString()); return i; } if (state == NAME_READ_START) { state = NAME_READ; varName.append(c); } else if (state == NAME_READ) { varName.append(c); } else if (state == REGEXP_READ_START) { state = REGEXP_READ; regExp.append(c); } else if (state == REGEXP_READ) { regExp.append(c); } else { throw new IllegalPathException(pathForExcMess, "Invalid character found at position " + i + " of \"" + pathTemplate + "\""); } } throw new IllegalPathException(pathForExcMess, "No '}' found after '{' " + "at position " + braceIndex + " of \"" + pathTemplate + "\""); } @Override public String toString() { return this.pattern.pattern(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/RemainingPath.java0000664000175000017500000000766111757206350033322 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; /** * This class contains the remaining path for a request. It does not contain any * matrix parameterand has no '/' t the start. * * @author Stephan Koops */ public class RemainingPath implements Comparable { /** * removes the matrix parameters from the given uri path.
* Also adds a '/' at the end, if there is no slash at the end. * * @param remainingPart * @return the given uri path without the matrix parameters. */ private static String removeMatrixParams(String remainingPart) { final StringBuilder stb; if (remainingPart.startsWith("/")) stb = new StringBuilder(remainingPart.substring(1)); else stb = new StringBuilder(remainingPart); int mpEndPos = Integer.MAX_VALUE; for (int i = stb.length() - 1; i >= 0; i--) { final char character = stb.charAt(i); if (character == '?') { stb.delete(i, Integer.MAX_VALUE); } else if (character == ';') { stb.delete(i, mpEndPos); mpEndPos = i; } else if (character == '/') { mpEndPos = i; } } if (stb.length() == 0 || stb.charAt(stb.length() - 1) != '/') stb.append('/'); return stb.toString(); } /** contains the given remaining path without matrix parameters. */ private final String remainingPart; /** * Creates a new RemianingPath wrapper. * * @param remainingPart */ public RemainingPath(String remainingPart) { this.remainingPart = removeMatrixParams(remainingPart); } public int compareTo(RemainingPath other) { return this.remainingPart.compareTo(other.remainingPart); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof RemainingPath)) { return false; } return this.remainingPart.equals(other.toString()); } /** * Returns the path without matrix and query parameters. * * @return the path without matrix and query parameters. */ public String getWithoutParams() { return this.remainingPart; } @Override public int hashCode() { return this.remainingPart.hashCode(); } /** * Checks, if the remaining path is empty or slash. * * @return true, of this remaining path is empty or '/', otherwise false. */ public boolean isEmptyOrSlash() { return Util.isEmptyOrSlash(this.remainingPart); } @Override public String toString() { return this.remainingPart; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/OneElementIterator.java0000664000175000017500000000472211757206350034334 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.Iterator; import java.util.NoSuchElementException; /** * Iterator that iterates over exact one element. * * @author Stephan Koops * @param * The type of the contained object. */ public class OneElementIterator implements Iterator { private final T element; private boolean hasNext = true; /** * @param element * The element to iterate over. May be null. */ public OneElementIterator(T element) { this.element = element; } /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return this.hasNext; } /** * @see java.util.Iterator#next() */ public T next() throws NoSuchElementException { if (!this.hasNext) { throw new NoSuchElementException("The element was already returned"); } this.hasNext = false; return this.element; } /** * @see java.util.Iterator#remove() * @throws UnsupportedOperationException */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException( "The OneElementIterator is not modifiable"); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/SecurityUtil.java0000664000175000017500000000644411757206350033237 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.List; import org.restlet.Request; /** * Security utilities. * * @author Stephan Koops */ public class SecurityUtil { /** Key in the request attributes for the HTTPS client certificates. */ private static final String ORG_RESTLET_HTTPS_CLIENT_CERTS = "org.restlet.https.clientCertificates"; /** * Returns the Principal from the SSL client certificates (the first with a * name). * * @param request * The Request to get the Principal from. * @return The Principal, or null, if no one is found. */ public static Principal getSslClientCertPrincipal(Request request) { final List sslClientCerts = getSslClientCerts(request); if (sslClientCerts != null) { for (final X509Certificate cert : sslClientCerts) { final Principal p = cert.getSubjectDN(); if ((p.getName() != null) && (p.getName().length() > 0)) { return p; } } } return null; } // LATER load auth data from Servlet-API ? /** * Returns the client certificates from the given Request. * * @param request * The request to get the client certificates from * @return the client certifucates. May be null. */ @SuppressWarnings("unchecked") private static List getSslClientCerts(Request request) { return (List) request.getAttributes().get( ORG_RESTLET_HTTPS_CLIENT_CERTS); } /** * Checks, if the given request was authenticated by a SSL client * certificate. * * @param request * The Request to check * @return true, if the given request was authenticated by a SSL client * certificate, otherwise false. */ public static boolean isSslClientCertAuth(Request request) { return getSslClientCerts(request) != null; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/SortedMetadata.java0000664000175000017500000001702411757206350033467 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.TreeMap; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Preference; /** * SortedMetadata contains given Metadata, sorted by it's quality, Metadata with * the highest quality first. * * @author Stephan Koops * @param * the Metadata type the instance contains. */ public class SortedMetadata implements Iterable { @SuppressWarnings("hiding") private class IteratorIterator implements Iterator { private final Iterator> iterIter; private Iterator iter; IteratorIterator(Iterator> iterIter) { this.iterIter = iterIter; } public boolean hasNext() { if ((this.iter != null) && this.iter.hasNext()) { return true; } while (this.iterIter.hasNext()) { final Iterable iterable = this.iterIter.next(); if (iterable != null) { this.iter = iterable.iterator(); if (this.iter.hasNext()) { return true; } } } return false; } public T next() { if (this.hasNext()) { return this.iter.next(); } throw new NoSuchElementException(); } /** * * @see java.util.Iterator#remove() */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } } /** * @param respMediaType * @return the media type as singleton of SortedMetadata */ public static SortedMetadata get(MediaType respMediaType) { return new SortedMetadata( Collections.singleton(new Preference(respMediaType))); } /** * Returns an empty SortedMetadata * * @return an empty SortedMetadata */ public static SortedMetadata getEmptyMediaTypes() { return new SortedMetadata( new ArrayList>()); } /** * Creates a new {@link SortedMetadata} for {@link MediaType}s. * * @param preferences * @return the given languages as SortedMetadata */ public static SortedMetadata getForLanguages( Collection> preferences) { return new SortedMetadata(preferences); } /** * Creates a new {@link SortedMetadata} for {@link MediaType}s. If the given * Collection is empty, {@link MediaType#ALL} is returned. * * @param preferences * @return the given media type as SortedMetadata */ public static SortedMetadata getForMediaTypes( Collection> preferences) { if (preferences.isEmpty()) { return new SortedMetadata( Collections .singletonList((Collection) Collections .singletonList(MediaType.ALL))); } return new SortedMetadata(preferences); } /** * Creates a SortedMetadata collection with exactly the {@link MediaType} * '*/*'' * * @return '*/*'' as SortedMediaType * @see MediaType#ALL */ public static SortedMetadata getMediaTypeAll() { return new SortedMetadata(Collections.singletonList(Util .createColl(MediaType.ALL))); } /** * * @param mediaType * @return the media type as singleton as SortedMetadata * @see Collections#singleton(Object) */ public static SortedMetadata singleton(MediaType mediaType) { return new SortedMetadata(Collections.singletonList(Util .createColl(mediaType))); } private final List> metadatas; /** * Creates a new SortedMetadata from the given Metadata. * * @param preferences */ @SuppressWarnings({ "unchecked", "rawtypes" }) private SortedMetadata(Collection> preferences) { final SortedMap> map = new TreeMap>( Collections.reverseOrder()); for (final Preference preference : preferences) { final Float quality = preference.getQuality(); Collection metadatas = map.get(quality); if (metadatas == null) { metadatas = new ArrayList(2); map.put(quality, metadatas); } metadatas.add(preference.getMetadata()); } final Collection> values = map.values(); this.metadatas = Collections.unmodifiableList(new ArrayList(values)); } /** * Creates a new SortedMetadata from the sorted Metadata. * * @param metadatas */ private SortedMetadata(List> metadatas) { this.metadatas = metadatas; } /** * Checks, if this SortedMetadata is empty * * @return true, if this sorted metadata is empty, or false if not. * @see Collection#isEmpty() */ public boolean isEmpty() { return this.metadatas.isEmpty(); } /** * Iterates over all the sorted Metadata. * * @see java.lang.Iterable#iterator() */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Iterator iterator() { return new IteratorIterator(this.metadatas.iterator()); } /** * Returns the list of collections as {@link Iterable} of {@link Iterable}s. * * @return the list of collections as {@link Iterable} of {@link Iterable}s. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Iterable> listOfColls() { return (Iterable) this.metadatas; } @Override public String toString() { return this.metadatas.toString(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/ExceptionHandler.java0000664000175000017500000004243311757206350034024 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.restlet.Request; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.ext.jaxrs.InstantiateException; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.MethodInvokeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.NotAcceptableWebAppException; import org.restlet.ext.jaxrs.internal.exceptions.RequestHandledException; import org.restlet.ext.jaxrs.internal.exceptions.UnsupportedMediaTypeWebAppException; import org.restlet.ext.jaxrs.internal.wrappers.AbstractMethodWrapper; import org.restlet.ext.jaxrs.internal.wrappers.ResourceMethod; /** *

* This class contains the methods to handle exceptions occuring in the * {@link org.restlet.ext.jaxrs.JaxRsRestlet}, e.g. while identifying the method * that should handle the request.
* Therefor it contains some Restlets that handles this exceptions. *

*

* Perhaps this class gets again public. Perhaps the special Restlets for * handling will be removed, or stay only for 404. *

* * @author Stephan Koops */ public class ExceptionHandler { private static final String HEADER_ALLOW = "Allow"; /** * @param supporting * @return */ private static Set getSupportedVariants( Collection supporting) { final Set supportedVariants = new HashSet(); for (final ResourceMethod resourceMethod : supporting) { supportedVariants.addAll(resourceMethod.getSupportedVariants()); } return supportedVariants; } private final Logger logger; private volatile Restlet noResMethodHandler; private volatile Restlet noResourceClHandler; private volatile Restlet noRootResClHandler; /** * Creates a new ExceptionHandler. * * @param logger * the logger to use */ public ExceptionHandler(Logger logger) { this.logger = logger; } /** * handles a {@link ConvertRepresentationException} * * @param cre * @return (static the thrown exeption for the compiler) * @throws WebApplicationException */ public WebApplicationException convertRepresentationExc( ConvertRepresentationException cre) throws WebApplicationException { final ResponseBuilder rb = Response.status(Status.BAD_REQUEST); final StringWriter stw = new StringWriter(); cre.printStackTrace(new PrintWriter(stw)); rb.entity(stw.toString()); throw new WebApplicationException(cre, rb.build()); } /** * Returns the Restlet that is called, if no resource method class could be * found. * * @return the Restlet that is called, if no resource method class could be * found. * @see #setNoResMethodHandler(Restlet) */ public Restlet getNoResMethodHandler() { return noResMethodHandler; } /** * Returns the Restlet that is called, if no resource class could be found. * * @return the Restlet that is called, if no resource class could be found. */ public Restlet getNoResourceClHandler() { return noResourceClHandler; } /** * Returns the Restlet that is called, if no root resource class could be * found. * * @return the Restlet that is called, if no root resource class could be * found. * @see #setNoRootResClHandler(Restlet) */ public Restlet getNoRootResClHandler() { return noRootResClHandler; } /** * Handles the given Exception, catched by an invoke of a resource method or * a creation if a sub resource object. * * @param exception * @param callContext * Contains the encoded template Parameters, that are read from * the called URI, the Restlet {@link org.restlet.Request} and * the Restlet {@link org.restlet.Response}. * @param methodName * @param logMessage * @return staticly to throw, if needed by compiler. * @throws RequestHandledException * throws this message to exit the method and indicate, that the * request was handled. * @throws RequestHandledException */ public RequestHandledException instantiateExecption( InstantiateException exception, CallContext callContext, String logMessage) throws RequestHandledException { callContext.getResponse().setStatus( org.restlet.data.Status.SERVER_ERROR_INTERNAL); this.logger.log(Level.WARNING, logMessage, exception.getCause()); exception.printStackTrace(); throw new RequestHandledException(); } /** * Handles the given Exception, catched by an invoke of a resource method or * a creation if a sub resource object. * * @param exception * @param callContext * Contains the encoded template Parameters, that are read from * the called URI, the Restlet {@link org.restlet.Request} and * the Restlet {@link org.restlet.Response}. * @param methodName * @param logMessage * @return staticly to throw, if needed by compiler. * @throws RequestHandledException * throws this message to exit the method and indicate, that the * request was handled. * @throws RequestHandledException */ public RequestHandledException methodInvokeException( MethodInvokeException exception, CallContext callContext, String logMessage) throws RequestHandledException { callContext.getResponse().setStatus( org.restlet.data.Status.SERVER_ERROR_INTERNAL); this.logger.log(Level.WARNING, logMessage, exception.getCause()); exception.printStackTrace(); throw new RequestHandledException(); } /** * @param allowedMethods * @throws WebApplicationException */ public void methodNotAllowed(Set allowedMethods) throws WebApplicationException { final ResponseBuilder rb = Response .status(org.restlet.data.Status.CLIENT_ERROR_METHOD_NOT_ALLOWED .getCode()); rb.header(HEADER_ALLOW, Util.toString(allowedMethods, ", ")); throw new WebApplicationException(rb.build()); } /** * Handles the given Exception, catched by an invoke of a resource method or * a creation if a sub resource object. * * @param exception * @param callContext * Contains the encoded template Parameters, that are read from * the called URI, the Restlet {@link org.restlet.Request} and * the Restlet {@link org.restlet.Response}. * @param methodName * @param logMessage * @return staticly to throw, if needed by compiler. * @throws RequestHandledException * throws this message to exit the method and indicate, that the * request was handled. * @throws RequestHandledException */ public RequestHandledException missingAnnotation( MissingAnnotationException exception, CallContext callContext, String logMessage) throws RequestHandledException { callContext.getResponse().setStatus( org.restlet.data.Status.SERVER_ERROR_INTERNAL); if (exception != null) { logMessage += ": " + exception.getMessage(); } this.logger.log(Level.WARNING, logMessage); throw new RequestHandledException(); } /** * @param entityClass * @param genericType * @param annotations * @param respMediaType * @param accMediaTypes * @return (static the thrown exeption for the compiler) * @throws WebApplicationException * the exception to throw according to the JAX-RS specification. */ public WebApplicationException noMessageBodyWriter( Class entityClass, Type genericType, Annotation[] annotations, MediaType respMediaType, SortedMetadata accMediaTypes) throws WebApplicationException { String warning = "No message body writer found for " + entityClass + "(generic type is " + genericType + ")"; if (respMediaType != null) { warning += "; response media type should be: " + respMediaType; } if (accMediaTypes != null) { warning += "; accepted media types are: " + accMediaTypes; } this.logger.warning(warning); annotations.toString(); // LATER log also annotations // NICE get as parameters the accMediaTypes and the entityClass. // and return supported MediaTypes as entity throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } /** * see spec, section 3.7.2, item 3(a).4 * * @param supporting * the methods supporting the requested resource and the given * HTTP method. * @throws WebApplicationException */ public void noResourceMethodForAccMediaTypes( Collection supporting) throws WebApplicationException { final Set supportedVariants = getSupportedVariants(supporting); throw new NotAcceptableWebAppException(supportedVariants); } /** * see spec, section 3.8, item 6 * * @return staticly to throw, if needed by compiler. * @throws WebApplicationException */ public WebApplicationException notAcceptableWhileDetermineMediaType() throws WebApplicationException { // NICE return supported MediaTypes as entity throw new WebApplicationException(Status.NOT_ACCEPTABLE); } /** * Handles the case, if no resource method was found. If a Restlet to handle * this case was given (see {@link #setNoResMethodHandler(Restlet)}), it is * called. Otherwise a {@link WebApplicationException} with status 404 is * thrown (see JAX-RS specification) * * @throws WebApplicationException * @throws RequestHandledException */ public void resourceMethodNotFound() throws WebApplicationException, RequestHandledException { if (this.noResMethodHandler != null) { this.noResMethodHandler.handle(Request.getCurrent(), org.restlet.Response.getCurrent()); throw new RequestHandledException(); } throw new WebApplicationException(Status.NOT_FOUND); } /** * Handles the case, if no resource class was found. If a Restlet to handle * this case was given (see {@link #setNoResourceClHandler(Restlet)}), it is * called. Otherwise a {@link WebApplicationException} with status 404 is * thrown (see spec, section 3.7.2, item 2e) * * @throws WebApplicationException * @throws RequestHandledException */ public void resourceNotFound() throws WebApplicationException, RequestHandledException { if (this.noResourceClHandler != null) { this.noResourceClHandler.handle(Request.getCurrent(), org.restlet.Response.getCurrent()); throw new RequestHandledException(); } throw new WebApplicationException(Status.NOT_FOUND); } /** * Handles the case, if no root resource class was found. If a Restlet to * handle this case was given (see {@link #setNoRootResClHandler(Restlet)}), * it is called. Otherwise a {@link WebApplicationException} with status 404 * is thrown (see JAX-RS specification, section 3.7.2, item 1d) * * @throws WebApplicationException * @throws RequestHandledException */ public void rootResourceNotFound() throws WebApplicationException, RequestHandledException { if (this.noRootResClHandler != null) { this.noRootResClHandler.handle(Request.getCurrent(), org.restlet.Response.getCurrent()); throw new RequestHandledException(); } throw new WebApplicationException(Status.NOT_FOUND); } /** * Handles the given Exception, catched by an invoke of a resource method or * a creation if a sub resource object. * * @param exception * the exception to log * @param jaxRsMethod * the called method when the exception occurs. May be null. * @param callContext * Contains the encoded template Parameters, that are read from * the called URI, the Restlet {@link org.restlet.Request} and * the Restlet {@link org.restlet.Response}. * @param logMessage * @param methodName * @return staticly to throw, if needed by compiler. * @throws RequestHandledException * throws this message to exit the method and indicate, that the * request was handled. * @throws RequestHandledException */ public RequestHandledException runtimeExecption(RuntimeException exception, AbstractMethodWrapper jaxRsMethod, CallContext callContext, String logMessage) throws RequestHandledException { callContext.getResponse().setStatus( org.restlet.data.Status.SERVER_ERROR_INTERNAL); if (jaxRsMethod != null) { logMessage = jaxRsMethod + ": " + logMessage; } this.logger.log(Level.WARNING, jaxRsMethod + ": " + logMessage, exception); exception.printStackTrace(); throw new RequestHandledException(); } /** * Sets the Restlet that will handle the {@link Request}s, if no resource * method could be found. * * @param noResMethodHandler * the noResMethodHandler to set * @see #getNoResMethodHandler() * @see #setNoResourceClHandler(Restlet) * @see #setNoRootResClHandler(Restlet) */ public void setNoResMethodHandler(Restlet noResMethodHandler) { this.noResMethodHandler = noResMethodHandler; } /** * Sets the Restlet that will handle the {@link Request}s, if no resource * class could be found. * * @param noResourceClHandler * the noResourceClHandler to set * @see #getNoResourceClHandler() * @see #setNoResMethodHandler(Restlet) * @see #setNoRootResClHandler(Restlet) */ public void setNoResourceClHandler(Restlet noResourceClHandler) { this.noResourceClHandler = noResourceClHandler; } /** * Sets the Restlet that is called, if no root resource class could be * found. * * @param noRootResClHandler * the Restlet to call, if no root resource class could be found. * @see #getNoRootResClHandler(Restlet) * @see #setNoResourceClHandler() * @see #setNoResMethodHandler(Restlet) */ public void setNoRootResClHandler(Restlet noRootResClHandler) { this.noRootResClHandler = noRootResClHandler; } /** * see spec, section 3.7.2, item 3 (a) .3 * * @param accepting * resource methods for the requested resource and the given HTTP * method. * @throws WebApplicationException */ public void unsupportedMediaType(Collection accepting) throws WebApplicationException { final Set acceptedVariants = getSupportedVariants(accepting); throw new UnsupportedMediaTypeWebAppException(acceptedVariants); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/AlgorithmUtil.java0000664000175000017500000004123411757206350033352 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.wrappers.ResourceMethod; import org.restlet.ext.jaxrs.internal.wrappers.RrcOrRml; import org.restlet.ext.jaxrs.internal.wrappers.SubResourceLocator; /** * This class contains helper methods for the algorithm in * {@link org.restlet.ext.jaxrs.JaxRsRestlet}. * * @author Stephan Koops */ public class AlgorithmUtil { private static enum ConsOrProdMime { /** * Declares that the methods etc. for the consume mime shoud be used */ CONSUME_MIME, /** * Declares that the methods etc. for the produced mime shoud be used */ PRODUCE_MIME } /** * Adds the matched template parameters to the {@link CallContext}. * * @param matchResult * @param callContext * Contains the encoded template Parameters, that are read * from the called URI, the Restlet {@link Request} and the * Restlet {@link Response}. */ public static void addPathVarsToMap(MatchingResult matchResult, CallContext callContext) { final Map variables = matchResult.getVariables(); for (final Map.Entry varEntry : variables.entrySet()) { final String key = varEntry.getKey(); final String value = varEntry.getValue(); callContext.addPathParamsEnc(key, value); } } private static OrderedMap> findMethodsSupportAllTypes( Collection resourceMethods, ConsOrProdMime inOut) { final OrderedMap> returnMethods = new OrderedMap>(); for (final ResourceMethod resourceMethod : resourceMethods) { final List mimes = getConsOrProdMimes(resourceMethod, inOut); for (final MediaType resMethMediaType : mimes) { if (resMethMediaType.equals(MediaType.ALL)) { returnMethods.put(resourceMethod, mimes); } } } return returnMethods; } private static OrderedMap> findMethodsSupportType( Collection resourceMethods, ConsOrProdMime inOut, SortedMetadata mediaTypes) { final OrderedMap> returnMethods = new OrderedMap>(); for (final ResourceMethod resourceMethod : resourceMethods) { final List mimes = getConsOrProdMimes(resourceMethod, inOut); for (final MediaType resMethMediaType : mimes) { for (final MediaType mediaType : mediaTypes) { final String resMethMainType = resMethMediaType .getMainType(); final String wishedMainType = mediaType.getMainType(); if (resMethMainType.equals(wishedMainType)) { returnMethods.put(resourceMethod, mimes); } } } } return returnMethods; } /** * @param resourceMethods * @param inOut * @param mediaType * @return Never returns null. */ private static OrderedMap> findMethodsSupportTypeAndSubType( Collection resourceMethods, ConsOrProdMime inOut, SortedMetadata mediaTypes) { final OrderedMap> returnMethods = new OrderedMap>(); for (final ResourceMethod resourceMethod : resourceMethods) { final List mimes = getConsOrProdMimes(resourceMethod, inOut); for (final MediaType resMethMediaType : mimes) { for (final MediaType mediaType : mediaTypes) { if (resMethMediaType.equals(mediaType, true)) { returnMethods.put(resourceMethod, mimes); } } } } return returnMethods; } /** * @param resourceMethods * @param inOut * @param mediaType * @return */ private static OrderedMap> findMethodSupportsMime( Collection resourceMethods, ConsOrProdMime inOut, SortedMetadata mediaTypes) { if ((mediaTypes == null) || mediaTypes.isEmpty()) { return findMethodsSupportAllTypes(resourceMethods, inOut); } OrderedMap> mms; mms = findMethodsSupportTypeAndSubType(resourceMethods, inOut, mediaTypes); if (mms.isEmpty()) { mms = findMethodsSupportType(resourceMethods, inOut, mediaTypes); if (mms.isEmpty()) { mms = findMethodsSupportAllTypes(resourceMethods, inOut); } } return mms; } /** * Sorts the ResourceMethods by it's number of non default regular * expressions */ private static Comparator COMP = new Comparator() { public int compare(ResourceMethod rm1, ResourceMethod rm2) { int nndre1 = rm1.getPathRegExp().getNoNonDefCaprGroups(); int nndre2 = rm2.getPathRegExp().getNoNonDefCaprGroups(); return nndre2 - nndre1; } }; /** * Sort by using the media type of input data as the primary key and the * media type of output data as the secondary key.
* Sorting of media types follows the general rule: x/y < x/* < */*, * i.e. a method that explicitly lists one of the requested media types is * sorted before a method that lists */*. Quality parameter values * are also used such that x/y;q=1.0 < x/y;q=0.7.
* See JSR-311 Spec, section 2.6, Part 3b+c.
* Never returns null. * * @param unsortedResourceMethods * the resourceMethods that provide the required mediaType * @param givenMediaType * The MediaType of the given entity. * @param accMediaTypes * The accepted MediaTypes * @param requHttpMethod * The HTTP method of the request. * @return Returns the method who best matches the given and accepted media * type in the request, or null */ public static ResourceMethod getBestMethod( Collection unsortedResourceMethods, MediaType givenMediaType, SortedMetadata accMediaTypes, Method requHttpMethod) { final Collection resourceMethods; resourceMethods = new SortedOrderedBag(COMP, unsortedResourceMethods); // 3 b+c SortedMetadata givenMediaTypes; if (givenMediaType != null) { givenMediaTypes = SortedMetadata.singleton(givenMediaType); } else { givenMediaTypes = null; } // mms = methods that support the given MediaType OrderedMap> mms1; mms1 = findMethodSupportsMime(resourceMethods, ConsOrProdMime.CONSUME_MIME, givenMediaTypes); if (mms1.size() == 1) { return Util.getFirstKey(mms1); } if (mms1.isEmpty()) { return Util.getFirstElement(resourceMethods); } // check for method with best Produces (secondary key) // mms = Methods support given MediaType and requested MediaType Map> mms2; mms2 = findMethodSupportsMime(mms1.keySet(), ConsOrProdMime.PRODUCE_MIME, accMediaTypes); if (mms2.size() == 1) { return Util.getFirstKey(mms2); } if (mms2.isEmpty()) { return Util.getFirstKey(mms1); } for (final MediaType accMediaType : accMediaTypes) { ResourceMethod bestResMethod = null; for (final Map.Entry> mm : mms2 .entrySet()) { for (final MediaType methodMediaType : mm.getValue()) { if (accMediaType.includes(methodMediaType)) { final ResourceMethod currentResMethod = mm.getKey(); if (bestResMethod == null) { bestResMethod = currentResMethod; } else { if (requHttpMethod.equals(Method.HEAD)) { // special handling for HEAD final Method bestMethodHttp; bestMethodHttp = bestResMethod.getHttpMethod(); if (bestMethodHttp.equals(Method.GET) && currentResMethod.getHttpMethod() .equals(Method.HEAD)) { // ignore HEAD method } else if (bestMethodHttp.equals(Method.HEAD) && currentResMethod.getHttpMethod() .equals(Method.GET)) { bestResMethod = currentResMethod; } else { // use one of the methods, e.g. the first } } else { // use one of the methods, e.g. the first } } } } } if (bestResMethod != null) { return bestResMethod; } } return Util.getFirstKey(mms2); } /** * @param resourceMethod * @param inOut * @return */ private static List getConsOrProdMimes( ResourceMethod resourceMethod, ConsOrProdMime inOut) { if (inOut.equals(ConsOrProdMime.CONSUME_MIME)) { return resourceMethod.getConsumedMimes(); } final List producedMimes = resourceMethod.getProducedMimes(); if (producedMimes.isEmpty()) { return Util.createList(MediaType.ALL); } return producedMimes; } /** * Implementation of algorithm in JSR-311-Spec, Revision 151, Version * 2008-08-27, Section 3.7.2, Part 1.e and nearly the same part 2f+2g.
* Sort E using *
    *
  1. the number of literal characters in each member as the primary key * (descending order),
  2. *
  3. the number of capturing groups as a secondary key (descending * order),
  4. *
  5. the number of capturing groups with non-default regular expressions * (i.e. not "([^/]+?)") as the tertiary key (descending order), and
  6. *
  7. the source of each member as quaternary key sorting those derived * from Tmethod ahead of those derived from Tlocator.
  8. *
* * @param * * @param rrcOrRmls * Collection of Sub-ResourceMethods and SubResourceLocators * or root resource class wrappers. * @return the resource method or sub resource locator or root resource * class, or null, if the Map is null or empty. */ public static R getFirstByNoOfLiteralCharsNoOfCapturingGroups( Collection rrcOrRmls) { if ((rrcOrRmls == null) || rrcOrRmls.isEmpty()) { return null; } final Iterator srmlIter = rrcOrRmls.iterator(); R bestSrml = srmlIter.next(); if (rrcOrRmls.size() == 1) { return bestSrml; } int bestSrmlChars = Integer.MIN_VALUE; int bestSrmlNoCaptGroups = Integer.MIN_VALUE; int bestSrmlNoNonDefCaptGroups = Integer.MIN_VALUE; for (final R srml : rrcOrRmls) { final PathRegExp srmlRegExp = srml.getPathRegExp(); final int srmlNoLitChars = srmlRegExp.getNoOfLiteralChars(); final int srmlNoCaptGroups = srmlRegExp.getNoOfCapturingGroups(); final int srmlNoNonDefCaptGroups = srmlRegExp .getNoNonDefCaprGroups(); if (srmlNoLitChars > bestSrmlChars) { bestSrml = srml; bestSrmlChars = srmlNoLitChars; bestSrmlNoCaptGroups = srmlNoCaptGroups; bestSrmlNoNonDefCaptGroups = srmlNoNonDefCaptGroups; continue; } if (srmlNoLitChars == bestSrmlChars) { if (srmlNoCaptGroups > bestSrmlNoCaptGroups) { bestSrml = srml; bestSrmlChars = srmlNoLitChars; bestSrmlNoCaptGroups = srmlNoCaptGroups; bestSrmlNoNonDefCaptGroups = srmlNoNonDefCaptGroups; continue; } if (srmlNoCaptGroups == bestSrmlNoCaptGroups) { if (srmlNoNonDefCaptGroups > bestSrmlNoNonDefCaptGroups) { bestSrml = srml; bestSrmlChars = srmlNoLitChars; bestSrmlNoCaptGroups = srmlNoCaptGroups; bestSrmlNoNonDefCaptGroups = srmlNoNonDefCaptGroups; continue; } if (srmlNoCaptGroups == bestSrmlNoCaptGroups) { if ((srml instanceof ResourceMethod) && (bestSrml instanceof SubResourceLocator)) { // prefare methods ahead locators bestSrml = srml; bestSrmlChars = srmlNoLitChars; bestSrmlNoCaptGroups = srmlNoCaptGroups; bestSrmlNoNonDefCaptGroups = srmlNoNonDefCaptGroups; continue; } } } } } return bestSrml; } /** * Removes the {@link ResourceMethod}s from the collection, that do not * support the given HTTP method. * * @param resourceMethods * the collection of {@link ResourceMethod}s. * @param httpMethod * the HTTP {@link Method} * @param alsoGet * if true, also methods suporting GET are included, also if * another HTTP method is required. It is intended to be used * for HEAD requests. */ public static void removeNotSupportedHttpMethod( Collection resourceMethods, org.restlet.data.Method httpMethod, boolean alsoGet) { final Iterator methodIter = resourceMethods.iterator(); while (methodIter.hasNext()) { final ResourceMethod resourceMethod = methodIter.next(); if (!resourceMethod.isHttpMethodSupported(httpMethod, alsoGet)) { methodIter.remove(); } } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/JaxRsOutputRepresentation.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/JaxRsOutputRepresentati0000664000175000017500000001112511757206350034500 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriter; import org.restlet.representation.OutputRepresentation; /** * This representation is used to write the Representations with a * {@link javax.ws.rs.ext.MessageBodyWriter}. * * @author Stephan Koops * @param * type of the object to serialize. */ public class JaxRsOutputRepresentation extends OutputRepresentation { private static final Logger LOGGER = Context.getCurrentLogger(); private final MessageBodyWriter mbw; private final T object; private final Type genericType; private final Annotation[] annotations; private final MultivaluedMap httpHeaders; /** * Creates a new JaxRsOutputRepresentation. * * @param object * the object to serialize The generic {@link Type} to convert * to. * @param genericType * The generic {@link Type} to convert to. * @param mediaType * the MediaType of the object. Must be concrete, see * {@link MediaType#isConcrete()}. * @param annotations * the annotations of the artefact to convert to * @param mbw * the MessageBodyWriter which will serialize the object. * @param httpHeaders * the mutable Map of HTTP response headers. */ public JaxRsOutputRepresentation(T object, Type genericType, MediaType mediaType, Annotation[] annotations, MessageBodyWriter mbw, MultivaluedMap httpHeaders) { super(mediaType, mbw.getSize(object, (object != null ? object .getClass() : null), genericType, annotations, mediaType)); if (!mediaType.isConcrete()) { throw new IllegalArgumentException(mediaType + " is not concrete"); } this.genericType = genericType; this.annotations = annotations; this.mbw = mbw; this.httpHeaders = httpHeaders; this.object = object; } /** * @see org.restlet.representation.Representation#write(java.io.OutputStream) */ @Override public void write(OutputStream outputStream) throws IOException { try { this.mbw.writeTo(this.object, this.object.getClass(), this.genericType, this.annotations, getMediaType(), this.httpHeaders, outputStream); } catch (WebApplicationException e) { final String msg = "The Restlet extension for JAX-RS do not support the throwing of WebApplicationException in a MessageBodyWriter."; LOGGER.config(msg); throw e; } catch (UnsupportedOperationException e) { LOGGER.log(Level.CONFIG, "operation not supported", e); throw e; } catch (RuntimeException e) { final String msg = e.getClass().getName() + " while running MessageOutputWriter:"; LOGGER.log(Level.CONFIG, msg, e); throw e; } } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java0000664000175000017500000006460011757206350033224 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import org.restlet.data.Reference; /** * Utility class to encode or check data. * * @author Stephan Koops */ public class EncodeOrCheck { /** A table of hex digits */ private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** * the unreserved characters in URIs */ public static final String UNRESERVED = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-._~"; /** * the gen-delimiter characters in URIs */ public static final String GEN_DELIMITERS = ":/?#[]@"; /** * the sub-delimiter characters in URIs */ public static final String SUB_DELIMITERS = "!$&'()*+,;="; /** * the additional allowed characters for template parameters in URIs. */ public static final String TEMPL_PARAMS = "{}"; /** * the reserved characters in URIs */ public static final String RESERVED = GEN_DELIMITERS + SUB_DELIMITERS; /** * the characters forbidden in a fragment. */ public static final String FRAGMENT_FORBIDDEN; static { final StringBuilder stb = new StringBuilder(); for (char c = 0; c < 256; c++) { final String cc = new String(new char[] { c }); if ((c != '%') && (c != '{') && (c != '}') && !RESERVED.contains(cc) && !UNRESERVED.contains(cc)) { stb.append(c); } } FRAGMENT_FORBIDDEN = stb.toString(); } /** * Checks / encodes all chars of the given char sequence. * * @param string * @param encode * true, if the value should be encoded, or false if not. * @return the enoced string (if it should be encoded) * @throws IllegalArgumentException * if encode is false and at least one character of the * CharSequence is invalid. */ public static String all(CharSequence string, boolean encode) throws IllegalArgumentException { final int length = string.length(); final StringBuilder stb = new StringBuilder(length); for (int i = 0; i < length; i++) { final char c = string.charAt(i); if (c == '%') { processPercent(i, encode, string, stb); } else if (Reference.isValid(c)) { stb.append(c); } else { toHexOrReject(c, stb, encode); } } return stb.toString(); } /** * Checks, if the string contains characters that are reserved in URIs. * * @see RFC 3986, * Section 2.2 * @param uriPart * @param indexForErrMessage * @param errMessName * @throws IllegalArgumentException * if the CharSequence to test contains illegal characters. */ public static void checkForInvalidUriChars(CharSequence uriPart, int indexForErrMessage, String errMessName) throws IllegalArgumentException { final int l = uriPart.length(); boolean inVar = false; for (int i = 0; i < l; i++) { final char c = uriPart.charAt(i); if (inVar) { if (c == '}') { inVar = false; } continue; } switch (c) { case '{': inVar = true; continue; case ':': case '/': case '?': case '#': case '[': case ']': case '@': case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': throw throwIllegalArgExc(indexForErrMessage, errMessName, uriPart, " contains at least one reservec character: " + c + ". They must be encoded."); } if ((c == ' ') || (c < 32) || (c >= 127)) { throw throwIllegalArgExc(indexForErrMessage, errMessName, uriPart, " contains at least one illegal character: " + c + ". They must be encoded."); } } } /** * Appends the given character encoded (if not unreserved) to the * {@link StringBuilder}. * * @param toEncode * the character to encode. * @param stb * the {@link StringBuilder} to append. * @return the number of added chars * @see RFC 3986, * section 2.2 */ static int encode(char toEncode, StringBuilder stb) { // this are all unreserved characters, see RFC 3986 (section 2.2) // http://tools.ietf.org/html/rfc3986#section-2.2 if (((toEncode >= 'A') && (toEncode <= 'Z')) || ((toEncode >= 'a') && (toEncode <= 'z')) || ((toEncode >= '0') && (toEncode <= '9')) || (toEncode == '-') || (toEncode == '.') || (toEncode == '_') || (toEncode == '~')) { stb.append(toEncode); return 1; } toHex(toEncode, stb); return 3; } /** * This methods encodes the given String, but doesn't encode braces. * * @param uriPart * the String to encode * @param allowSemicolon * if true, a ';' is encoded, otherwise an * {@link IllegalArgumentException} is thrown. * @param encodeSlash * if encodeSlash is true, than slashes are also converted, * otherwise not. * @return the encoded String * @throws IllegalArgumentException */ private static String encodeNotBraces(CharSequence uriPart, boolean allowSemicolon, boolean encodeSlash) throws IllegalArgumentException { final StringBuilder stb = new StringBuilder(); final int l = uriPart.length(); for (int i = 0; i < l; i++) { final char c = uriPart.charAt(i); if (c == '{') { i = processTemplVarname(uriPart, i, stb); } else if (c == '%') { processPercent(i, true, uriPart, stb); } else if (c == '}') { throw new IllegalArgumentException("'}' is only allowed as " + "end of a variable name in \"" + uriPart + "\""); } else if (c == ';') { if (allowSemicolon) { encode(c, stb); } else { throw new IllegalArgumentException( "A semicolon is not allowed in a path"); } } else if (!encodeSlash && (c == '/')) { stb.append(c); } else { encode(c, stb); } } return stb.toString(); } /** * @param fragment * the fragment, may contain URI template parameters. Must not be * null. * @return the encoced character sequence (if it should be encoded) * @throws IllegalArgumentException * if encode is false and the fragment contains at least one * invalid character. */ public static CharSequence fragment(CharSequence fragment) throws IllegalArgumentException { // This method is optimized for speed, so it is not very good readable. final StringBuilder stb = new StringBuilder(fragment.length()); final int length = fragment.length(); for (int i = 0; i < length; i++) { final char c = fragment.charAt(i); if (c == '{') { i = processTemplVarname(fragment, i, stb); } else if ((c >= 97) && (c <= 122)) { stb.append(c); } else if ((c >= 63) && (c <= 91)) { stb.append(c); } else if ((c >= 38) && (c <= 59)) { stb.append(c); } else if ((c == '!') || (c == '#') || (c == '$') || (c == '=') || (c == ']') || (c == '_') || (c == '~')) { stb.append(c); } else if (c == '}') { throw new IllegalArgumentException( "'}' is only allowed as end of an template variable name"); } else if (c == '%') { processPercent(i, true, fragment, stb); } else { toHexOrReject(c, stb, true); // allowed is: 033 / 035 / 036 / 038 / 039 / 040 / 041 / 042 / // 043 / // 044 / 045 / 046 / 047 / 48-57 / 058 /059 / 061 / 063 / 064 / // 65-90 / 091 / 093 / 095 / 97-122 / 123 / 125 / 126 } } return stb; } /** * encodes respectively checks a full matrix parameter list. * * @param matrix * matrix parameters to convert or check, may contain URI * template parameters. Must not be null. * @return the encoced character sequence (if it should be encoded) * @throws IllegalArgumentException * if encode is false and at least one character is invalid. */ public static CharSequence fullMatrix(CharSequence matrix) throws IllegalArgumentException { return fullQueryOrMatrix(matrix, ';', "%20", true); } /** * encodes respectively checks a full query. * * @param query * query to convert or check, may contain URI template * parameters. Must not be null. * @param encode * @return the encoced character sequence (if it should be encoded) */ public static CharSequence fullQuery(CharSequence query, boolean encode) { return fullQueryOrMatrix(query, '&', "+", encode); } /** * @param string * @param delimiter * @param spaceReplace * The String to replace a space with ("+" or "%20") * @param encode * @return * @throws IllegalArgumentException */ private static CharSequence fullQueryOrMatrix(CharSequence string, char delimiter, String spaceReplace, boolean encode) throws IllegalArgumentException { final int l = string.length(); final StringBuilder stb = new StringBuilder(l + 6); for (int i = 0; i < l; i++) { final char c = string.charAt(i); if (c == '{') { i = processTemplVarname(string, i, stb); } else if ((c == delimiter) || (c == '=')) { stb.append(c); } else if (c == ' ') { if (encode) { stb.append(spaceReplace); } else { throw new IllegalArgumentException( "A space is not allowed. Switch encode to on to auto encode it."); } } else if (Reference.isUnreserved(c)) { stb.append(c); } else if (c == '}') { throw new IllegalArgumentException("'}' is only allowed as " + "end of a variable name in \"" + string + "\""); } else if (c == '%') { processPercent(i, encode, string, stb); } else { toHexOrReject(c, stb, encode); } } return stb; } /** * Checks, if the host String contains is valid. * * @param host * Could include template variable names. Must not be null, will * throw a NullPointerException. * @return the valid host. * @throws IllegalArgumentException * if the host contains an invalid character. */ public static String host(String host) throws IllegalArgumentException { if (host.length() == 0) { throw new IllegalArgumentException("The host must not be empty"); } final int length = host.length(); // LATER de/encode: host for (int i = 0; i < length; i++) { final char ch = host.charAt(i); if ((ch <= ' ') || (ch >= 127)) { throw new IllegalArgumentException( ("The " + i + ". character is not valid")); } } return host; } /** * Encodes the given string, if encoding is enabled. If encoding is * disabled, the methods checks the validaty of the containing characters. * * @param nameOrValue * the string to encode or check. Must not be null; result are * not defined. May contain URI template parameters. * @param encode * if true, the String is encoded, if false it is checked, if all * chars are valid. * @param nameForMessage * The name for the message * @return the encoced character sequence (if it should be encoded) * @throws IllegalArgumentException * if the given String is null, or at least one char is invalid. */ public static String nameOrValue(Object nameOrValue, boolean encode, String nameForMessage) throws IllegalArgumentException { if (nameOrValue == null) { throw throwIllegalArgExc(Integer.MIN_VALUE, nameForMessage, nameOrValue, " must not be null"); } CharSequence nov; if (nameOrValue instanceof CharSequence) { nov = (CharSequence) nameOrValue; } else { nov = nameOrValue.toString(); } if (encode) { return encodeNotBraces(nov, true, true); } EncodeOrCheck.checkForInvalidUriChars(nov, Integer.MIN_VALUE, nameForMessage); return nov.toString(); } /** * * @param path * @param encode * @return the encoced character sequence (if it should be encoded) */ public static CharSequence pathSegmentsWithMatrix(CharSequence path, boolean encode) { return pathSegmentWithMatrix(path, encode, false); } /** * @param pathSegments * the path to check; must not be null. * @param encode * @return the encoced character sequence (if it should be encoded) * @throws IllegalArgumentException * id encode is false and the path contains an invalid * character. */ public static CharSequence pathSegmentWithMatrix(CharSequence pathSegments, boolean encode) throws IllegalArgumentException { return pathSegmentWithMatrix(pathSegments, encode, true); } /** * @param pathSegments * the path to check; must not be null. * @param encode * @return * @throws IllegalArgumentException * id encode is false and the path contains an invalid * character. */ private static CharSequence pathSegmentWithMatrix( CharSequence pathSegments, boolean encode, boolean encodeSlash) throws IllegalArgumentException { final int l = pathSegments.length(); final StringBuilder stb = new StringBuilder(l + 6); for (int i = 0; i < l; i++) { final char c = pathSegments.charAt(i); if (c == '{') { i = processTemplVarname(pathSegments, i, stb); } else if (c == '%') { processPercent(i, encode, pathSegments, stb); } else if (c == '/') { if (encodeSlash) { toHex('/', stb); } else { stb.append('/'); } } else if (Reference.isUnreserved(c) || Reference.isReserved(c)) { stb.append(c); } else if (c == '}') { throw new IllegalArgumentException("'}' is only allowed " + "as end of a variable name in \"" + pathSegments + "\""); } else { toHexOrReject(c, stb, encode); } } return stb; } /** * This methods encodes the given path, but doesn't encode braces. * * @param path * the path to encode * @return the encoded String * @throws IllegalArgumentException * if the path is not valid */ public static CharSequence pathWithoutMatrix(CharSequence path) throws IllegalArgumentException { return encodeNotBraces(path, false, false); } /** * appends the '%' at the given position i to the given StringBuilder.
* Preconditions (not checked !!): *
    *
  • i > 0
  • *
  • at position i is a '%'.
  • *
* * @param i * the index in the uriPart * @param encode * @param uriPart * @param stb */ static void processPercent(int i, boolean encode, CharSequence uriPart, StringBuilder stb) { if (encode) { toHex('%', stb); return; } if (uriPart.length() <= i + 2) { final CharSequence hexDigits = uriPart.subSequence(i, uriPart .length()); throw new IllegalArgumentException( "A percent encoding must have two charachters, so " + hexDigits + " is not allowed"); } char c1 = uriPart.charAt(i + 1); char c2 = uriPart.charAt(i + 2); if (!(((c1 >= '0') && (c1 <= '9')) || ((c1 >= 'A') && (c1 <= 'F')) || ((c1 >= 'a') && (c1 <= 'f'))) || !(((c2 >= '0') && (c2 <= '9')) || ((c2 >= 'A') && (c2 <= 'F')) || ((c2 >= 'a') && (c2 <= 'f')))) { throw new IllegalArgumentException("The percent encoded char %" + c1 + c2 + " is not valid"); } stb.append('%'); } /** * Reads and checks the template variable name. The starting "{" is at given * position i. * * @param uriPart * the processed part of the uri * @param braceIndex * the current for variable value (position of "{"). The method * do not check, if this is the position of the '{'. * @param stb * the StringBuilder to append the variable name with "{" and "}" * to. Will be changed, also if an error occurs. May be null; * then nothing is appended. * @return the position of the corresponding "}" to assign to the for * variable. * @throws IllegalArgumentException * if the rest of the uriPart contains a '{' or no '}'. */ private static int processTemplVarname(CharSequence uriPart, int braceIndex, StringBuilder stb) throws IllegalArgumentException { final int l = uriPart.length(); if (stb != null) { stb.append('{'); } for (int i = braceIndex + 1; i < l; i++) { final char c = uriPart.charAt(i); if (c == '{') { throw new IllegalArgumentException("A variable must not " + "contain an extra '{' in \"" + uriPart + "\""); } if (stb != null) { stb.append(c); } if (c == '}') { if (i == braceIndex + 1) { throw new IllegalArgumentException( "The template variable name '{}' is not allowed in " + "\"" + uriPart + "\""); } return i; } } throw new IllegalArgumentException("No '}' found after '{' " + "at position " + braceIndex + " of \"" + uriPart + "\""); } /** * Checks, if the String is a valid URI scheme * * @param scheme * the String to check. May contain template variables. * @return the valid scheme * @throws IllegalArgumentException * If the string is not a valid URI scheme. */ public static String scheme(String scheme) throws IllegalArgumentException { if (scheme == null) { throw new IllegalArgumentException("The scheme must not be null"); } final int schemeLength = scheme.length(); if (schemeLength == 0) { throw new IllegalArgumentException( "The scheme must not be an empty String"); } for (int i = 0; i < schemeLength; i++) { final char c = scheme.charAt(i); if (c == '{') { i = processTemplVarname(scheme, i, null); } else if (c == '}') { throw new IllegalArgumentException("The '}' is only allowed " + "as end of a variable name in \"" + scheme + "\""); } else if (((c > 64) && (c <= 90)) || ((c > 92) && (c <= 118))) { continue; } else if ((((c >= '0') && (c <= '9')) || (c == '+') || (c == '-') || (c == '.')) && (i > 0)) { continue; } else { if (i == 0) { throw new IllegalArgumentException( "The first character of a scheme must be an alphabetic character or a template variable name begin with '{'. Scheme is \"" + scheme + "\""); } throw new IllegalArgumentException( "The " + i + ". character of a scheme " + "must be an alphabetic character, a number, a '+', a '-' or a '.'. Template variable names are also allowed. Scheme is \"" + scheme + "\""); } } return scheme; } /** * * @param index * index, starting with zero. * @param errMessName * the name of the string with illegal characters * @param illegalString * the illegal String * @param messageEnd * @return */ private static IllegalArgumentException throwIllegalArgExc(int index, String errMessName, Object illegalString, String messageEnd) { final StringBuilder stb = new StringBuilder(); stb.append("The "); if (index >= 0) { stb.append(index); stb.append(". "); } stb.append(errMessName); stb.append(" ("); stb.append(illegalString); stb.append(")"); stb.append(messageEnd); if (index >= 0) { stb.append(" (index starting with 0)"); } throw new IllegalArgumentException(stb.toString()); } /** * Appends the given character precent-encoded to the {@link StringBuilder}. * Example: ' ' -> "%20% * * @param toEncode * @param stb */ public static void toHex(char toEncode, StringBuilder stb) { stb.append('%'); stb.append(HEX_DIGITS[(toEncode >> 4) & 0xF]); stb.append(HEX_DIGITS[toEncode & 0xF]); } /** * if encode is true, the given char is appended as hex string to the * {@link StringBuilder}. If encode is false, an * {@link IllegalArgumentException} is thrown. * * @param c * @param stb * @param encode * true, if the value should be encoded, or false if not. * @throws IllegalArgumentException */ private static void toHexOrReject(char c, StringBuilder stb, boolean encode) throws IllegalArgumentException { if (encode) { stb.append('%'); stb.append(HEX_DIGITS[(c >> 4) & 0xF]); stb.append(HEX_DIGITS[c & 0xF]); } else { throw new IllegalArgumentException( ("The character " + c + " is not valid")); } } /** * @param userInfo * the URI user-info, may contain URI template parameters * @param encode * @return the encoced character sequence (if it should be encoded) * @throws IllegalArgumentException * if automatic encoding is disabled and the userInfo contains * illegal characters, or if the userInfo is null. */ public static CharSequence userInfo(CharSequence userInfo, boolean encode) throws IllegalArgumentException { final int length = userInfo.length(); final StringBuilder stb = new StringBuilder(length); for (int i = 0; i < length; i++) { final char c = userInfo.charAt(i); if (c == '{') { i = processTemplVarname(userInfo, i, stb); } else if (c == '%') { processPercent(i, encode, userInfo, stb); } else if (Reference.isUnreserved(c) || Reference.isSubDelimiter(c)) { stb.append(c); } else if (c == '}') { throw new IllegalArgumentException("'}' is only allowed " + "as end of a variable name in \"" + userInfo + "\""); } else if (c == ':') { stb.append(c); } else { toHexOrReject(c, stb, encode); } } return stb; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/MatchingResult.java0000664000175000017500000000525711757206350033524 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.Map; import javax.ws.rs.Path; /** * Wraps a result of a matching of a concrete path against a path pattern. * * @author Stephan Koops */ public class MatchingResult { private final String matched; private final Map variables; private final RemainingPath finalCapturingGroup; /** * Creates a new MatchingResult * * @param matched * The matched uri part * @param variables * @param finalCapturingGroup */ public MatchingResult(String matched, Map variables, String finalCapturingGroup) { this.matched = matched; this.variables = variables; this.finalCapturingGroup = new RemainingPath(finalCapturingGroup); } /** * Returns the final capturing group. Starts ever with a slash. * * @return Returns the final capturing group. */ public RemainingPath getFinalCapturingGroup() { return this.finalCapturingGroup; } /** * Returns the matched uri path. * * @return Returns the matched uri path. */ public String getMatched() { return this.matched; } /** * Returns the variables found in the given @{@link Path} * * @return Returns the variables found in the given @{@link Path} */ public Map getVariables() { return this.variables; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/SortedOrderedBag.java0000664000175000017500000001357411757206350033753 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.util; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; /** * A sorted ordered bag allows multiple elements, where the {@link Comparator} * says that they are equal. In this case an element added later than another * element is put behind the first added element. * * @author Stephan Koops * @param */ public class SortedOrderedBag implements Collection { private static final class Compar> implements Comparator { /***/ public Compar() { } public int compare(A o1, A o2) { return o1.compareTo(o2); } } @SuppressWarnings("rawtypes") private static final Comparator DEFAULT_COMPARATOR = new Compar(); private final Comparator comp; private final LinkedList elements = new LinkedList(); /** * Creates a new sorted ordered bag. */ @SuppressWarnings("unchecked") public SortedOrderedBag() { this.comp = (Comparator) DEFAULT_COMPARATOR; } /** * Creates a new sorted ordered bag. * * @param coll */ @SuppressWarnings("unchecked") public SortedOrderedBag(Collection coll) { this.comp = (Comparator) DEFAULT_COMPARATOR; this.addAll(coll); } /** * Creates a new sorted ordered bag. * * @param comp * the {@link Comparator} to use */ public SortedOrderedBag(Comparator comp) { this.comp = comp; } /** * Creates a new sorted ordered bag. * * @param comp * the {@link Comparator} to use * @param coll */ public SortedOrderedBag(Comparator comp, Collection coll) { this.comp = comp; this.addAll(coll); } /** * uses bubble sort * * @see java.util.Collection#add(java.lang.Object) */ public boolean add(E add) { if (this.elements.isEmpty()) { this.elements.add(add); return true; } final ListIterator listIter; listIter = this.elements.listIterator(this.elements.size()); while (listIter.hasPrevious()) { E current = listIter.previous(); if (comp.compare(add, current) >= 0) { listIter.next(); listIter.add(add); return true; } } this.elements.addFirst(add); return true; } /** * @see java.util.Collection#addAll(java.util.Collection) */ public boolean addAll(Collection c) { for (E e : c) this.add(e); return true; } /** * @see java.util.Collection#clear() */ public void clear() { this.elements.clear(); } /** * @see java.util.Collection#contains(java.lang.Object) */ public boolean contains(Object o) { return this.elements.contains(o); } /** * @see java.util.Collection#containsAll(java.util.Collection) */ public boolean containsAll(Collection c) { return this.elements.containsAll(c); } /** * @see java.util.Collection#isEmpty() */ public boolean isEmpty() { return this.elements.isEmpty(); } /** * @param index * @return the element at the given position * @see java.util.List#get(int) */ public E get(int index) { return this.elements.get(index); } /** * @see java.util.Collection#iterator() */ public Iterator iterator() { return this.elements.iterator(); } /** * @see java.util.Collection#remove(java.lang.Object) */ public boolean remove(Object o) { return this.elements.remove(o); } /** * @see java.util.Collection#removeAll(java.util.Collection) */ public boolean removeAll(Collection c) { return this.elements.removeAll(c); } /** * @see java.util.Collection#retainAll(java.util.Collection) */ public boolean retainAll(Collection c) { return this.elements.retainAll(c); } /** * @see java.util.Collection#size() */ public int size() { return this.elements.size(); } /** * @see java.util.Collection#toArray() */ public Object[] toArray() { return this.elements.toArray(); } /** * @see java.util.Collection#toArray(T[]) */ public T[] toArray(T[] a) { return this.elements.toArray(a); } @Override public String toString() { return this.elements.toString(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/0000775000175000017500000000000011757206350027672 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/UriBuilderImpl.java0000664000175000017500000000376411757206350033437 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import javax.ws.rs.core.UriBuilder; import org.restlet.ext.jaxrs.AbstractUriBuilder; /** * Implementation of interface {@link UriBuilder}. * * @author Stephan Koops * @see UriBuilder */ public class UriBuilderImpl extends AbstractUriBuilder { /** * Create a copy of the UriBuilder preserving its state. This is a more * efficient means of creating a copy than constructing a new UriBuilder * from a URI returned by the {@link #build} method. * * @return a copy of the UriBuilder * @see javax.ws.rs.core.UriBuilder#clone() */ @Override public UriBuilder clone() { final UriBuilderImpl uriBuilder = new UriBuilderImpl(); copyInto(uriBuilder); return uriBuilder; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedExtendedUriInfo.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedExtended0000664000175000017500000000716411757206350034344 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import javax.ws.rs.core.UriInfo; import org.restlet.ext.jaxrs.ExtendedUriBuilder; import org.restlet.ext.jaxrs.ExtendedUriInfo; /** * A ThreadLocalizedUriInfo is used to inject, if a {@link UriInfo} is required * to inject. It must be new instantiated for every place to inject. * * @author Stephan Koops * @see UriInfo * @see ThreadLocalizedContext */ public class ThreadLocalizedExtendedUriInfo extends ThreadLocalizedUriInfo implements ExtendedUriInfo { /** * @param tlContext */ public ThreadLocalizedExtendedUriInfo(ThreadLocalizedContext tlContext) { super(tlContext); } /** * Get the absolute path of the request in the form of an * {@link ExtendedUriBuilder}. This includes everything preceding the path * (host, port etc) but excludes query parameters. It also includes the * extension of the current request. * * @return an ExtendedUriBuilder initialized with the absolute path of the * request and an extension according to the current chosen media * type. * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see UriInfo#getAbsolutePathBuilder() */ @Override public ExtendedUriBuilder getAbsolutePathBuilder() { return getCallContext().getAbsolutePathBuilderExtended(); } /** * Get the base URI of the application in the form of a UriBuilder. It also * includes the extension of the current request. * * @return a UriBuilder initialized with the base URI of the application and * an extension according to the current chosen media type. * @see UriInfo#getBaseUriBuilder() */ @Override public ExtendedUriBuilder getBaseUriBuilder() { return getCallContext().getBaseUriBuilderExtended(); } /** * Get the absolute request URI in the form of a UriBuilder. It also * includes the extension of the current request. * * @return a UriBuilder initialized with the absolute request URI and an * extension according to the current chosen media type * @throws java.lang.IllegalStateException * if called outside the scope of a request */ @Override public ExtendedUriBuilder getRequestUriBuilder() { return getCallContext().getRequestUriBuilderExtended(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/MultivaluedMapImpl.java0000664000175000017500000001050111757206350034305 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import org.restlet.ext.jaxrs.internal.util.Util; /** * Implementation of the JAX-RS interface {@link MultivaluedMap}. * * @author Stephan Koops * * @param * @param */ public class MultivaluedMapImpl extends HashMap> implements MultivaluedMap { private static final long serialVersionUID = 6228280442855580961L; /** * Creates a new empty {@link MultivaluedMapImpl} */ public MultivaluedMapImpl() { } /** * Creates a copy of the given {@link MultivaluedMap}. * * @param old * the {@link MultivaluedMap} to copy. The values are not cloned. */ public MultivaluedMapImpl(MultivaluedMap old) { for (final Map.Entry> entry : old.entrySet()) { final List value = entry.getValue(); put(entry.getKey(), new LinkedList(value)); } } /** * Add a value to the current list of values for the supplied key. * * @param key * the key * @param value * the value to be added. * @see MultivaluedMap#add(Object, Object) */ public void add(K key, V value) { List list = get(key); if (list == null) { list = new LinkedList(); put(key, list); } list.add(value); } /** * Creates a clone of this map. The contained values are not cloned. * * @return A copy of this map */ @Override public MultivaluedMapImpl clone() { return new MultivaluedMapImpl(this); } /** * A shortcut to get the first value of the supplied key. * * @param key * the key * @return the first value for the specified key or null if the key is not * in the map. * @see MultivaluedMap#getFirst(Object) */ public V getFirst(K key) { final List list = get(key); if ((list == null) || list.isEmpty()) { return null; } return Util.getFirstElement(list); } /** * A shortcut to get the last value of the supplied key. * * @param key * the key * @return the last value for the specified key or null if the key is not in * the map. */ public V getLast(K key) { final List list = get(key); if ((list == null) || list.isEmpty()) { return null; } return list.get(0); } /** * Set the key's value to be a one item list consisting of the supplied * value. Any existing values will be replaced. * * @param key * the key * @param value * the single value of the key * @see MultivaluedMap#putSingle(Object, Object) */ public void putSingle(K key, V value) { final List list = new LinkedList(); list.add(value); put(key, list); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ResponseImpl.java0000664000175000017500000000612611757206350033162 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; /** * Implementation of {@link Response}. * * @author Stephan Koops */ public class ResponseImpl extends Response { private Object entity; private MultivaluedMap metadata; private int status = 200; /** * Creates a new Response Instance with status code 200 */ public ResponseImpl() { } /** * Creates a new Response Instance. * * @param status * the status code for the new response. */ public ResponseImpl(int status) { this.status = status; } @Override public ResponseImpl clone() { final ResponseImpl newResp = new ResponseImpl(this.status); newResp.entity = this.entity; newResp.metadata = new MultivaluedMapImpl(this.metadata); return newResp; } /** * @see javax.ws.rs.core.Response#getEntity() */ @Override public Object getEntity() { return this.entity; } /** * Get metadata associated with the response as a map. The returned map may * be subsequently modified by the JAX-RS runtime. * * @return response metadata as a map * @see javax.ws.rs.core.Response#getMetadata() */ @Override public MultivaluedMap getMetadata() { // TODO use HeaderDelegate to serialize if (this.metadata == null) { this.metadata = new MultivaluedMapImpl(); } return this.metadata; } /** * @see javax.ws.rs.core.Response#getStatus() */ @Override public int getStatus() { return this.status; } void setEntity(Object entity) { this.entity = entity; } void setStatus(int status) { this.status = status; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ResponseBuilderImpl.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ResponseBuilderImpl.jav0000664000175000017500000004127111757206350034330 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.net.URI; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.data.Dimension; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.Util; /** * Implementation of the {@link ResponseBuilder}. * * @author Stephan Koops */ public class ResponseBuilderImpl extends ResponseBuilder { private MultivaluedMap metadata; private Map newCookies; private ResponseImpl response; /** * Creates a new Response Builder */ public ResponseBuilderImpl() { } /** * Create a Response instance from the current ResponseBuilder. The builder * is reset to a blank state equivalent to calling the ok method. * * @return a Response instance * @see javax.ws.rs.core.Response.ResponseBuilder#build() */ @Override public Response build() { if (this.response == null) { return new ResponseImpl(); } final Response r = this.response; if (this.newCookies != null) { final MultivaluedMap metadata = getMetadata(); for (final NewCookie cookie : this.newCookies.values()) { metadata.add(HttpHeaders.SET_COOKIE, cookie); } this.newCookies = null; } this.response = null; this.metadata = null; return r; } /** * Set the cache control data on the ResponseBuilder. * * @param cacheControl * the cache control directives * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#cacheControl(javax.ws.rs.core.CacheControl) */ @Override public ResponseBuilder cacheControl(CacheControl cacheControl) { if (cacheControl == null) { getMetadata().remove(HttpHeaders.CACHE_CONTROL); } else { getMetadata().putSingle(HttpHeaders.CACHE_CONTROL, cacheControl); } return this; } /** * @see javax.ws.rs.core.Response.ResponseBuilder#clone() */ @Override public ResponseBuilderImpl clone() { final ResponseBuilderImpl newRb = new ResponseBuilderImpl(); newRb.response = this.response.clone(); newRb.newCookies = new HashMap(this.newCookies); // metadatas are read from the response. return newRb; } /** * Set the content location on the ResponseBuilder. * * * @param location * the content location * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#contentLocation(java.net.URI) */ @Override public ResponseBuilder contentLocation(URI location) { if (location == null) { getMetadata().remove(HttpHeaders.CONTENT_LOCATION); } else { getMetadata().putSingle(HttpHeaders.CONTENT_LOCATION, location.toASCIIString()); } return this; } /** * Add cookies to the ResponseBuilder. If more than one cookie with the same * is supplied, later ones overwrite earlier ones. * * @param cookies * new cookies that will accompany the response. * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#cookie(javax.ws.rs.core.NewCookie) */ @Override public ResponseBuilder cookie(NewCookie... cookies) { final Map newCookies = getNewCookies(); for (final NewCookie cookie : cookies) { if (cookie != null) { newCookies.put(cookie.getName(), cookie); } } return this; } /** * Set the language on the ResponseBuilder.
* This method is not required by the JAX-RS API bu is used from * {@link #variant(Variant)}. * * @param encoding * the encoding of the response entity * @return the updated ResponseBuilder */ public ResponseBuilder encoding(String encoding) { if (encoding == null) { getMetadata().remove(HttpHeaders.CONTENT_ENCODING); } else { getMetadata().putSingle(HttpHeaders.CONTENT_ENCODING, encoding); } return this; } /** * Set the entity on the ResponseBuilder. * * * @param entity * the response entity * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#entity(java.lang.Object) */ @Override public ResponseBuilder entity(Object entity) { getResponse().setEntity(entity); return this; } /** * @see javax.ws.rs.core.Response.ResponseBuilder#expires(java.util.Date) */ @Override public ResponseBuilder expires(Date expires) { if (expires == null) { getMetadata().remove(HttpHeaders.EXPIRES); } else { getMetadata().putSingle(HttpHeaders.EXPIRES, expires); } return this; } MultivaluedMap getMetadata() { if (this.metadata == null) { this.metadata = getResponse().getMetadata(); } return this.metadata; } Map getNewCookies() { if (this.newCookies == null) { this.newCookies = new HashMap(); } return this.newCookies; } ResponseImpl getResponse() { if (this.response == null) { this.response = new ResponseImpl(); } return this.response; } /** * Add a header to the ResponseBuilder. * * @param name * the name of the header * @param value * the value of the header, the header will be serialized using * its toString method. If null then all current headers of the * same name will be removed. * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#header(String, Object) */ @Override public ResponseBuilder header(String name, Object value) { if (name == null) { throw new IllegalArgumentException( "You must give a name of the header"); } if (name.equals(HttpHeaders.SET_COOKIE)) { if (value == null) { this.newCookies.clear(); } else if (value instanceof NewCookie) { cookie((NewCookie) value); } else if (value instanceof Cookie) { cookie(new NewCookie((Cookie) value)); } else { cookie(NewCookie.valueOf(value.toString())); } } else { if (value == null) { getMetadata().remove(name); } else { getMetadata().add(name, value); } } return this; } /** * Set the language on the ResponseBuilder. * * * @param language * the language of the response entity * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#language(java.lang.String) */ @Override public ResponseBuilder language(Locale language) { if (language == null) { getMetadata().remove(HttpHeaders.CONTENT_LANGUAGE); } else { getMetadata().putSingle(HttpHeaders.CONTENT_LANGUAGE, language); } return this; } /** * Set the language on the ResponseBuilder. * * * @param language * the language of the response entity * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#language(java.lang.String) */ @Override public ResponseBuilder language(String language) { if (language == null) { getMetadata().remove(HttpHeaders.CONTENT_LANGUAGE); } else { getMetadata().putSingle(HttpHeaders.CONTENT_LANGUAGE, language); } return this; } /** * Set the last modified date on the ResponseBuilder. * * * @param lastModified * the last modified date * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#lastModified(java.util.Date) */ @Override public ResponseBuilder lastModified(Date lastModified) { if (lastModified == null) { getMetadata().remove(HttpHeaders.LAST_MODIFIED); } else { getMetadata().putSingle(HttpHeaders.LAST_MODIFIED, lastModified); } return this; } /** * Set the location on the ResponseBuilder. * * * @param location * the location * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#location(java.net.URI) */ @Override public ResponseBuilder location(URI location) { if (location == null) { getMetadata().remove(HttpHeaders.LOCATION); } else { getMetadata().putSingle(HttpHeaders.LOCATION, location); } return this; } /** * Set the status on the ResponseBuilder. * * @param status * the response status * @return the updated ResponseBuilder * @throws IllegalArgumentException * if status is less than 100 or greater than 599. * @see javax.ws.rs.core.Response.ResponseBuilder#status(int) */ @Override public ResponseBuilder status(int status) { if (status < 100 || status >= 600) throw new IllegalArgumentException( "The status must be between 100 (inclusive) and 600 (exclusive), but is " + status); if (this.response == null) { this.response = new ResponseImpl(status); } else { this.response.setStatus(status); } return this; } /** * Set the entity tag on the ResponseBuilder. * * @param tag * the entity tag * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#tag(javax.ws.rs.core.EntityTag) */ @Override public ResponseBuilder tag(EntityTag tag) { if (tag == null) { getMetadata().remove(HttpHeaders.ETAG); } else { getMetadata().putSingle(HttpHeaders.ETAG, tag); } return this; } /** * Set a strong entity tag on the ResponseBuilder. This is a shortcut for * tag(new EntityTag(value)). * * @param tag * the string content of a strong entity tag. The JAX-RS runtime * will quote the supplied value when creating the header. * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#tag(java.lang.String) */ @Override public ResponseBuilder tag(String tag) { if (tag == null) { tag((EntityTag) null); } else { tag(new EntityTag(tag, false)); } return this; } /** * Set the response media type on the ResponseBuilder. * * @see javax.ws.rs.core.Response.ResponseBuilder#type(javax.ws.rs.core.MediaType) */ @Override public ResponseBuilder type(MediaType type) { if (type == null) { getMetadata().remove(HttpHeaders.CONTENT_TYPE); } else { getMetadata().putSingle(HttpHeaders.CONTENT_TYPE, type); } return this; } /** * Set the response media type on the ResponseBuilder. * * @param type * the media type of the response entity * @return the updated ResponseBuilder * @throws IllegalArgumentException * if type cannot be parsed * @see javax.ws.rs.core.Response.ResponseBuilder#type(java.lang.String) */ @Override public ResponseBuilder type(String type) { if (type == null) { return type((MediaType) null); } return type(MediaType.valueOf(type)); } /** * Set representation metadata on the ResponseBuilder. * * @param variant * metadata of the response entity * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#variant(javax.ws.rs.core.Variant) */ @Override public ResponseBuilder variant(Variant variant) { if (variant == null) { this.language((String) null); this.encoding(null); this.type((MediaType) null); } else { this.language(variant.getLanguage()); this.encoding(variant.getEncoding()); this.type(variant.getMediaType()); } return this; } /** * Add a Vary header that lists the available variants. * * @param variants * a list of available representation variants, a null value will * remove an existing value for vary. * @return the updated ResponseBuilder * @see javax.ws.rs.core.Response.ResponseBuilder#variants(java.util.List) */ @Override public ResponseBuilder variants(List variants) { if (variants == null) { getMetadata().remove(HttpHeaders.VARY); return this; } // NICE add entity header with further information // give links, use extension mapping. Was macht Restlet da schon? final Set encodings = new HashSet(); final Set languages = new HashSet(); final Set mediaTypes = new HashSet(); final Set charsets = new HashSet(); for (final Variant variant : variants) { final String encoding = variant.getEncoding(); if (encoding != null) { encodings.add(encoding); } final Locale language = variant.getLanguage(); if (language != null) { languages.add(language); } final MediaType mediaType = variant.getMediaType(); if (mediaType != null) { mediaTypes.add(Converter.getMediaTypeWithoutParams(mediaType)); } final String charset = Converter.getCharset(mediaType); if (charset != null) { charsets.add(charset); } } Set dimensions; dimensions = org.restlet.Response.getCurrent().getDimensions(); if (encodings.size() > 1) { dimensions.add(Dimension.ENCODING); } if (languages.size() > 1) { dimensions.add(Dimension.LANGUAGE); } if (mediaTypes.size() > 1) { dimensions.add(Dimension.MEDIA_TYPE); } if (charsets.size() > 1) { dimensions.add(Dimension.CHARACTER_SET); } final String vary = Util.formatDimensions(dimensions); if (vary != null) { getMetadata().putSingle(HttpHeaders.VARY, vary); } return this; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/CallContext.java0000664000175000017500000013256411757206350032770 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.net.URI; import java.net.URISyntaxException; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.MatrixParam; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.Application; import org.restlet.Request; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.CharacterSet; import org.restlet.data.Dimension; import org.restlet.data.Form; import org.restlet.data.Language; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.data.Tag; import org.restlet.ext.jaxrs.ExtendedUriBuilder; import org.restlet.ext.jaxrs.RoleChecker; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.EmptyIterator; import org.restlet.ext.jaxrs.internal.util.SecurityUtil; import org.restlet.ext.jaxrs.internal.util.SortedMetadata; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.representation.Representation; import org.restlet.security.Role; /** * Contains all request specific data of the interfaces injectable for @ * {@link Context}. Implementation of the JAX-RS interfaces {@link HttpHeaders}, * {@link UriInfo}, {@link javax.ws.rs.core.Request} and {@link SecurityContext} * .
* This class is not required to be thread safe, because it is only used for one * client request in one thread at the same time. * * @author Stephan Koops */ @SuppressWarnings("deprecation") public class CallContext implements javax.ws.rs.core.Request, HttpHeaders, SecurityContext { /** * Iterator to return the values for a matrix parameter. * * @author Stephan Koops */ private static class MatrixParamEncIter implements Iterator { /** Iterates over the matrix parameters of one path segment */ private Iterator>> matrixParamIter; private final String mpName; private Iterator mpValueIter; private String nextMpValue; private final Iterator pathSegmentIter; MatrixParamEncIter(String mpName, List pathSegmentsEnc) { this.pathSegmentIter = pathSegmentsEnc.iterator(); this.mpName = mpName; } /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if (this.nextMpValue != null) { return true; } while ((this.mpValueIter != null) && (this.mpValueIter.hasNext())) { this.nextMpValue = this.mpValueIter.next(); return true; } while ((this.matrixParamIter != null) && (matrixParamIter.hasNext())) { final Map.Entry> entry = matrixParamIter .next(); if (entry.getKey().equals(this.mpName)) { this.mpValueIter = entry.getValue().iterator(); return hasNext(); } } while (this.pathSegmentIter.hasNext()) { this.matrixParamIter = this.pathSegmentIter.next() .getMatrixParameters().entrySet().iterator(); return hasNext(); } return false; } /** * @see java.util.Iterator#next() */ public String next() { if (!hasNext()) { throw new NoSuchElementException(); } final String nextMpValue = this.nextMpValue; this.nextMpValue = null; return nextMpValue; } /** * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException("unmodifiable"); } } private static final int STATUS_PREC_FAILED = Status.CLIENT_ERROR_PRECONDITION_FAILED .getCode(); private static final Logger unexpectedLogger = org.restlet.Context .getCurrentLogger(); /** * the unmodifiable List of accepted languages. Lazy initialization by * getter. * * @see #getAcceptableLanguages() */ private List acceptedLanguages; /** * the unmodifiable List of accepted {@link MediaType}s. Lazy initialization * by getter. * * @see #getAcceptableMediaTypes() */ private List acceptedMediaTypes; private final SortedMetadata accMediaTypes; /** contains the current value of the ancestor resources */ private final LinkedList matchedResources = new LinkedList(); /** contains the current value of the ancestor resource URIs */ private final LinkedList matchedURIs = new LinkedList(); private String baseUri; private Map cookies; private Locale language; private MediaType mediaType; private MultivaluedMap pathParametersDecoded; /** is null, if no templateParameters given on creation */ private MultivaluedMap pathParametersEncoded; private List pathSegmentsDecoded = null; private List pathSegmentsEncoded = null; private MultivaluedMap queryParametersDecoded; private MultivaluedMap queryParametersEncoded; private boolean readOnly = false; private final Reference referenceCut; private final Reference referenceOriginal; private final Request request; private UnmodifiableMultivaluedMap requestHeaders; private final org.restlet.Response response; private final RoleChecker roleChecker; /** * * @param request * The Restlet request to wrap. Must not be null. * @param response * The Restlet response * @param roleChecker * Optional, can be null, see {@link RoleChecker}. */ public CallContext(Request request, org.restlet.Response response, RoleChecker roleChecker) { if (request == null) { throw new IllegalArgumentException( "The Restlet Request must not be null"); } if (response == null) { throw new IllegalArgumentException( "The Restlet Response must not be null"); } final Reference referenceCut = request.getResourceRef(); if (referenceCut == null) { throw new IllegalArgumentException( "The request reference must not be null"); } if (referenceCut.getBaseRef() == null) { throw new IllegalArgumentException( "The request reference must contains a baseRef"); } final Reference referenceOriginal = request.getOriginalRef(); if (referenceOriginal == null) { throw new IllegalArgumentException( "The request.originalRef must not be null"); } final Reference appRootRef = request.getRootRef(); if (appRootRef == null) { throw new IllegalArgumentException( "The root reference of the request must not be null"); } referenceOriginal.setBaseRef(appRootRef); this.referenceCut = referenceCut; this.referenceOriginal = referenceOriginal; this.readOnly = false; this.request = request; this.response = response; this.roleChecker = roleChecker; this.accMediaTypes = SortedMetadata.getForMediaTypes(request .getClientInfo().getAcceptedMediaTypes()); } /** * also useable after {@link #setReadOnly()} * * @param resourceObject * @param newUriPart * @throws URISyntaxException * @see UriInfo#getMatchedResources() * @see UriInfo#getMatchedURIs() */ public void addForMatched(Object resourceObject, String newUriPart) { if (resourceObject == null) { throw new IllegalArgumentException( "The resource object must not be null"); } if (newUriPart == null) { throw new IllegalArgumentException( "The new URI part must not be null"); } final StringBuilder newUri; if (this.matchedURIs.isEmpty()) newUri = new StringBuilder(); else newUri = new StringBuilder(this.matchedURIs.getFirst()); if (newUriPart.length() == 0 || newUriPart.charAt(0) != '/') { newUri.append('/'); } newUri.append(newUriPart); this.matchedResources.addFirst(resourceObject); this.matchedURIs.addFirst(newUri.toString()); } /** * @param varName * @param varValue */ public void addPathParamsEnc(String varName, String varValue) { checkChangeable(); interalGetPathParamsEncoded().add(varName, varValue); } /** * Checks, if this object is changeable. If not, a * {@link IllegalStateException} is thrown. * * @throws IllegalStateException */ protected void checkChangeable() throws IllegalStateException { if (!isChangeable()) { throw new IllegalStateException( "The CallContext is no longer changeable"); } } /** * Creates an unmodifiable List of {@link PathSegment}s. * * @param decode * indicates, if the values should be decoded or not * @return */ private List createPathSegments(boolean decode) { List segmentsEnc; segmentsEnc = this.referenceOriginal.getRelativeRef().getSegments(); final int l = segmentsEnc.size(); final List pathSegments = new ArrayList(l); for (int i = 0; i < l; i++) { final String segmentEnc = segmentsEnc.get(i); pathSegments.add(new PathSegmentImpl(segmentEnc, decode, i)); } return Collections.unmodifiableList(pathSegments); } /** * @param ref * @return * @throws IllegalArgumentException */ private UriBuilder createUriBuilder(Reference ref) { // NICE what happens, if the Reference is invalid for the UriBuilder? UriBuilder b = new UriBuilderImpl(); return fillUriBuilder(ref, b); } /** * @param ref * @param b * @return * @throws IllegalArgumentException */ private UriBuilder fillUriBuilder(Reference ref, final UriBuilder b) throws IllegalArgumentException { b.scheme(ref.getScheme(false)); b.userInfo(ref.getUserInfo(false)); b.host(ref.getHostDomain(false)); b.port(ref.getHostPort()); b.path(ref.getPath(false)); b.replaceQuery(ref.getQuery(false)); b.fragment(ref.getFragment(false)); return b; } private ExtendedUriBuilder createExtendedUriBuilder(Reference ref) { ExtendedUriBuilder b = new ExtendedUriBuilder(); fillUriBuilder(ref, b); String extension = ref.getExtensions(); b.extension(extension); return b; } @Override public boolean equals(Object anotherObject) { if (this == anotherObject) { return true; } if (!(anotherObject instanceof UriInfo)) { return false; } final UriInfo other = (UriInfo) anotherObject; if (!getBaseUri().equals(other.getBaseUri())) { return false; } if (!this.getPathSegments().equals(other.getPathSegments())) { return false; } if (!Util.equals(this.getPathParameters(), other.getPathParameters())) { return false; } return true; } /** * Evaluate request preconditions based on the passed in value. * * @param lastModified * a date that specifies the modification date of the resource * @return null if the preconditions are met or a ResponseBuilder set with * the appropriate status if the preconditions are not met. * @throws java.lang.IllegalArgumentException * if lastModified is null * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see #evaluatePreconditions(Date, EntityTag) * @see javax.ws.rs.core.Request#evaluatePreconditions(java.util.Date) */ public ResponseBuilder evaluatePreconditions(Date lastModified) { if (lastModified == null) { throw new IllegalArgumentException( "The last modification date must not be null"); } return evaluatePreconditionsInternal(lastModified, null); } /** * Evaluates the preconditions of the current request against the given last * modified date and / or the given entity tag. This method does not check, * if the arguments are not null. * * @param lastModified * @param entityTag * @return * @see Request#evaluateConditions(Tag, Date) */ private ResponseBuilder evaluatePreconditionsInternal( final Date lastModified, final EntityTag entityTag) { Status status = this.request.getConditions().getStatus( this.request.getMethod(), true, Converter.toRestletTag(entityTag), lastModified); if (status == null) return null; if (status.equals(Status.REDIRECTION_NOT_MODIFIED)) { final ResponseBuilder rb = Response.notModified(); rb.lastModified(lastModified); rb.tag(entityTag); return rb; } return Response.status(STATUS_PREC_FAILED); } /** * Evaluate request preconditions based on the passed in value. * * @param lastModified * a date that specifies the modification date of the resource * @param eTag * an ETag for the current state of the resource * @return null if the preconditions are met or a ResponseBuilder set with * the appropriate status if the preconditions are not met. A * returned ResponseBuilder will include an ETag header set with the * value of eTag. * @throws java.lang.IllegalArgumentException * if lastModified or eTag is null * @throws java.lang.IllegalStateException * if called outside the scope of a request * * @see javax.ws.rs.core.Request#evaluatePreconditions(java.util.Date, * javax.ws.rs.core.EntityTag) * @see RFC * 2616, section 10.3.5: Status 304: Not Modified * @see RFC * 2616, section 10.4.13: Status 412: Precondition Failed * @see RFC 2616, * section 13.3: (Caching) Validation Model * @see RFC 2616, * section 14.24: Header "If-Match" * @see RFC 2616, * section 14.25: Header "If-Modified-Since" * @see RFC 2616, * section 14.26: Header "If-None-Match" * @see RFC 2616, * section 14.28: Header "If-Unmodified-Since" */ public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag entityTag) { if (lastModified == null) { throw new IllegalArgumentException( "The last modification date must not be null"); } if (entityTag == null) { throw new IllegalArgumentException( "The entity tag must not be null"); } return evaluatePreconditionsInternal(lastModified, entityTag); } /** * Evaluate request preconditions based on the passed in value. * * @param eTag * an ETag for the current state of the resource * @return null if the preconditions are met or a ResponseBuilder set with * the appropriate status if the preconditions are not met. A * returned ResponseBuilder will include an ETag header set with the * value of eTag. * @throws java.lang.IllegalArgumentException * if eTag is null * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see #evaluatePreconditions(Date, EntityTag) * @see javax.ws.rs.core.Request#evaluatePreconditions(javax.ws.rs.core.EntityTag) */ public ResponseBuilder evaluatePreconditions(EntityTag entityTag) { if (entityTag == null) { throw new IllegalArgumentException( "The entity tag must not be null"); } return evaluatePreconditionsInternal(null, entityTag); } /** * Get the absolute path of the request. This includes everything preceding * the path (host, port etc) but excludes query parameters and fragment. * This is a shortcut for * uriInfo.getBase().resolve(uriInfo.getPath()). * * @return the absolute path of the request * @see UriInfo#getAbsolutePath() */ public URI getAbsolutePath() { try { return new URI(this.referenceOriginal.toString(false, false)); } catch (URISyntaxException e) { throw wrapUriSyntaxExc(e, unexpectedLogger, "Could not create URI"); } } /** * Get the absolute path of the request in the form of a UriBuilder. This * includes everything preceding the path (host, port etc) but excludes * query parameters and fragment. * * @return a UriBuilder initialized with the absolute path of the request. * @see UriInfo#getAbsolutePathBuilder() */ public UriBuilder getAbsolutePathBuilder() { return createUriBuilder(this.referenceOriginal); } ExtendedUriBuilder getAbsolutePathBuilderExtended() { return createExtendedUriBuilder(this.referenceOriginal); } /** * @see javax.ws.rs.core.HttpHeaders#getAcceptableLanguages() */ public List getAcceptableLanguages() { if (this.acceptedLanguages == null) { final SortedMetadata accLangages = SortedMetadata .getForLanguages(this.request.getClientInfo() .getAcceptedLanguages()); final List accLangs = new ArrayList(); for (final Language language : accLangages) { accLangs.add(Converter.toLocale(language)); } this.acceptedLanguages = Collections.unmodifiableList(accLangs); } return this.acceptedLanguages; } /** * For use from JAX-RS interface. * * @see HttpHeaders#getAcceptableMediaTypes() */ public List getAcceptableMediaTypes() { if (this.acceptedMediaTypes == null) { final List accMediaTypes = new ArrayList(); for (final org.restlet.data.MediaType mediaType : this.accMediaTypes) { accMediaTypes.add(Converter.toJaxRsMediaType(mediaType)); } this.acceptedMediaTypes = Collections .unmodifiableList(accMediaTypes); } return this.acceptedMediaTypes; } /** * Returns the accepted media types as Restlet * {@link org.restlet.data.MediaType}s. * * @return the accepted {@link org.restlet.data.MediaType}s. */ public SortedMetadata getAccMediaTypes() { return this.accMediaTypes; } /** * current state of the matchedResources * * @see javax.ws.rs.core.UriInfo#getMatchedResources() */ List getMatchedResources() { return this.matchedResources; } /** * current state of the matchedURIs * * @see javax.ws.rs.core.UriInfo#getMatchedURIs() */ List getMatchedURIs() { return this.matchedURIs; } /** * Returns the string value of the authentication scheme used to protect the * resource. If the resource is not authenticated, null is returned. * * Values are the same as the CGI variable AUTH_TYPE * * @return one of the static members BASIC_AUTH, FORM_AUTH, * CLIENT_CERT_AUTH, DIGEST_AUTH (suitable for == comparison) or the * container-specific string indicating the authentication scheme, * or null if the request was not authenticated. * @see SecurityContext#getAuthenticationScheme() */ public String getAuthenticationScheme() { if (SecurityUtil.isSslClientCertAuth(this.request)) { return SecurityContext.CLIENT_CERT_AUTH; } ChallengeResponse challengeResponse = request.getChallengeResponse(); if (challengeResponse == null) { return null; } if (!request.getClientInfo().isAuthenticated()) { return null; } final ChallengeScheme authScheme = challengeResponse.getScheme(); if (authScheme == null) { return null; } if (authScheme.equals(ChallengeScheme.HTTP_BASIC)) { return SecurityContext.BASIC_AUTH; } if (authScheme.equals(ChallengeScheme.HTTP_DIGEST)) { return SecurityContext.DIGEST_AUTH; } // if (authScheme.equals(ChallengeScheme.HTTPS_CLIENT_CERT)) // return SecurityContext.CLIENT_CERT_AUTH; // if (authScheme.equals(ChallengeScheme.HTTP_SERVLET_FORM)) // return SecurityContext.FORM_AUTH; return authScheme.getName(); } /** * Get the base URI of the application. URIs of resource beans are all * relative to this base URI. * * @return the base URI of the application * @see UriInfo#getBaseUri() */ public URI getBaseUri() { try { return new URI(getBaseUriStr()); } catch (URISyntaxException e) { throw wrapUriSyntaxExc(e, unexpectedLogger, "Could not create URI"); } } /** * Get the absolute path of the request in the form of a UriBuilder. This * includes everything preceding the path (host, port etc) but excludes * query parameters and fragment. * * @return a UriBuilder initialized with the absolute path of the request. * @see UriInfo#getAbsolutePathBuilder() * @see UriInfo#getBaseUriBuilder() */ public UriBuilder getBaseUriBuilder() { return UriBuilder.fromUri(getBaseUriStr()); } ExtendedUriBuilder getBaseUriBuilderExtended() { ExtendedUriBuilder uriBuilder = ExtendedUriBuilder .fromUri(getBaseUriStr()); ExtendedUriBuilder originalRef = createExtendedUriBuilder(this.referenceOriginal); uriBuilder.extension(originalRef.getExtension()); return uriBuilder; } private String getBaseUriStr() { if (this.baseUri == null) { final Reference baseRef = this.referenceCut.getBaseRef(); if (baseRef != null) { this.baseUri = baseRef.toString(false, false); } } return this.baseUri; } /** * Get the request URI extension. The returned string includes any * extensions remove during request pre-processing for the purposes of * URI-based content negotiation. E.g. if the request URI was: * *
     * http://example.com/resource.xml.en
     * 
* * this method would return "xml.en" even if an applications implementation * of {@link ApplicationConfig#getMediaTypeMappings()} returned a map that * included "xml" as a key * * @return the request URI extension * @see javax.ws.rs.core.UriInfo#getConnegExtension() */ public String getConnegExtension() { return referenceOriginal.getExtensions(); } /** * Get any cookies that accompanied the request. * * @return a map of cookie name (String) to Cookie. * @see HttpHeaders#getCookies() */ public Map getCookies() { if (this.cookies == null) { final Map cookies = new HashMap(); for (final org.restlet.data.Cookie rc : this.request.getCookies()) { final Cookie cookie = Converter.toJaxRsCookie(rc); cookies.put(cookie.getName(), cookie); } this.cookies = Collections.unmodifiableMap(cookies); } return this.cookies; } /** * @see HttpHeaders#getLanguage() */ public Locale getLanguage() { if (this.language == null) { final Representation entity = this.request.getEntity(); if (entity == null) { return null; } final List languages = entity.getLanguages(); if (languages.isEmpty()) { return null; } this.language = Converter.toLocale(Util.getFirstElement(languages)); } return this.language; } /** * Returns the last matrix parameter with the given name; leaves it encoded. * * @param matrixParamAnnot * @return the last matrix parameter with the given name; leaves it encoded. * @see #matrixParamEncIter(MatrixParam) */ public String getLastMatrixParamEnc(MatrixParam matrixParamAnnot) { final String mpName = matrixParamAnnot.value(); final List pathSegments = getPathSegments(false); for (int i = pathSegments.size() - 1; i >= 0; i--) { final PathSegment pathSegment = pathSegments.get(i); final List mpValues = pathSegment.getMatrixParameters() .get(mpName); if ((mpValues != null) && !mpValues.isEmpty()) { final String result = Util.getLastElement(mpValues); if (result == null) { return ""; } return result; } } return null; } /** * @param annotation * @return the last encoded path param with the given name * @see #pathParamEncIter(PathParam) */ public String getLastPathParamEnc(PathParam annotation) { final String varName = annotation.value(); final List values = interalGetPathParamsEncoded().get(varName); if ((values == null) || values.isEmpty()) { return null; } return Util.getLastElement(values); } /** * @param pathParam * @return . */ public String getLastPathSegmentEnc(PathParam pathParam) { pathParam.annotationType(); // TODO CallContext.getLastPathSegmentEnc(PathParam) throw new NotYetImplementedException(); } /** * Get the media type of the request entity * * @return the media type or null if there is no request entity. * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see HttpHeaders#getMediaType() */ public MediaType getMediaType() { if (this.mediaType == null) { org.restlet.data.MediaType rmt = request.getEntity().getMediaType(); CharacterSet rCharSet = request.getEntity().getCharacterSet(); this.mediaType = Converter.toJaxRsMediaType(rmt, rCharSet); } return this.mediaType; } /** * @see javax.ws.rs.core.Request#getMethod() */ public String getMethod() { return this.request.getMethod().getName(); } /** * Get the path of the current request relative to the base URI as a string. * All sequences of escaped octets are decoded, equivalent to * getPath(true). * * @return the relative URI path. * @see UriInfo#getPath() */ public String getPath() { return getPath(true); } /** * Get the path of the current request relative to the base URI as a string. * * @param decode * controls whether sequences of escaped octets are decoded * (true) or not (false). * @return the relative URI path. * @see UriInfo#getPath(boolean) */ public String getPath(boolean decode) { final String path = this.referenceOriginal.getRelativeRef().toString( true, true); if (!decode) { return path; } return Reference.decode(path); } /** * Get the values of any embedded URI template parameters. All sequences of * escaped octets are decoded, equivalent to * getTemplateParameters(true). * * @return an unmodifiable map of parameter names and values * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see javax.ws.rs.Path * @see UriInfo#getPathParameters() */ public MultivaluedMap getPathParameters() { if (this.pathParametersDecoded == null) { final MultivaluedMapImpl pathParamsDec = new MultivaluedMapImpl(); for (final Map.Entry> entryEnc : interalGetPathParamsEncoded() .entrySet()) { final String keyDec = Reference.decode(entryEnc.getKey()); final List valuesEnc = entryEnc.getValue(); List valuesDec = new ArrayList(valuesEnc.size()); for (final String valueEnc : valuesEnc) { valuesDec.add(Reference.decode(valueEnc)); } pathParamsDec.put(keyDec, valuesDec); } UnmodifiableMultivaluedMap ppd; ppd = UnmodifiableMultivaluedMap.get(pathParamsDec, false); if (isChangeable()) { return ppd; } this.pathParametersDecoded = ppd; } return this.pathParametersDecoded; } /** * Get the values of any embedded URI template parameters. * * @param decode * controls whether sequences of escaped octets are decoded * (true) or not (false). * @return an unmodifiable map of parameter names and values * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see javax.ws.rs.Path * @see UriInfo#getPathParameters(boolean) */ public MultivaluedMap getPathParameters(boolean decode) { if (decode) { return getPathParameters(); } return UnmodifiableMultivaluedMap.get(interalGetPathParamsEncoded()); } /** * Get the path of the current request relative to the base URI as a list of * {@link PathSegment}. This method is useful when the path needs to be * parsed, particularly when matrix parameters may be present in the path. * All sequences of escaped octets are decoded, equivalent to * getPathSegments(true). * * @return an unmodifiable list of {@link PathSegment}. The matrix parameter * map of each path segment is also unmodifiable. * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see PathSegment * @see UriInfo#getPathSegments() */ public List getPathSegments() { return getPathSegments(true); } /** * Get the path of the current request relative to the base URI as a list of * {@link PathSegment}. This method is useful when the path needs to be * parsed, particularly when matrix parameters may be present in the path. * * @param decode * controls whether sequences of escaped octets are decoded * (true) or not (false). * @return an unmodifiable list of {@link PathSegment}. The matrix parameter * map of each path segment is also unmodifiable. * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see PathSegment * @see UriInfo#getPathSegments(boolean) */ public List getPathSegments(boolean decode) { if (decode) { if (this.pathSegmentsDecoded == null) { this.pathSegmentsDecoded = createPathSegments(true); } return this.pathSegmentsDecoded; } if (this.pathSegmentsEncoded == null) { this.pathSegmentsEncoded = createPathSegments(false); } return this.pathSegmentsEncoded; } /** * Get the URI query parameters of the current request. All sequences of * escaped octets are decoded, equivalent to * getQueryParameters(true). * * @return an unmodifiable map of query parameter names and values * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see UriInfo#getQueryParameters() */ public MultivaluedMap getQueryParameters() { if (this.queryParametersDecoded == null) { this.queryParametersDecoded = UnmodifiableMultivaluedMap .getFromForm(this.referenceOriginal.getQueryAsForm(), false); } return this.queryParametersDecoded; } /** * Get the URI query parameters of the current request. * * @param decode * controls whether sequences of escaped octets in parameter * names and values are decoded (true) or not (false). * @return an unmodifiable map of query parameter names and values * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see UriInfo#getQueryParameters(boolean) */ public MultivaluedMap getQueryParameters(boolean decode) { if (decode) { return getQueryParameters(); } if (this.queryParametersEncoded == null) { final Form queryForm = Converter .toFormEncoded(this.referenceOriginal.getQuery()); this.queryParametersEncoded = UnmodifiableMultivaluedMap .getFromForm(queryForm, false); } return this.queryParametersEncoded; } /** * Returns the Restlet {@link org.restlet.Request} * * @return the Restlet {@link org.restlet.Request} */ public Request getRequest() { return this.request; } /** * @see javax.ws.rs.core.HttpHeaders#getRequestHeader(java.lang.String) */ public List getRequestHeader(String headerName) { String[] values; values = Util.getHttpHeaders(this.request).getValuesArray(headerName); return Collections.unmodifiableList(Arrays.asList(values)); } /** * @see HttpHeaders#getRequestHeaders() */ public MultivaluedMap getRequestHeaders() { if (this.requestHeaders == null) { this.requestHeaders = UnmodifiableMultivaluedMap.getFromForm(Util .getHttpHeaders(this.request), false); } return this.requestHeaders; } /** * @return the absolute request URI * @see UriInfo#getRequestUri() */ public URI getRequestUri() { try { return new URI(this.referenceOriginal.toString(true, true)); } catch (URISyntaxException e) { throw wrapUriSyntaxExc(e, unexpectedLogger, "Could not create URI"); } } /** * Get the absolute request URI in the form of a UriBuilder. * * @return a UriBuilder initialized with the absolute request URI. * @see UriInfo#getRequestUriBuilder() */ public UriBuilder getRequestUriBuilder() { return UriBuilder.fromUri(getRequestUri()); } ExtendedUriBuilder getRequestUriBuilderExtended() { return ExtendedUriBuilder.fromUri(getRequestUri()); } /** * Returns the Restlet {@link org.restlet.Response} * * @return the Restlet {@link org.restlet.Response} */ public org.restlet.Response getResponse() { return this.response; } /** * Returns a java.security.Principal object containing the name * of the current authenticated user. If the user has not been * authenticated, the method returns null. * * @return a java.security.Principal containing the name of the * user making this request; null if the user has not been * authenticated * @see SecurityContext#getUserPrincipal() */ public Principal getUserPrincipal() { Principal foundPrincipal = (request.getChallengeResponse() == null) ? null : request.getChallengeResponse().getPrincipal(); if (foundPrincipal != null) return foundPrincipal; return SecurityUtil.getSslClientCertPrincipal(this.request); } @Override public int hashCode() { return this.getBaseUriStr().hashCode() ^ this.getPathSegments().hashCode() ^ this.getPathParameters().hashCode(); } /** * @return the pathParametersEncoded */ protected MultivaluedMap interalGetPathParamsEncoded() { if (this.pathParametersEncoded == null) { this.pathParametersEncoded = new MultivaluedMapImpl(); } return this.pathParametersEncoded; } protected boolean isChangeable() { return !this.readOnly; } /** * Returns a boolean indicating whether this request was made using a secure * channel, such as HTTPS. * * @return true if the request was made using a secure channel, * false otherwise * @see SecurityContext#isSecure() */ public boolean isSecure() { return this.request.isConfidential(); } /** * Returns a boolean indicating whether the authenticated user is included * in the specified logical "role". If the user has not been authenticated, * the method returns false. * * @param roleName * a String specifying the name of the role * @return a boolean indicating whether the user making the * request belongs to a given role; false if the user * has not been authenticated * @see SecurityContext#isUserInRole(String) */ public boolean isUserInRole(String roleName) { if (roleChecker != null) { return roleChecker.isInRole(getUserPrincipal(), roleName); } Role role = Application.getCurrent().getRole(roleName); return (role != null) && this.request.getClientInfo().getRoles().contains(role); } /** * @param matrixParamAnnot * @return . * @see #getLastMatrixParamEnc(MatrixParam) */ public Iterator matrixParamEncIter(MatrixParam matrixParamAnnot) { final String mpName = matrixParamAnnot.value(); return new MatrixParamEncIter(mpName, getPathSegments(false)); } /** * @param pathParamAnnot * @return . * @see #getLastPathParamEnc(PathParam) */ public Iterator pathParamEncIter(PathParam pathParamAnnot) { // LATER perhaps this method could be removed, if it is not needed for // @PathParam(..) PathSegment final String ppName = pathParamAnnot.value(); List pathParamValues; pathParamValues = interalGetPathParamsEncoded().get(ppName); if (pathParamValues == null) { return EmptyIterator.get(); } return pathParamValues.iterator(); } /** * @param pathParam * @return . */ public Iterator pathSegementEncIter(PathParam pathParam) { pathParam.annotationType(); // TODO CallContext.pathSegementEncIter(PathParam) throw new NotYetImplementedException(); } /** * Select the representation variant that best matches the request. More * explicit variants are chosen ahead of less explicit ones. A vary header * is computed from the supplied list and automatically added to the * response. * * @param variants * a list of Variant that describe all of the available * representation variants. * @return the variant that best matches the request. * @see Variant.VariantListBuilder * @throws IllegalArgumentException * if variants is null or empty. * @see javax.ws.rs.core.Request#selectVariant(List) */ public Variant selectVariant(List variants) throws IllegalArgumentException { if ((variants == null) || variants.isEmpty()) { throw new IllegalArgumentException(); } final List restletVariants = Converter .toRestletVariants(variants); final org.restlet.representation.Variant bestRestlVar = this.request .getClientInfo().getPreferredVariant(restletVariants, null); final Variant bestVariant = Converter.toJaxRsVariant(bestRestlVar); final Set dimensions = this.response.getDimensions(); if (bestRestlVar.getCharacterSet() != null) { dimensions.add(Dimension.CHARACTER_SET); } if (bestRestlVar.getEncodings() != null) { dimensions.add(Dimension.ENCODING); } if (bestRestlVar.getLanguages() != null) { dimensions.add(Dimension.LANGUAGE); } if (bestRestlVar.getMediaType() != null) { dimensions.add(Dimension.MEDIA_TYPE); } // NICE add also to JAX-RS-Response, which is possibly not yet // generated. return bestVariant; } /** * Sets the Context to be read only. As from now changes are not allowed. * This method is intended to be used by {@link CallContext#setReadOnly()}. * Ignored by {@link #addForMatched(Object, String)}. */ public void setReadOnly() { this.readOnly = true; } @Override public String toString() { return this.referenceOriginal.toString(true, false); } /** * This method throws an {@link WebApplicationException} for Exceptions * where is no planned handling. Logs the exception (warn {@link Level}). * * @param exc * the catched URISyntaxException * @param unexpectedLogger * the unexpectedLogger to log the messade * @param logMessage * the message to log. * @return Will never return anything, because the generated * WebApplicationException will be thrown. You an formally throw the * returned exception (e.g. in a catch block). So the compiler is * sure, that the method will be left here. * @throws WebApplicationException * contains the given {@link Exception} */ private WebApplicationException wrapUriSyntaxExc(URISyntaxException exc, Logger logger, String logMessage) throws WebApplicationException { logger.log(Level.WARNING, logMessage, exc); exc.printStackTrace(); throw new WebApplicationException(exc, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedUriInfo.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedUriInfo.0000664000175000017500000001627311757206350034236 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.net.URI; import java.util.List; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.restlet.ext.jaxrs.ExtendedUriInfo; /** * A ThreadLocalizedUriInfo is used to inject, if a {@link UriInfo} is required * to inject. It must be new instantiated for every place to inject. * * @author Stephan Koops * @see UriInfo * @see ThreadLocalizedContext */ public class ThreadLocalizedUriInfo implements UriInfo { private final ThreadLocal matchedInfos = new ThreadLocal(); private final ThreadLocalizedContext tlContext; /** * Creates a new ThreadLocalizedUriInfo * * @param tlContext */ public ThreadLocalizedUriInfo(ThreadLocalizedContext tlContext) { this.tlContext = tlContext; } /** * @return the MatchedInfo with the current data from the * {@link CallContext}. * @throws IllegalStateException * if no CallContext could be loaded. */ private MatchedInfo createAncestorInfo() throws IllegalStateException { final CallContext callContext = getCallContext(); return new MatchedInfo(callContext.getMatchedURIs(), callContext.getMatchedResources()); } private MatchedInfo get() throws IllegalStateException { MatchedInfo matchedInfo = this.matchedInfos.get(); if (matchedInfo != null) { return matchedInfo; } matchedInfo = createAncestorInfo(); this.matchedInfos.set(matchedInfo); return matchedInfo; } /** * @see JaxRsUriInfo#getAbsolutePath() * @see UriInfo#getAbsolutePath() */ public URI getAbsolutePath() { return getCallContext().getAbsolutePath(); } /** * @see JaxRsUriInfo#getAbsolutePathBuilder() * @see UriInfo#getAbsolutePathBuilder() * @see ExtendedUriInfo#getAbsolutePathBuilder() */ public UriBuilder getAbsolutePathBuilder() { return getCallContext().getAbsolutePathBuilder(); } /** * @see JaxRsUriInfo#getMatchedResources() * @see UriInfo#getMatchedResources() */ public List getMatchedResources() { return get().getResources(); } /** * @see UriInfo#getMatchedURIs() */ public List getMatchedURIs() { return get().getUris(true); } /** * @see JaxRsUriInfo#getAncestorResourceURIs(boolean) * @see UriInfo#getAncestorResourceURIs(boolean) */ public List getMatchedURIs(boolean decode) { return get().getUris(decode); } /** * @see JaxRsUriInfo#getBaseUri() * @see UriInfo#getBaseUri() */ public URI getBaseUri() { return getCallContext().getBaseUri(); } /** * @see JaxRsUriInfo#getBaseUriBuilder() * @see UriInfo#getBaseUriBuilder() */ public UriBuilder getBaseUriBuilder() { return getCallContext().getBaseUriBuilder(); } protected CallContext getCallContext() throws IllegalStateException { return this.tlContext.get(); } /** * @see JaxRsUriInfo#getPath() * @see UriInfo#getPath() */ public String getPath() { return getCallContext().getPath(); } /** * @see JaxRsUriInfo#getPath(boolean) * @see UriInfo#getPath(boolean) */ public String getPath(boolean decode) { return getCallContext().getPath(decode); } /** * @see JaxRsUriInfo#getPathParameters() * @see UriInfo#getPathParameters() */ public MultivaluedMap getPathParameters() { return getCallContext().getPathParameters(); } /** * @see JaxRsUriInfo#getPathParameters(boolean) * @see UriInfo#getPathParameters(boolean) */ public MultivaluedMap getPathParameters(boolean decode) { return getCallContext().getPathParameters(decode); } /** * @see JaxRsUriInfo#getPathSegments() * @see UriInfo#getPathSegments() */ public List getPathSegments() { return getCallContext().getPathSegments(); } /** * @see JaxRsUriInfo#getPathSegments(boolean) * @see UriInfo#getPathSegments(boolean) */ public List getPathSegments(boolean decode) { return getCallContext().getPathSegments(decode); } /** * @see JaxRsUriInfo#getQueryParameters() * @see UriInfo#getQueryParameters() */ public MultivaluedMap getQueryParameters() { return getCallContext().getQueryParameters(); } /** * @see JaxRsUriInfo#getQueryParameters(boolean) * @see UriInfo#getQueryParameters(boolean) */ public MultivaluedMap getQueryParameters(boolean decode) { return getCallContext().getQueryParameters(decode); } /** * @see JaxRsUriInfo#getRequestUri() * @see UriInfo#getRequestUri() */ public URI getRequestUri() { return getCallContext().getRequestUri(); } /** * @see JaxRsUriInfo#getRequestUriBuilder() * @see UriInfo#getRequestUriBuilder() */ public UriBuilder getRequestUriBuilder() { return getCallContext().getRequestUriBuilder(); } /** * Removes the MatchedInfo for the current thread. */ public void reset() { this.matchedInfos.remove(); } /** * Saves the current state of the ancestorResource(URI)s for the current * thread. * * @param saveState * if true, the current state is save for the current thread from * the current {@link CallContext}; if false (for singeltons), * the saved object for the current thread is removed. */ public void saveStateForCurrentThread(boolean saveState) { if (saveState) { this.matchedInfos.set(createAncestorInfo()); } else { reset(); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedContext.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedContext.0000664000175000017500000002036611757206350034305 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.security.Principal; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Request; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Providers; /** * This class is used for thread local injection into providers and resources. * * @author Stephan Koops * @see Request * @see HttpHeaders * @see SecurityContext * @see Providers * @see ContextResolver * @see CallContext */ public class ThreadLocalizedContext implements Request, HttpHeaders, SecurityContext { /** * The key of the {@link CallContext} in the * {@link org.restlet.Request} attributes. */ private static final String CALLCONTEXT_KEY = "org.restlet.ext.jaxrs.CallContext"; /** * @param lastModified * @return null if the preconditions are met or a ResponseBuilder set with * the appropriate status if the preconditions are not met. * @see CallContext#evaluatePreconditions(java.util.Date) * @see Request#evaluatePreconditions(Date) */ public ResponseBuilder evaluatePreconditions(Date lastModified) { return get().evaluatePreconditions(lastModified); } /** * @param lastModified * @param entityTag * @return {@inheritDoc} * @see CallContext#evaluatePreconditions(java.util.Date, * javax.ws.rs.core.EntityTag) * @see Request#evaluatePreconditions(Date, EntityTag) */ public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag entityTag) { return get().evaluatePreconditions(lastModified, entityTag); } /** * @param entityTag * @return null if the preconditions are met or a ResponseBuilder set with * the appropriate status if the preconditions are not met. A * returned ResponseBuilder will include an ETag header set with the * value of eTag. * @see CallContext#evaluatePreconditions(javax.ws.rs.core.EntityTag) * @see Request#evaluatePreconditions(EntityTag) */ public ResponseBuilder evaluatePreconditions(EntityTag entityTag) { return get().evaluatePreconditions(entityTag); } /** * Returns the wrapped CallContext for the current Thread. * * @return the wrapped CallContext for the current Thread. Never returns * null. * @throws IllegalStateException * if no {@link CallContext} was given for the current thread. * If this occurs, their is a bug in this JAX-RS implementation. * @see #set(CallContext) */ public CallContext get() throws IllegalStateException { final Object callContext = getRequestAttributes().get(CALLCONTEXT_KEY); if (callContext == null) { throw new IllegalStateException("No CallContext given until now"); } return (CallContext) callContext; } /** * @see HttpHeaders#getAcceptableLanguages() */ public List getAcceptableLanguages() { return get().getAcceptableLanguages(); } /** * @see CallContext#getAcceptableMediaTypes() * @see HttpHeaders#getAcceptableMediaTypes() */ public List getAcceptableMediaTypes() { return get().getAcceptableMediaTypes(); } /** * @see CallContext#getAuthenticationScheme() * @see SecurityContext#getAuthenticationScheme() */ public String getAuthenticationScheme() { return get().getAuthenticationScheme(); } /** * @see CallContext#getCookies() * @see HttpHeaders#getCookies() */ public Map getCookies() { return get().getCookies(); } /** * @see CallContext#getLanguage() * @see HttpHeaders#getLanguage() */ public Locale getLanguage() { return get().getLanguage(); } /** * @see CallContext#getMediaType() * @see HttpHeaders#getMediaType() */ public MediaType getMediaType() { return get().getMediaType(); } /** * @see javax.ws.rs.core.Request#getFormParameters() */ public String getMethod() { return get().getMethod(); } /** * Returns the attributes of the current Restlet * {@link org.restlet.Request}. * * @return the attributes of the current Restlet Request, but never null */ private Map getRequestAttributes() { return org.restlet.Request.getCurrent().getAttributes(); } /** * @see CallContext#getRequestHeader(java.lang.String) * @see HttpHeaders#getRequestHeader(String) */ public List getRequestHeader(String name) { return get().getRequestHeader(name); } /** * @see CallContext#getRequestHeaders() * @see HttpHeaders#getRequestHeaders() */ public MultivaluedMap getRequestHeaders() { return get().getRequestHeaders(); } /** * @see CallContext#getUserPrincipal() * @see SecurityContext#getUserPrincipal() */ public Principal getUserPrincipal() { return get().getUserPrincipal(); } /** * @see CallContext#isSecure() * @see SecurityContext#isSecure() */ public boolean isSecure() { return get().isSecure(); } /** * @param role * @see CallContext#isUserInRole(java.lang.String) * @see SecurityContext#isUserInRole(String) */ public boolean isUserInRole(String role) { return get().isUserInRole(role); } /** * @param variants * @throws IllegalArgumentException * @see CallContext#selectVariant(java.util.List) * @see Request#selectVariant(List) */ public Variant selectVariant(List variants) throws IllegalArgumentException { return get().selectVariant(variants); } /** * Sets the CallContext for the current thread. You MUST set a CallContext * here before you can get it by {@link #get()}. * * @param callContext * The CallContext for the current request; must not be null. * @see #reset() * @see #get() * @throws IllegalArgumentException * if null was given. */ public void set(CallContext callContext) throws IllegalArgumentException { if (callContext == null) { throw new IllegalArgumentException( "You must give a CallContext here. null is not allowed"); } getRequestAttributes().put(CALLCONTEXT_KEY, callContext); } /** * @return . * @see UriInfo#getPathSegments() */ public List getPathSegments() { return get().getPathSegments(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/PathSegmentImpl.java0000664000175000017500000002103411757206350033576 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.io.IOException; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import org.restlet.data.Reference; import org.restlet.ext.jaxrs.internal.util.EncodeOrCheck; import org.restlet.ext.jaxrs.internal.util.Util; /** * The implementation of the JAX-RS interface {@link PathSegment} * * @author Stephan Koops */ public class PathSegmentImpl implements PathSegment { /** * @param matrParamString * The string to parse the matrix parameters * @param decoding * if true, than the keys and values are decoded, if false, than * not. * @param encodeAndCheckWhenNotDecode * If decode is false and encodeAndCheckWhenNotDecode is true, * than an IllegalArgumentException is thrown, when a parameter * contains illegal characters, if false nothing will checked. If * decode is true, this value is ignored. * @return Method is public for testing, otherwise it would be package * visible. */ public static MultivaluedMapImpl parseMatrixParams( String matrParamString, boolean decoding) { final MultivaluedMapImpl matrixParameters = new MultivaluedMapImpl(); if (matrParamString == null) { return matrixParameters; } final String[] paramsEncSpl = matrParamString.split(";"); for (final String matrParamEnc : paramsEncSpl) { final int posEquSign = matrParamEnc.indexOf('='); String nameEnc; String valueEnc; if (posEquSign <= 0) { nameEnc = matrParamEnc; valueEnc = ""; } else { nameEnc = matrParamEnc.substring(0, posEquSign); valueEnc = matrParamEnc.substring(posEquSign + 1); } if ((nameEnc.length() == 0) && (valueEnc == null)) { continue; } String name; String value; if (decoding) { name = Reference.decode(nameEnc); value = Reference.decode(valueEnc); } else { name = nameEnc; value = valueEnc; } matrixParameters.add(name, value); } return matrixParameters; } private final boolean decode; /** * The matrix parameters. Encoded or decoded, depends on {@link #decode}. */ private volatile MultivaluedMap matrixParameters; /** * the encoded matrix parameters, as given in constructor. */ private final String matrParamEncoded; /** encoded or decoded, depends on {@link #decode} */ private final String path; /** * @param segmentEnc * Segment with matrix parameter. The segment is encoded. * @param decode * true, if the path and the marix parameters should be decoded. * @param indexForErrMess * If the user adds more than one path segment with one call, you * can give the index for an error message here. Set -1, if none. * See * {@link EncodeOrCheck#checkForInvalidUriChars(String, int, String)} * @throws IllegalArgumentException * the segment is null, if decode and encode is both true */ public PathSegmentImpl(String segmentEnc, boolean decode, int indexForErrMess) throws IllegalArgumentException { if (segmentEnc == null) { if (indexForErrMess >= 0) { throw new IllegalArgumentException("The " + indexForErrMess + ". segment must not be null"); } throw new IllegalArgumentException("The segment must not be null"); } this.decode = decode; final int indexOfSemic = segmentEnc.indexOf(';'); String path; if (indexOfSemic >= 0) { path = segmentEnc.substring(0, indexOfSemic); this.matrParamEncoded = segmentEnc.substring(indexOfSemic + 1); } else { path = segmentEnc; this.matrParamEncoded = null; } this.path = decode ? Reference.decode(path) : path; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof PathSegmentImpl)) { return false; } final PathSegment other = (PathSegment) object; if (!getPath().equals(other.getPath())) { return false; } if (!getMatrixParameters().equals(other.getMatrixParameters())) { return false; } return true; } /** * Get a map of the decoded (or encoded?) matrix parameters associated with * the path segment * * @return the map of matrix parameters. Never returns null. */ public MultivaluedMap getMatrixParameters() { if (this.matrixParameters == null) { this.matrixParameters = parseMatrixParams(this.matrParamEncoded, this.decode); } return this.matrixParameters; } /** * @return the path segment * @see PathSegment#getPath() */ public String getPath() { return this.path; } @Override public int hashCode() { return this.path.hashCode() ^ getMatrixParameters().hashCode(); } /** * Appends this PathSegment to the given Appendable * * @param stb * StringBuilder or other Appendable to append this PathSegment. * @param convertBraces * if true, all braces are converted, if false then not, see * {@link Util#append(Appendable, CharSequence, boolean)}. * @throws IOException * if the Appendable has a problem. */ public void toAppendable(Appendable stb, boolean convertBraces) throws IOException { Util.append(stb, this.path, convertBraces); final MultivaluedMap matrixParams = getMatrixParameters(); for (final Map.Entry> mpe : matrixParams .entrySet()) { for (final String value : mpe.getValue()) { stb.append(';'); Util.append(stb, mpe.getKey(), convertBraces); stb.append('='); Util.append(stb, value, convertBraces); } } } @Override public String toString() { final StringBuilder stb = new StringBuilder(); toStringBuilder(stb, false); return stb.toString(); } /** * Appends this PathSegment to the given StringBuilder * * @param stb * the StrinBuilder to append * @param convertBraces * if true, than conatined braces will be encoded, see * {@link Util#append(Appendable, CharSequence, boolean)}. */ public void toStringBuilder(StringBuilder stb, boolean convertBraces) { try { toAppendable(stb, convertBraces); } catch (IOException e) { throw new RuntimeException( "IOException in StringBuilder; that is normally not possible"); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/VariantListBuilderImpl.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/VariantListBuilderImpl.0000664000175000017500000001534111757206350034270 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Variant.VariantListBuilder; import org.restlet.ext.jaxrs.internal.util.OneElementIterator; import org.restlet.ext.jaxrs.internal.util.Util; /** * Concrete implementation of abstract class {@link VariantListBuilder} * * @author Stephan Koops */ public class VariantListBuilderImpl extends VariantListBuilder { /** * Creates an Iterator over the elements of the list. If the list is null or * empty, an Iterator with exact one element is returned: null. * * @param * @param list * @return an {@link Iterator} with at least one element (perhaps null). * never null. */ private static Iterator createIterator(List list) { if ((list == null) || list.isEmpty()) { return new OneElementIterator(null); } return list.iterator(); } private List mediaTypes; private List languages; private List encodings; private List variants; /** * Creates a new VariantListBuilder */ public VariantListBuilderImpl() { } /** * Add the current combination of metadata to the list of supported * variants, after this method is called the current combination of metadata * is emptied. If more than one value is supplied for one or more of the * variant properties then a variant will be generated for each possible * combination. E.g. in the following list would have four * members: *

* *

     * List<Variant> list = VariantListBuilder.newInstance().languages("en","fr")
     *   .encodings("zip", "identity").add().build()
     * 
* * * @return the updated builder * @see javax.ws.rs.core.Variant.VariantListBuilder#add() */ @Override public VariantListBuilder add() { buildVariants(); return this; } /** * Build a list of representation variants from the current state of the * builder. After this method is called the builder is reset to an empty * state. * * @return a list of representation variants * @see javax.ws.rs.core.Variant.VariantListBuilder#build() */ @Override public List build() { if (Util.isNotEmpty(this.encodings) || Util.isNotEmpty(this.languages) || Util.isNotEmpty(this.mediaTypes)) { buildVariants(); } List variants = this.variants; this.variants = null; return variants; } private void buildVariants() { Iterator mediaTypeIter = createIterator(this.mediaTypes); if (this.variants == null) { this.variants = new ArrayList(); } while (mediaTypeIter.hasNext()) { MediaType mediaType = mediaTypeIter.next(); Iterator languageIter = createIterator(this.languages); while (languageIter.hasNext()) { Locale language = languageIter.next(); Iterator encodingIter = createIterator(this.encodings); while (encodingIter.hasNext()) { String encoding = encodingIter.next(); Variant variant = new Variant(mediaType, language, encoding); this.variants.add(variant); } } } this.encodings.clear(); this.languages.clear(); this.mediaTypes.clear(); } /** * Set the encoding[s] for this variant. * * @param encodings * the available encodings * @return the updated builder * @see javax.ws.rs.core.Variant.VariantListBuilder#encodings(java.lang.String[]) */ @Override public VariantListBuilder encodings(String... encodings) { if (this.encodings == null) { this.encodings = new ArrayList(); } for (String encoding : encodings) { this.encodings.add(encoding); } return this; } /** * Set the language[s] for this variant. * * @param languages * the available languages * @return the updated builder * @see javax.ws.rs.core.Variant.VariantListBuilder#languages(java.lang.String[]) */ @Override public VariantListBuilder languages(Locale... languages) { if (this.languages == null) { this.languages = new ArrayList(); } for (Locale language : languages) { this.languages.add(language); } return this; } /** * Set the media type[s] for this variant. * * @param mediaTypes * the available mediaTypes. If specific charsets are supported * they should be included as parameters of the respective media * type. * @return the updated builder * @see javax.ws.rs.core.Variant.VariantListBuilder#mediaTypes(javax.ws.rs.core.MediaType[]) */ @Override public VariantListBuilder mediaTypes(MediaType... mediaTypes) { if (this.mediaTypes == null) { this.mediaTypes = new ArrayList(); } for (MediaType mediaType : mediaTypes) { this.mediaTypes.add(mediaType); } return this; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/UnmodifiableMultivaluedMap.javarestlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/UnmodifiableMultivalued0000664000175000017500000002004111757206350034424 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.core.MultivaluedMap; import org.restlet.data.Form; import org.restlet.data.Parameter; /** * An unmodifiable {@link MultivaluedMap}. * * @author Stephan Koops * * @param * @param */ public class UnmodifiableMultivaluedMap implements MultivaluedMap { /** * Creates a MultiValuedMap of unmodifiable Lists. */ private static MultivaluedMapImpl copyForm(Form form, boolean caseInsensitive) { final MultivaluedMapImpl mmap = new MultivaluedMapImpl(); for (final Parameter param : form) { final String key = caseInsensitive ? param.getName().toLowerCase() : param.getName(); mmap.add(key, param.getValue()); } for (final Map.Entry> entry : mmap.entrySet()) { final List unmodifiable = Collections .unmodifiableList(entry.getValue()); mmap.put(entry.getKey(), unmodifiable); } return mmap; } /** * Returns an UnmodifiableMultivaluedMap, that contains the content of the * given {@link MultivaluedMap}. * * @param mmap * @return the created unmodifiable map */ public static UnmodifiableMultivaluedMap get( MultivaluedMap mmap) { return get(mmap, true); } /** * Returns an UnmodifiableMultivaluedMap, that contains the content of the * given {@link MultivaluedMap}. * * @param mmap * @param caseSensitive * @return the created unmodifiable map */ public static UnmodifiableMultivaluedMap get( MultivaluedMap mmap, boolean caseSensitive) { if (mmap instanceof UnmodifiableMultivaluedMap) { return (UnmodifiableMultivaluedMap) mmap; } if (mmap instanceof MultivaluedMapImpl) { return new UnmodifiableMultivaluedMap( (MultivaluedMapImpl) mmap, caseSensitive); } return new UnmodifiableMultivaluedMap( new MultivaluedMapImpl(mmap), caseSensitive); } /** * Creates an UnmodifiableMultivaluedMap<String, String;> from the * given Form. * * @param form * @param caseSensitive * @return the created unmodifiable map */ public static UnmodifiableMultivaluedMap getFromForm( Form form, boolean caseSensitive) { return new UnmodifiableMultivaluedMap(copyForm(form, !caseSensitive), caseSensitive); } private final MultivaluedMapImpl mmap; private final boolean caseInsensitive; /** * Creates a new unmodifiable {@link MultivaluedMap}. * * @param mmap * @param caseSensitive */ private UnmodifiableMultivaluedMap(MultivaluedMapImpl mmap, boolean caseSensitive) { this.mmap = mmap; this.caseInsensitive = !caseSensitive; } @Deprecated public void add(K key, V value) { throw throwUnmodifiable(); } private Object caseInsensitive(Object key) { if (this.caseInsensitive && (key != null)) { key = key.toString().toLowerCase(); } return key; } @Deprecated public void clear() throws UnsupportedOperationException { throw throwUnmodifiable(); } public boolean containsKey(Object key) { if (this.caseInsensitive && (key != null)) { this.mmap.containsKey(caseInsensitive(key.toString())); } return this.mmap.containsKey(key); } public boolean containsValue(Object value) { if (value instanceof List) { return this.mmap.containsValue(value); } for (final List vList : this.mmap.values()) { if (vList.contains(value)) { return true; } } return false; } public Set>> entrySet() { return Collections.unmodifiableSet(this.mmap.entrySet()); } @Override public boolean equals(Object anotherObect) { if (anotherObect == this) { return true; } if (!(anotherObect instanceof MultivaluedMap)) { return false; } return this.mmap.equals(anotherObect); } public List get(Object key) { return Collections .unmodifiableList(this.mmap.get(caseInsensitive(key))); } @SuppressWarnings("unchecked") public V getFirst(K key) { if (this.caseInsensitive && (key instanceof String)) { key = (K) key.toString().toLowerCase(); } return this.mmap.getFirst(key); } /** * Returns the last element for the given key. * * @param key * @return Returns the last element for the given key. */ @SuppressWarnings("unchecked") public V getLast(K key) { if (this.caseInsensitive && (key instanceof String)) { key = (K) key.toString().toLowerCase(); } return this.mmap.getLast(key); } @Override public int hashCode() { int hashCode = this.mmap.hashCode(); if (this.caseInsensitive) { hashCode++; } return hashCode; } public boolean isEmpty() { return this.mmap.isEmpty(); } public Set keySet() { return Collections.unmodifiableSet(this.mmap.keySet()); } public List put(K key, List value) throws UnsupportedOperationException { throw throwUnmodifiable(); } public void putAll(Map> t) throws UnsupportedOperationException { throw throwUnmodifiable(); } public void putSingle(K key, V value) throws UnsupportedOperationException { throw throwUnmodifiable(); } public List remove(Object key) throws UnsupportedOperationException { throw throwUnmodifiable(); } public int size() { int size = 0; for (final List l : this.mmap.values()) { size += l.size(); } return size; } /** * @throws UnsupportedOperationException */ private UnsupportedOperationException throwUnmodifiable() throws UnsupportedOperationException { throw new UnsupportedOperationException( "The HTTP headers are immutable"); } public Collection> values() { return Collections.unmodifiableCollection(this.mmap.values()); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/core/MatchedInfo.java0000664000175000017500000000617011757206350032722 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs.internal.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.restlet.ext.jaxrs.internal.util.EncodeOrCheck; class MatchedInfo { /** * */ private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * an unmodifiable list with the resource objects. */ private final List resources; /** * an unmodifiable list with the decoded uris, or null, if not yet * requested. */ private volatile List urisDecoded; /** * an unmodifiable list with the encoded uris. */ private final List urisEncoded; /** * @param urisEncoded * @param resources */ public MatchedInfo(List urisEncoded, List resources) { this.urisEncoded = Arrays.asList(urisEncoded .toArray(EMPTY_STRING_ARRAY)); this.resources = Arrays.asList(resources.toArray()); } /** * Returns an unmodifiable List of resource class objects. * * @return an unmodifiable List of resource class objects. */ List getResources() { return this.resources; } /** * Returns an unmodifiable List of relative URI parts. * * @return an unmodifiable List of relative URI parts. */ List getUris(boolean decode) { if (decode) { if (this.urisDecoded == null) { List urisDecoded; urisDecoded = new ArrayList(this.urisEncoded.size()); for (final String uriEncoded : this.urisEncoded) { urisDecoded.add(EncodeOrCheck.all(uriEncoded, false)); } this.urisDecoded = Collections.unmodifiableList(urisDecoded); } return this.urisDecoded; } return this.urisEncoded; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/package-info.java0000664000175000017500000000404011757206350030313 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Implementation of JAX-RS 1.0 (JSR-311). This is the API developed by the * JSR-311 expert group. The main class is JaxRsApplication. *

*

* This extension doesn't pretend to be fully compliant with the * specification but it is close to completion. We are looking forward to * getting access to the TCK in order to validate our compatibility. *

* * @since Restlet 1.1 * @see Specification: PDF (normative) * @see * HTML (non normative) * @see JSR-311 Web site * @author Stephan Koops */ package org.restlet.ext.jaxrs; restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/ExtendedUriInfo.java0000664000175000017500000000700711757206350031031 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import javax.ws.rs.core.UriInfo; /** * This {@link UriInfo} extension returns {@link javax.ws.rs.core.UriBuilder}s * which contains the "file" extension given by the request. This extension will * also be available, if the path will be changed (e.g. replaced, removed or * matrix parameters added). For further information see * {@link ExtendedUriBuilder#extension(String)}, * {@link ExtendedUriBuilder#extensionLanguage(String)} and * {@link ExtendedUriBuilder#extensionMedia(String)}. You could get it in the * same way as the default UriInfo, that measn annotate a field of this type * with @{@link javax.ws.rs.core.Context}. * * @author Stephan Koops * @see UriInfo */ public interface ExtendedUriInfo extends UriInfo { /** * Get the absolute path of the request in the form of an * {@link ExtendedUriBuilder}. This includes everything preceding the path * (host, port etc) but excludes query parameters. It also includes the * extension of the current request. * * @return an ExtendedUriBuilder initialized with the absolute path of the * request and an extension according to the current chosen media * type. * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see UriInfo#getAbsolutePathBuilder() */ public ExtendedUriBuilder getAbsolutePathBuilder(); /** * Get the base URI of the application in the form of an * {@link ExtendedUriBuilder}. It also includes the extension of the current * request. * * @return a UriBuilder initialized with the base URI of the application and * an extension according to the current chosen media type. * @see UriInfo#getBaseUriBuilder() */ public ExtendedUriBuilder getBaseUriBuilder(); /** * Get the absolute request URI in the form of an {@link ExtendedUriBuilder} * . It also includes the extension of the current request. * * @return a UriBuilder initialized with the absolute request URI and an * extension according to the current chosen media type * @throws java.lang.IllegalStateException * if called outside the scope of a request */ public ExtendedUriBuilder getRequestUriBuilder(); } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/ExtendedUriBuilder.java0000664000175000017500000003477111757206350031534 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import java.lang.reflect.Method; import java.net.URI; import java.util.Map; import java.util.StringTokenizer; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; import org.restlet.Application; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.service.MetadataService; /** * This {@link UriBuilder} extension provides special help for "file" * extensions. They will not be removed, if path will be changed (e.g. replaced, * removed or matrix parameters added). For further information see * {@link #extension(String)}, {@link #extensionLanguage(String)} and * {@link #extensionMedia(String)}. You could get an instance with an * {@link ExtendedUriInfo}. * * @author Stephan Koops */ public class ExtendedUriBuilder extends AbstractUriBuilder { /** * Create a new instance representing a relative URI initialized from a URI * path. * * @param path * a URI path that will be used to initialize the UriBuilder, may * contain URI template parameters. * @return a new UriBuilder * @throws IllegalArgumentException * if path is null */ public static ExtendedUriBuilder fromPath(String path) throws IllegalArgumentException { ExtendedUriBuilder b = newInstance(); b.replacePath(path); return b; } /** * Create a new instance representing a relative URI initialized from a root * resource class. * * @param resource * a root resource whose {@link javax.ws.rs.Path} value will be * used to initialize the UriBuilder. * @return a new UriBuilder * @throws IllegalArgumentException * if resource is not annotated with {@link javax.ws.rs.Path} or * resource is null. */ public static ExtendedUriBuilder fromResource(Class resource) throws IllegalArgumentException { ExtendedUriBuilder b = newInstance(); b.path(resource); return b; } /** * Create a new instance initialized from an existing URI. * * @param uri * a URI that will be used to initialize the UriBuilder, may not * contain URI parameters. * @return a new UriBuilder * @throws IllegalArgumentException * if uri is not a valid URI or is null */ public static ExtendedUriBuilder fromUri(String uri) throws IllegalArgumentException { URI u; try { u = URI.create(uri); } catch (NullPointerException ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } return fromUri(u); } /** * Create a new instance initialized from an existing URI. * * @param uri * a URI that will be used to initialize the UriBuilder. * @return a new UriBuilder * @throws IllegalArgumentException * if uri is null */ public static ExtendedUriBuilder fromUri(URI uri) throws IllegalArgumentException { ExtendedUriBuilder b = newInstance(); b.uri(uri); return b; } /** * Creates a new instance of UriBuilder. * * @return a new instance of UriBuilder */ public static ExtendedUriBuilder newInstance() { return new ExtendedUriBuilder(); } /** The extension for the language */ private String extensionLanguage; /** The extension for the media type */ private String extensionMedia; /** * Other extensions as language and media type * * @see #extensionLanguage * @see #extensionMedia */ private String extensionOthers; /** {@inheritDoc} */ @Override public ExtendedUriBuilder clone() { ExtendedUriBuilder clone = new ExtendedUriBuilder(); super.copyInto(clone); clone.extension(this.getExtension()); return clone; } /** * Set the extension that will be appended to the final path segment at * build time. An initial "." will be appended if necessary. If the final * path segment already contains an extension, it will be retained and the * supplied extension will be used as a new extension. * *

* Note that the extension will be appended to the path component, matrix * and query parameters will follow any appended extension. *

* * @param extensions * the extensions to append at build time, a null value will * result in no extension being appended. * @return the updated UriBuilder */ public ExtendedUriBuilder extension(String extensions) { if (extensions == null) { this.extensionLanguage = null; this.extensionMedia = null; this.extensionOthers = null; return this; } MetadataService metadataService; metadataService = Application.getCurrent().getMetadataService(); StringTokenizer stt = new StringTokenizer(extensions, "."); while (stt.hasMoreTokens()) { String extension = stt.nextToken(); Metadata metadata = metadataService.getMetadata(extension); if (metadata instanceof Language) { this.extensionLanguage = extension; } else if (metadata instanceof MediaType) { this.extensionMedia = extension; } else { if (extensionOthers == null) this.extensionOthers = extension; else this.extensionOthers += "." + extension; } } return this; } /** * Appends an extension for the language ("de", "en", "fr" or whatever). * null resets the language extension. * * @param language * @return this {@link ExtendedUriBuilder} */ public ExtendedUriBuilder extensionLanguage(String language) { if (Util.startsWith(language, '.')) { this.extensionLanguage = language.substring(1); } else { this.extensionLanguage = language; } return this; } /** * Appends an extension for the media type ("html", "pdf", "gif" or * whatever). null resets the media type extension. * * @param mediaExtension * @return this ExtendedUriBuilder */ public ExtendedUriBuilder extensionMedia(String mediaExtension) { if (Util.startsWith(mediaExtension, '.')) { this.extensionMedia = mediaExtension.substring(1); } else { this.extensionMedia = mediaExtension; } return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder fragment(String fragment) { super.fragment(fragment); return this; } /** * Returns the extension of the current uri, if available. * * @return the extension for content negotiation, including a "." at the * start, or null if no extension is available. Never * returns "" or ".". */ @Override public String getExtension() { StringBuilder stb = new StringBuilder(); if (extensionOthers != null) { stb.append('.'); stb.append(extensionOthers); } if (extensionLanguage != null) { stb.append('.'); stb.append(extensionLanguage); } if (extensionMedia != null) { stb.append('.'); stb.append(extensionMedia); } if (stb.length() == 0) return null; return stb.toString(); } /** {@inheritDoc} */ @Override public ExtendedUriBuilder host(String host) throws IllegalArgumentException { super.host(host); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder matrixParam(String name, Object... values) throws IllegalArgumentException { super.matrixParam(name, values); return this; } /** {@inheritDoc} */ @Override @SuppressWarnings("rawtypes") public ExtendedUriBuilder path(Class resource) throws IllegalArgumentException { super.path(resource); return this; } /** {@inheritDoc} */ @Override @SuppressWarnings("rawtypes") public ExtendedUriBuilder path(Class resource, String methodName) throws IllegalArgumentException { super.path(resource, methodName); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder path(Method method) throws IllegalArgumentException { super.path(method); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder path(String pathToAppend) throws IllegalArgumentException { super.path(pathToAppend); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder port(int port) throws IllegalArgumentException { super.port(port); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder port(String port) throws IllegalArgumentException { super.port(port); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder queryParam(String name, Object... values) throws IllegalArgumentException { super.queryParam(name, values); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder replaceMatrix(String matrix) throws IllegalArgumentException { super.replaceMatrix(matrix); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder replaceMatrixParam(String name, Object... values) throws IllegalArgumentException { super.replaceMatrixParam(name, values); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder replacePath(String newPath) { if (newPath == null) { super.replacePath(newPath); this.extension(null); return this; } int beginLastSegment = newPath.lastIndexOf('/'); int beginLastMatrix = newPath.indexOf(';', beginLastSegment); int endExt = beginLastMatrix > 0 ? beginLastMatrix : newPath.length(); int beginExtensions = Util.indexOfBetween(newPath, '.', beginLastSegment, endExt); if (beginExtensions < 0) { super.replacePath(newPath); return this; } String extensions = newPath.substring(beginExtensions, endExt); StringBuilder pathStb = new StringBuilder(); pathStb.append(newPath, 0, beginExtensions); pathStb.append(newPath, endExt, newPath.length()); this.extension(extensions); super.replacePath(pathStb); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder replaceQuery(String query) throws IllegalArgumentException { super.replaceQuery(query); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder replaceQueryParam(String name, Object... values) throws IllegalArgumentException { super.replaceQueryParam(name, values); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder scheme(String scheme) throws IllegalArgumentException { super.scheme(scheme); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder schemeSpecificPart(String ssp) throws IllegalArgumentException { super.schemeSpecificPart(ssp); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder segment(String... segments) throws IllegalArgumentException { super.segment(segments); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder uri(URI uri) throws IllegalArgumentException { super.uri(uri); return this; } /** {@inheritDoc} */ @Override public ExtendedUriBuilder userInfo(String ui) { super.userInfo(ui); return this; } /** {@inheritDoc} */ @Override public URI build(Object... values) throws IllegalArgumentException, UriBuilderException { return super.build(values); } /** {@inheritDoc} */ @Override public URI buildFromEncoded(Object... values) throws IllegalArgumentException, UriBuilderException { return super.buildFromEncoded(values); } /** {@inheritDoc} */ @Override public URI buildFromEncodedMap(Map values) throws IllegalArgumentException, UriBuilderException { return super.buildFromEncodedMap(values); } /** * @see javax.ws.rs.core.UriBuilder#buildFromMap(java.util.Map) */ @Override public URI buildFromMap(Map values) throws IllegalArgumentException, UriBuilderException { return super.buildFromMap(values); } /** {@inheritDoc} */ @Override public String toString() { return super.toString(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/RoleChecker.java0000664000175000017500000001115711757206350030164 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import java.security.Principal; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.data.ClientInfo; import org.restlet.security.Guard; /** *

* This interface provides user role checks. *

*

* This interface is from a time when Restlet did not have a full security API, * and hence no support for checking if a user is in a role. At that time, this * interface was used to check if a user is in a role. It is currently still * supported for backwards compatibility, but should not be used for new * development. *

*

* Implementations must be thread save. *

*

* This interface is used by {@link SecurityContext#isUserInRole(String)}. The * JAX-RS runtime delegates this method call along with the {@link Principal} of * the HTTP request to method {@link #isInRole(Principal, String)}, the only * method of this interface. *

*

* If you want to use a RoleChecker, you must give an instance of this inteface * to the {@link JaxRsApplication}. If you do not give an instance, the normal * Restlet security API will be used. *

*

* To check if the user is authenticated, use any Restlet {@link Guard}. *

* * @author Stephan Koops * @see SecurityContext * @see ClientInfo#getRoles * @deprecated Use the new Restlet security model instead. */ @Deprecated public interface RoleChecker { /** * Access control constant that gives all roles to all principals. */ public static final RoleChecker ALLOW_ALL = new RoleChecker() { public boolean isInRole(Principal principal, String role) throws WebApplicationException { return true; } }; /** * Access control constant that doesn't give any role to any principal. */ public static final RoleChecker FORBID_ALL = new RoleChecker() { public boolean isInRole(Principal principal, String role) throws WebApplicationException { return false; } }; /** * An {@link RoleChecker} that throws an WebApplicationExeption with status * 500 (Internal Server Error) for every call on it. */ public static final RoleChecker REJECT_WITH_ERROR = new RoleChecker() { public boolean isInRole(Principal principal, String role) throws WebApplicationException { final String message = "No access control defined."; final ResponseBuilder rb = Response.serverError(); rb.entity(message).language("en").type(MediaType.TEXT_HTML_TYPE); throw new WebApplicationException(rb.build()); } }; /** * Checks, if the user is in the given role, or false if not.
* This method is used by the {@link SecurityContext}. * * @param principal * The principal to check. * @param role * the role. * @return true, if the user is in the role, false otherwise. * @throws WebApplicationException * The developer may handle exceptions by throw a * {@link WebApplicationException}. * @see SecurityContext#isUserInRole(String) */ public boolean isInRole(Principal principal, String role) throws WebApplicationException; } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/JaxRsRestlet.java0000664000175000017500000015146511757206350030377 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.addPathVarsToMap; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.getBestMethod; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.getFirstByNoOfLiteralCharsNoOfCapturingGroups; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.removeNotSupportedHttpMethod; import static org.restlet.ext.jaxrs.internal.util.Util.copyResponseHeaders; import static org.restlet.ext.jaxrs.internal.util.Util.getMediaType; import static org.restlet.ext.jaxrs.internal.util.Util.getSupportedCharSet; import static org.restlet.ext.jaxrs.internal.util.Util.sortByConcreteness; import java.lang.annotation.Annotation; import java.lang.reflect.GenericSignatureFormatError; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.ClientInfo; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.MethodInvokeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.RequestHandledException; import org.restlet.ext.jaxrs.internal.provider.BufferedReaderProvider; import org.restlet.ext.jaxrs.internal.provider.ByteArrayProvider; import org.restlet.ext.jaxrs.internal.provider.ConverterProvider; import org.restlet.ext.jaxrs.internal.provider.FileProvider; import org.restlet.ext.jaxrs.internal.provider.InputStreamProvider; import org.restlet.ext.jaxrs.internal.provider.ReaderProvider; import org.restlet.ext.jaxrs.internal.provider.SourceProvider; import org.restlet.ext.jaxrs.internal.provider.StreamingOutputProvider; import org.restlet.ext.jaxrs.internal.provider.StringProvider; import org.restlet.ext.jaxrs.internal.provider.WebAppExcMapper; import org.restlet.ext.jaxrs.internal.provider.WwwFormFormProvider; import org.restlet.ext.jaxrs.internal.provider.WwwFormMmapProvider; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.ExceptionHandler; import org.restlet.ext.jaxrs.internal.util.JaxRsOutputRepresentation; import org.restlet.ext.jaxrs.internal.util.MatchingResult; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.util.RemainingPath; import org.restlet.ext.jaxrs.internal.util.SortedMetadata; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.util.WrappedRequestForHttpHeaders; import org.restlet.ext.jaxrs.internal.wrappers.AbstractMethodWrapper; import org.restlet.ext.jaxrs.internal.wrappers.ResourceClass; import org.restlet.ext.jaxrs.internal.wrappers.ResourceClasses; import org.restlet.ext.jaxrs.internal.wrappers.ResourceMethod; import org.restlet.ext.jaxrs.internal.wrappers.ResourceMethodOrLocator; import org.restlet.ext.jaxrs.internal.wrappers.ResourceObject; import org.restlet.ext.jaxrs.internal.wrappers.RootResourceClass; import org.restlet.ext.jaxrs.internal.wrappers.SubResourceLocator; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; import org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriter; import org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriterSubSet; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ResourceException; import org.restlet.routing.Router; import org.restlet.service.MetadataService; /** *

* This class choose the JAX-RS resource class and method to use for a request * and handles the result from the resource method. Typically you should * instantiate a {@link JaxRsApplication} to run JAX-RS resource classes. *

* * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Stephan Koops */ public class JaxRsRestlet extends Restlet { /** * Structure to return the obtained {@link ResourceObject} and the * identified {@link ResourceMethod}. * * @author Stephan Koops */ class ResObjAndMeth { private ResourceObject resourceObject; private ResourceMethod resourceMethod; ResObjAndMeth(ResourceObject resourceObject, ResourceMethod resourceMethod) { this.resourceObject = resourceObject; this.resourceMethod = resourceMethod; } } /** * Structure to return the obtained {@link ResourceObject} and the remaining * path after identifying the object. * * @author Stephan Koops */ class ResObjAndRemPath { private ResourceObject resourceObject; private RemainingPath u; ResObjAndRemPath(ResourceObject resourceObject, RemainingPath u) { this.resourceObject = resourceObject; this.u = u; } } /** * Structure to return an instance of the identified * {@link RootResourceClass}, the matched URI path and the remaining path * after identifying the root resource class. * * @author Stephan Koops */ class RroRemPathAndMatchedPath { private ResourceObject rootResObj; private RemainingPath u; private String matchedUriPath; RroRemPathAndMatchedPath(ResourceObject rootResObj, RemainingPath u, String matchedUriPath) { this.rootResObj = rootResObj; this.u = u; this.matchedUriPath = matchedUriPath; } } static { javax.ws.rs.ext.RuntimeDelegate .setInstance(new org.restlet.ext.jaxrs.internal.spi.RuntimeDelegateImpl()); } private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; @SuppressWarnings("deprecation") private volatile RoleChecker roleChecker; private final JaxRsProviders providers; private final ResourceClasses resourceClasses; /** * Contains and handles the exceptions occurring while in resource objects * and providers, and also for the other cases where the runtime environment * should throw {@link WebApplicationException}. */ private final ExceptionHandler excHandler; /** * Contains the thread localized {@link CallContext}s. */ private final ThreadLocalizedContext tlContext = new ThreadLocalizedContext(); private volatile ObjectFactory objectFactory; /** * Creates a new JaxRsRestlet with the given Context. Only the default * providers are loaded. * * @param context * the context from the parent, see * {@link Restlet#Restlet(Context)}. * @param metadataService * the metadata service of the {@link JaxRsApplication}. * @see #JaxRsRestlet(Context, RoleChecker, MetadataService) */ public JaxRsRestlet(Context context, MetadataService metadataService) { this(context, null, metadataService); } /** * Creates a new JaxRsRestlet with the given Context. Only the default * providers are loaded. * * @param context * the context from the parent, see * {@link Restlet#Restlet(Context)}. * @param roleChecker * The RoleChecker to use. If null, the normal Restlet security * API wil be used. * @param metadataService * the metadata service of the {@link JaxRsApplication}. * @see #JaxRsRestlet(Context, MetadataService) */ @SuppressWarnings("deprecation") public JaxRsRestlet(Context context, RoleChecker roleChecker, MetadataService metadataService) { super(context); final ExtensionBackwardMapping extensionBackwardMapping = new ExtensionBackwardMapping( metadataService); this.excHandler = new ExceptionHandler(getLogger()); this.providers = new JaxRsProviders(this.objectFactory, this.tlContext, extensionBackwardMapping, getLogger()); this.resourceClasses = new ResourceClasses(this.tlContext, this.providers, extensionBackwardMapping, getLogger()); this.loadDefaultProviders(); this.setRoleChecker(roleChecker); } /** * Will use the given JAX-RS root resource class.
* If the given class is not a valid root resource class, a warning is * logged and false is returned. * * @param jaxRsClass * A JAX-RS root resource class or provider class to add. If the * root resource class is already available in this JaxRsRestlet, * it is ignored for later calls of this method. * @return true if the class is added or was already included, or false if * the given class is not a valid class (a warning was logged). * @throws IllegalArgumentException * if the root resource class is null. */ public boolean addClass(Class jaxRsClass) throws IllegalArgumentException { if (jaxRsClass == null) throw new IllegalArgumentException( "The JAX-RS class to add must not be null"); boolean used = false; if (Util.isRootResourceClass(jaxRsClass)) { used = resourceClasses.addRootClass(jaxRsClass); } if (Util.isProvider(jaxRsClass)) { if (providers.addClass(jaxRsClass)) used = true; } // @see Application#getClasses() // @see Application#getSingletons() if (!used) { getLogger() .warning( "The class " + jaxRsClass + " is neither a provider nor a root resource class"); } return used; } /** * Adds the provider object as default provider to this JaxRsRestlet. * * @param jaxRsProvider * The provider object or class name. * @return true, if the provider is ok and added, otherwise false. * @throws IllegalArgumentException * if null was given * @see {@link javax.ws.rs.ext.Provider} */ private boolean addDefaultProvider(Object jaxRsProvider) { try { return addSingleton(jaxRsProvider, true); } catch (GenericSignatureFormatError e) { getLogger().warning( "Unable to add default provider class : " + jaxRsProvider); } return false; } /** * Adds the provider object to this JaxRsRestlet. * * @param jaxRsProviderOrRootresourceObject * the JAX-RS provider or root resource object * @return true, if the provider is ok and added, otherwise false. * @throws IllegalArgumentException * if null was given * @see javax.ws.rs.ext.Provider */ public boolean addSingleton(Object jaxRsProviderOrRootresourceObject) throws IllegalArgumentException { return addSingleton(jaxRsProviderOrRootresourceObject, false); } /** * Adds the provider object to this JaxRsRestlet. * * @param jaxRsProvider * The provider object or class name. * @param defaultProvider * @return true, if the provider is ok and added, otherwise false. * @throws IllegalArgumentException * if null was given * @see {@link javax.ws.rs.ext.Provider} */ private boolean addSingleton(Object jaxRsProvider, boolean defaultProvider) throws IllegalArgumentException { if (jaxRsProvider instanceof String) { try { jaxRsProvider = Engine.loadClass((String) jaxRsProvider) .newInstance(); } catch (ClassNotFoundException e) { getLogger().fine( "Unable to load provider class : " + jaxRsProvider); jaxRsProvider = null; } catch (InstantiationException e) { getLogger().fine( "Unable to instantiate provider : " + jaxRsProvider); jaxRsProvider = null; } catch (IllegalAccessException e) { getLogger().fine( "Unable to access to provider : " + jaxRsProvider); jaxRsProvider = null; } catch (NoClassDefFoundError e) { getLogger().fine( "Unable to load provider class : " + jaxRsProvider); jaxRsProvider = null; } } else if (jaxRsProvider == null) throw new IllegalArgumentException( "The JAX-RS object to add must not be null"); else if (jaxRsProvider instanceof Class) throw new IllegalArgumentException( "The JAX-RS object to add must not be a java.lang.Class"); boolean used = false; if (jaxRsProvider != null) { if (defaultProvider || Util.isProvider(jaxRsProvider.getClass())) { used = providers.addSingleton(jaxRsProvider, defaultProvider); } if (Util.isRootResourceClass(jaxRsProvider.getClass())) { throw new NotYetImplementedException( "only providers are allowed as singletons for now"); // used = ... } if (!used) { final String warning = ("The class " + jaxRsProvider.getClass() + " is neither a provider nor a root resource class"); getLogger().warning(warning); } } return used; } // now methods for the daily work /** * Sets the Restlet that is called, if no (root) resource class or method * could be found. * * @param notMatchedRestlet * the Restlet to call, if no (root) resource class or method * could be found. * @see #setNoRootResClHandler(Restlet) * @see #setNoResourceClHandler(Restlet) * @see #setNoResMethodHandler(Restlet) * @see Router#attachDefault(Restlet) */ public void attachDefault(Restlet notMatchedRestlet) { this.setNoRootResClHandler(notMatchedRestlet); this.setNoResourceClHandler(notMatchedRestlet); this.setNoResMethodHandler(notMatchedRestlet); } /** * Converts the given entity - returned by the resource method - to a * Restlet {@link Representation}. * * @param entity * the entity to convert. * @param resourceMethod * The resource method created the entity. Could be null, if an * exception is handled, e.g. a {@link WebApplicationException}. * @param jaxRsResponseMediaType * The MediaType of the JAX-RS {@link javax.ws.rs.core.Response}. * May be null. * @param jaxRsRespHeaders * The headers added to the {@link javax.ws.rs.core.Response} by * the {@link ResponseBuilder}. * @param accMediaTypes * the accepted media type from the current call context, or the * returned of the JAX-RS {@link javax.ws.rs.core.Response}. * @return the corresponding Restlet Representation. Returns * null only if null was given. * @throws WebApplicationException * @see AbstractMethodWrapper.EntityGetter */ private Representation convertToRepresentation(Object entity, ResourceMethod resourceMethod, MediaType jaxRsResponseMediaType, MultivaluedMap jaxRsRespHeaders, SortedMetadata accMediaTypes) throws ImplementationException { if (entity instanceof Representation) { Representation repr = (Representation) entity; // ensures that a supported character set is set repr.setCharacterSet(getSupportedCharSet(repr.getCharacterSet())); if (jaxRsResponseMediaType != null) { repr.setMediaType(Converter .getMediaTypeWithoutParams(jaxRsResponseMediaType)); } return repr; } Type genericReturnType; Class entityClass; Annotation[] methodAnnotations; if (resourceMethod != null) // is default methodAnnotations = resourceMethod.getAnnotations(); else methodAnnotations = EMPTY_ANNOTATION_ARRAY; if (entity instanceof GenericEntity) { GenericEntity genericEntity = (GenericEntity) entity; genericReturnType = genericEntity.getType(); entityClass = genericEntity.getRawType(); entity = genericEntity.getEntity(); } else { entityClass = (entity != null) ? entity.getClass() : null; if (resourceMethod != null) // is default genericReturnType = resourceMethod.getGenericReturnType(); else genericReturnType = null; if (genericReturnType instanceof Class && ((Class) genericReturnType) .isAssignableFrom(javax.ws.rs.core.Response.class)) { genericReturnType = entityClass; } } final MultivaluedMap httpResponseHeaders = new WrappedRequestForHttpHeaders( tlContext.get().getResponse(), jaxRsRespHeaders); final Representation repr; if (entity != null) { final MediaType respMediaType = determineMediaType( jaxRsResponseMediaType, resourceMethod, entityClass, genericReturnType); final MessageBodyWriterSubSet mbws; mbws = providers.writerSubSet(entityClass, genericReturnType); if (mbws.isEmpty()) throw excHandler.noMessageBodyWriter(entityClass, genericReturnType, methodAnnotations, null, null); final MessageBodyWriter mbw = mbws.getBestWriter(respMediaType, methodAnnotations, accMediaTypes); if (mbw == null) throw excHandler.noMessageBodyWriter(entityClass, genericReturnType, methodAnnotations, respMediaType, accMediaTypes); repr = new JaxRsOutputRepresentation(entity, genericReturnType, respMediaType, methodAnnotations, mbw, httpResponseHeaders); } else { // entity == null repr = new EmptyRepresentation(); repr.setMediaType(determineMediaType(jaxRsResponseMediaType, resourceMethod, entityClass, genericReturnType)); } repr.setCharacterSet(getSupportedCharSet(httpResponseHeaders)); return repr; } /** * @param o * @param subResourceLocator * @param callContext * @return * @throws WebApplicationException * @throws RequestHandledException */ private ResourceObject createSubResource(ResourceObject o, SubResourceLocator subResourceLocator, CallContext callContext) throws WebApplicationException, RequestHandledException { try { o = subResourceLocator.createSubResource(o, resourceClasses, getLogger()); } catch (WebApplicationException e) { throw e; } catch (RuntimeException e) { throw excHandler.runtimeExecption(e, subResourceLocator, callContext, "Could not create new instance of resource class"); } catch (MissingAnnotationException e) { throw excHandler.missingAnnotation(e, callContext, "Could not create new instance of resource class"); } catch (InstantiateException e) { throw excHandler.instantiateExecption(e, callContext, "Could not create new instance of resource class"); } catch (InvocationTargetException e) { throw handleInvocationTargetExc(e); } catch (ConvertRepresentationException e) { throw excHandler.convertRepresentationExc(e); } return o; } /** * Determines the MediaType for a response, see JAX-RS-Spec (2008-08-27), * section 3.8 "Determining the MediaType of Responses" * * @param jaxRsResponseMediaType * @param resourceMethod * The ResourceMethod that created the entity. * @param entityClass * needed, if neither the resource method nor the resource class * is annotated with @{@link Produces}. * @param genericReturnType * needed, if neither the resource method nor the resource class * is annotated with @{@link Produces}. * @param methodAnnotation * needed, if neither the resource method nor the resource class * is annotated with @{@link Produces}. * @param mbws * The {@link MessageBodyWriter}s, that support the class of the * returned entity object as generic type of the * {@link MessageBodyWriter}. * @return the determined {@link MediaType}. If no method is given, * "text/plain" is returned. * @throws WebApplicationException */ private MediaType determineMediaType(MediaType jaxRsResponseMediaType, ResourceMethod resourceMethod, Class entityClass, Type genericReturnType) throws WebApplicationException { // In many cases it is not possible to statically determine the media // type of a response. The following algorithm is used to determine the // response media type, Mselected, at run time: // 1. If the method returns an instance of Response whose metadata // includes the response media type (Mspecified) then set Mselected = // Mspecified, finish. if (jaxRsResponseMediaType != null) return jaxRsResponseMediaType; if (resourceMethod == null) return MediaType.TEXT_PLAIN; CallContext callContext = tlContext.get(); // 2. Gather the set of producible media types P : // // (a) If the method is annotated with @Produces, set P = {V (method)} // where V (t) represents the values of @Produces on the specified // target t. // // (b) Else if the class is annotated with @Produces, set P = {V // (class)}. Collection p = resourceMethod.getProducedMimes(); // (c) Else set P = {V (writers)} where 'writers' is the set of // MessageBodyWriter that support the class of the returned entity // object. if (p.isEmpty()) { p = providers.writerSubSet(entityClass, genericReturnType) .getAllProducibleMediaTypes(); } // 3. If P = {}, set P = {'*/*'} if (p.isEmpty()) return MediaType.ALL; else p = sortByConcreteness(p); // 4. Obtain the acceptable media types A. If A = {}, set A = {'*/*'} SortedMetadata a = callContext.getAccMediaTypes(); if (a.isEmpty()) a = SortedMetadata.getMediaTypeAll(); // 5. Set M = {}. For each member of A,a: // (a) For each member of P,p: // (a.1) If a is compatible with p, add S(a,p) to M, where the function // S returns the most specific media type of the pair with the q-value // of a. List m = new ArrayList(); // First test equality (ideal) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.equals(p1)) { m.add(a1); } } } // Otherwise test inclusion (good) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.includes(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // Finally test compatibility (most flexible) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.isCompatible(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // 6. If M = {} then generate a WebApplicationException with a not // acceptable response (HTTP 406 status) and no entity. The exception // MUST be processed as described in section 3.3.4. Finish. if (m.isEmpty()) excHandler.notAcceptableWhileDetermineMediaType(); // 7. Sort M in descending order, with a primary key of specificity (n/m // > n/* > */*) and secondary key of q-value. // TODO // 8. For each member of M,m: // (a) If m is a concrete type, set Mselected = m, finish. for (MediaType mediaType : m) if (mediaType.isConcrete()) return mediaType; // 9. If M contains '*/*' or 'application/*', set Mselected = // 'application/octet-stream', finish. if (m.contains(MediaType.ALL) || m.contains(MediaType.APPLICATION_ALL)) return MediaType.APPLICATION_OCTET_STREAM; // 10. Generate a WebApplicationException with a not acceptable response // (HTTP 406 status) and no entity. The exception MUST be processed as // described in section 3.3.4. Finish. throw excHandler.notAcceptableWhileDetermineMediaType(); } /** * Returns the Restlet that is called, if no resource method class could be * found. * * @return the Restlet that is called, if no resource method class could be * found. * @see #setNoResMethodHandler(Restlet) */ public Restlet getNoResMethodHandler() { return excHandler.getNoResMethodHandler(); } /** * Returns the Restlet that is called, if no resource class could be found. * * @return the Restlet that is called, if no resource class could be found. */ public Restlet getNoResourceClHandler() { return excHandler.getNoResourceClHandler(); } /** * Returns the Restlet that is called, if no root resource class could be * found. You could remove a given Restlet by set null here.
* If no Restlet is given here, status 404 will be returned. * * @return the Restlet that is called, if no root resource class could be * found. * @see #setNoRootResClHandler(Restlet) */ public Restlet getNoRootResClHandler() { return excHandler.getNoRootResClHandler(); } /** * Returns the ObjectFactory for root resource class and provider * instantiation, if given. * * @return the ObjectFactory for root resource class and provider * instantiation, if given. */ public ObjectFactory getObjectFactory() { return this.objectFactory; } /** * Gets the currently used {@link RoleChecker}. * * @return the currently used RoleChecker. * @see #setRoleChecker(RoleChecker) * @deprecated Use {@link ClientInfo#getRoles()} instead */ @Deprecated public RoleChecker getRoleChecker() { return roleChecker; } /** * Returns an unmodifiable set with the attached root resource classes. * * @return an unmodifiable set with the attached root resource classes. */ public Set> getRootResourceClasses() { Set> rrcs = new HashSet>(); for (RootResourceClass rootResourceClass : this.resourceClasses.roots()) rrcs.add(rootResourceClass.getJaxRsClass()); return Collections.unmodifiableSet(rrcs); } /** * Returns a Collection with all root uris attached to this JaxRsRestlet. * * @return a Collection with all root uris attached to this JaxRsRestlet. */ public Collection getRootUris() { List uris = new ArrayList(); for (RootResourceClass rrc : this.resourceClasses.roots()) uris.add(rrc.getPathRegExp().getPathTemplateEnc()); return Collections.unmodifiableCollection(uris); } /** * Handles a call by looking for the resource metod to call, call it and * return the result. * * @param request * The {@link Request} to handle. * @param response * The {@link Response} to update. */ @Override public void handle(Request request, Response response) { super.handle(request, response); ResourceObject resourceObject = null; final Reference baseRef = request.getResourceRef().getBaseRef(); request.setRootRef(new Reference(baseRef.toString())); // NICE Normally, the "rootRef" property is set by the VirtualHost, each // time a request is handled by one of its routes. // Email from Jerome, 2008-09-22 try { CallContext callContext; callContext = new CallContext(request, response, this.roleChecker); tlContext.set(callContext); try { ResObjAndMeth resObjAndMeth; resObjAndMeth = requestMatching(); callContext.setReadOnly(); ResourceMethod resourceMethod = resObjAndMeth.resourceMethod; resourceObject = resObjAndMeth.resourceObject; Object result = invokeMethod(resourceMethod, resourceObject); handleResult(result, resourceMethod); } catch (WebApplicationException e) { // the message of the Exception is not used in the // WebApplicationException jaxRsRespToRestletResp(this.providers.convert(e), null); return; } } catch (RequestHandledException e) { // Exception was handled and data were set into the Response. } finally { Representation entity = request.getEntity(); if (entity != null) entity.release(); } } /** * Handles the given Exception, catched by an invoke of a resource method or * a creation if a sub resource object. * * @param ite * @param methodName * @throws RequestHandledException * throws this message to exit the method and indicate, that the * request was handled. * @throws RequestHandledException */ private RequestHandledException handleInvocationTargetExc( InvocationTargetException ite) throws RequestHandledException { Throwable cause = ite.getCause(); if (cause instanceof ResourceException) { // avoid mapping to a JAX-RS Response and back to a Restlet Response Status status = ((ResourceException) cause).getStatus(); Response restletResponse = tlContext.get().getResponse(); restletResponse.setStatus(status); } else { javax.ws.rs.core.Response jaxRsResp = this.providers.convert(cause); jaxRsRespToRestletResp(jaxRsResp, null); } throw new RequestHandledException(); } /** * Sets the result of the resource method invocation into the response. Do * necessary converting. * * @param result * the object returned by the resource method * @param resourceMethod * the resource method; it is needed for the conversion. Could be * null, if an exception is handled, e.g. a * {@link WebApplicationException}. */ private void handleResult(Object result, ResourceMethod resourceMethod) { Response restletResponse = tlContext.get().getResponse(); if (result instanceof javax.ws.rs.core.Response) { jaxRsRespToRestletResp((javax.ws.rs.core.Response) result, resourceMethod); } else if (result instanceof ResponseBuilder) { String warning = "the method " + resourceMethod + " returnef a ResponseBuilder. You should " + "call responseBuilder.build() in the resource method"; getLogger().warning(warning); jaxRsRespToRestletResp(((ResponseBuilder) result).build(), resourceMethod); } else { if (result == null) // no representation restletResponse.setStatus(Status.SUCCESS_NO_CONTENT); else restletResponse.setStatus(Status.SUCCESS_OK); SortedMetadata accMediaTypes; accMediaTypes = tlContext.get().getAccMediaTypes(); restletResponse.setEntity(convertToRepresentation(result, resourceMethod, null, null, accMediaTypes)); } } /** * Identifies the method that will handle the request, see JAX-RS-Spec * (2008-04-16), section 3.7.2 "Request Matching", Part 3: Identify the * method that will handle the request:" * * @return Resource Object and Method, that handle the request. * @throws RequestHandledException * for example if the method was OPTIONS, but no special * Resource Method for OPTIONS is available. * @throws ResourceMethodNotFoundException */ private ResObjAndMeth identifyMethod(ResObjAndRemPath resObjAndRemPath, MediaType givenMediaType) throws RequestHandledException { CallContext callContext = tlContext.get(); org.restlet.data.Method httpMethod = callContext.getRequest() .getMethod(); // 3. Identify the method that will handle the request: // (a) ResourceObject resObj = resObjAndRemPath.resourceObject; RemainingPath u = resObjAndRemPath.u; // (a) 1 ResourceClass resourceClass = resObj.getResourceClass(); Collection resourceMethods = resourceClass .getMethodsForPath(u); if (resourceMethods.isEmpty()) excHandler.resourceMethodNotFound();// NICE (resourceClass, u); // (a) 2: remove methods not support the given method boolean alsoGet = httpMethod.equals(Method.HEAD); removeNotSupportedHttpMethod(resourceMethods, httpMethod, alsoGet); if (resourceMethods.isEmpty()) { Set allowedMethods = resourceClass.getAllowedMethods(u); if (httpMethod.equals(Method.OPTIONS)) { callContext.getResponse().getAllowedMethods() .addAll(allowedMethods); throw new RequestHandledException(); } excHandler.methodNotAllowed(allowedMethods); } // (a) 3 if (givenMediaType != null) { Collection supporting = resourceMethods; resourceMethods = new ArrayList(); for (ResourceMethod resourceMethod : supporting) { if (resourceMethod.isGivenMediaTypeSupported(givenMediaType)) resourceMethods.add(resourceMethod); } if (resourceMethods.isEmpty()) excHandler.unsupportedMediaType(supporting); } // (a) 4 SortedMetadata accMediaTypes = callContext .getAccMediaTypes(); Collection supporting = resourceMethods; resourceMethods = new ArrayList(); for (ResourceMethod resourceMethod : supporting) { if (resourceMethod.isAcceptedMediaTypeSupported(accMediaTypes)) resourceMethods.add(resourceMethod); } if (resourceMethods.isEmpty()) { excHandler.noResourceMethodForAccMediaTypes(supporting); } // (b) and (c) ResourceMethod bestResourceMethod = getBestMethod(resourceMethods, givenMediaType, accMediaTypes, httpMethod); MatchingResult mr = bestResourceMethod.getPathRegExp().match(u); addPathVarsToMap(mr, callContext); String matchedUriPart = mr.getMatched(); if (matchedUriPart.length() > 0) { Object jaxRsResObj = resObj.getJaxRsResourceObject(); callContext.addForMatched(jaxRsResObj, matchedUriPart); } return new ResObjAndMeth(resObj, bestResourceMethod); } /** * Identifies the root resource class, see JAX-RS-Spec (2008-04-16), section * 3.7.2 "Request Matching", Part 1: "Identify the root resource class" * * @param u * the remaining path after the base ref * @return The identified root resource object, the remaining path after * identifying and the matched template parameters; see * {@link RroRemPathAndMatchedPath}. * @throws WebApplicationException * @throws RequestHandledException */ private RroRemPathAndMatchedPath identifyRootResource(RemainingPath u) throws WebApplicationException, RequestHandledException { // 1. Identify the root resource class: // (a) // c: Set: root resource classes // e: Set // Map eAndCs = new HashMap(); Collection eAndCs = new ArrayList(); // (a) and (b) and (c) Filter E for (RootResourceClass rootResourceClass : this.resourceClasses.roots()) { // Map.Entry eAndC = eAndCIter.next(); // UriTemplateRegExp regExp = eAndC.getKey(); // Class clazz = eAndC.getValue(); PathRegExp rrcPathRegExp = rootResourceClass.getPathRegExp(); MatchingResult matchingResult = rrcPathRegExp.match(u); if (matchingResult == null) continue; // doesn't match if (matchingResult.getFinalCapturingGroup().isEmptyOrSlash()) eAndCs.add(rootResourceClass); else if (rootResourceClass.hasSubResourceMethodsOrLocators()) eAndCs.add(rootResourceClass); } // (d) if (eAndCs.isEmpty()) excHandler.rootResourceNotFound(); // (e) and (f) RootResourceClass tClass = getFirstByNoOfLiteralCharsNoOfCapturingGroups(eAndCs); // (f) PathRegExp rMatch = tClass.getPathRegExp(); MatchingResult matchResult = rMatch.match(u); u = matchResult.getFinalCapturingGroup(); addPathVarsToMap(matchResult, tlContext.get()); ResourceObject o = instantiateRrc(tClass); return new RroRemPathAndMatchedPath(o, u, matchResult.getMatched()); } /** * Instantiates the root resource class and handles thrown exceptions. * * @param rrc * the root resource class to instantiate * @return the instance of the root resource * @throws WebApplicationException * if a WebApplicationException was thrown while creating the * instance. * @throws RequestHandledException * If an Exception was thrown and the request is already * handeled. */ private ResourceObject instantiateRrc(RootResourceClass rrc) throws WebApplicationException, RequestHandledException { ResourceObject o; try { o = rrc.getInstance(this.objectFactory); } catch (WebApplicationException e) { throw e; } catch (RuntimeException e) { throw excHandler.runtimeExecption(e, null, tlContext.get(), "Could not create new instance of root resource class"); } catch (InstantiateException e) { throw excHandler.instantiateExecption(e, tlContext.get(), "Could not create new instance of root resource class"); } catch (InvocationTargetException e) { throw handleInvocationTargetExc(e); } return o; } /** * Invokes the (sub) resource method. Handles / converts also occuring * exceptions. * * @param resourceMethod * the (sub) resource method to invoke * @param resourceObject * the resource object to invoke the method on. * @return the object returned by the (sub) resource method. * @throws RequestHandledException * if the request is already handled * @throws WebApplicationException * if a JAX-RS class throws an WebApplicationException */ private Object invokeMethod(ResourceMethod resourceMethod, ResourceObject resourceObject) throws WebApplicationException, RequestHandledException { Object result; try { result = resourceMethod.invoke(resourceObject); } catch (WebApplicationException e) { throw e; } catch (InvocationTargetException ite) { throw handleInvocationTargetExc(ite); } catch (RuntimeException e) { throw excHandler.runtimeExecption(e, resourceMethod, tlContext.get(), "Can not invoke the resource method"); } catch (MethodInvokeException e) { throw excHandler.methodInvokeException(e, tlContext.get(), "Can not invoke the resource method"); } catch (ConvertRepresentationException e) { throw excHandler.convertRepresentationExc(e); } return result; } /** * Converts the given JAX-RS {@link javax.ws.rs.core.Response} to a Restlet * {@link Response}. * * @param jaxRsResponse * The response returned by the resource method, perhaps as * attribute of a {@link WebApplicationException}. * @param resourceMethod * The resource method creating the response. Could be null, if * an exception is handled, e.g. a * {@link WebApplicationException}. */ private void jaxRsRespToRestletResp( javax.ws.rs.core.Response jaxRsResponse, ResourceMethod resourceMethod) { Response restletResponse = tlContext.get().getResponse(); restletResponse.setStatus(Status.valueOf(jaxRsResponse.getStatus())); MultivaluedMap httpHeaders = jaxRsResponse .getMetadata(); MediaType respMediaType = getMediaType(httpHeaders); Object jaxRsEntity = jaxRsResponse.getEntity(); SortedMetadata accMediaType; if (respMediaType != null) accMediaType = SortedMetadata.get(respMediaType); else accMediaType = tlContext.get().getAccMediaTypes(); restletResponse.setEntity(convertToRepresentation(jaxRsEntity, resourceMethod, respMediaType, httpHeaders, accMediaType)); copyResponseHeaders(httpHeaders, restletResponse); } private void loadDefaultProviders() { addDefaultProvider(new BufferedReaderProvider()); addDefaultProvider(new ByteArrayProvider()); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.DataSourceProvider"); // not yet tested addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.FileUploadProvider"); addDefaultProvider(new FileProvider()); addDefaultProvider(new InputStreamProvider()); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.JaxbElementProvider"); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.JaxbProvider"); // not yet tested addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.MultipartProvider"); addDefaultProvider(new ReaderProvider()); addDefaultProvider(new StreamingOutputProvider()); addDefaultProvider(new StringProvider()); addDefaultProvider(new WwwFormFormProvider()); addDefaultProvider(new WwwFormMmapProvider()); addDefaultProvider(new SourceProvider()); addDefaultProvider(new WebAppExcMapper()); // Fall-back on the Restlet converter service addDefaultProvider(new ConverterProvider()); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.JsonProvider"); } /** * Obtains the object that will handle the request, see JAX-RS-Spec * (2008-04-16), section 3.7.2 "Request Matching", Part 2: "btain the object * that will handle the request" * * @param rroRemPathAndMatchedPath * @throws WebApplicationException * @throws RequestHandledException * @throws RuntimeException */ private ResObjAndRemPath obtainObject( RroRemPathAndMatchedPath rroRemPathAndMatchedPath) throws WebApplicationException, RequestHandledException { ResourceObject o = rroRemPathAndMatchedPath.rootResObj; RemainingPath u = rroRemPathAndMatchedPath.u; ResourceClass resClass = o.getResourceClass(); CallContext callContext = tlContext.get(); callContext.addForMatched(o.getJaxRsResourceObject(), rroRemPathAndMatchedPath.matchedUriPath); // Part 2 for (;;) // (j) { // (a) If U is null or '/' go to step 3 if (u.isEmptyOrSlash()) { return new ResObjAndRemPath(o, u); } // (b) Set C = class ofO,E = {} Collection eWithMethod = new ArrayList(); // (c) and (d) Filter E: remove members do not match U or final // match not empty for (ResourceMethodOrLocator methodOrLocator : resClass .getResourceMethodsAndLocators()) { PathRegExp pathRegExp = methodOrLocator.getPathRegExp(); MatchingResult matchingResult = pathRegExp.match(u); if (matchingResult == null) continue; if (matchingResult.getFinalCapturingGroup().isEmptyOrSlash()) eWithMethod.add(methodOrLocator); // the following is added by Stephan (is not in spec 2008-03-06) else if (methodOrLocator instanceof SubResourceLocator) eWithMethod.add(methodOrLocator); } // (e) If E is empty -> HTTP 404 if (eWithMethod.isEmpty()) excHandler.resourceNotFound();// NICE (o.getClass(), u); // (f) and (g) sort E, use first member of E ResourceMethodOrLocator firstMeth = getFirstByNoOfLiteralCharsNoOfCapturingGroups(eWithMethod); PathRegExp rMatch = firstMeth.getPathRegExp(); MatchingResult matchingResult = rMatch.match(u); addPathVarsToMap(matchingResult, callContext); // (h) When Method is resource method if (firstMeth instanceof ResourceMethod) return new ResObjAndRemPath(o, u); String matchedUriPart = matchingResult.getMatched(); Object jaxRsResObj = o.getJaxRsResourceObject(); callContext.addForMatched(jaxRsResObj, matchedUriPart); // (g) and (i) u = matchingResult.getFinalCapturingGroup(); SubResourceLocator subResourceLocator = (SubResourceLocator) firstMeth; o = createSubResource(o, subResourceLocator, callContext); resClass = o.getResourceClass(); // (j) Go to step 2a (repeat for) } } /** * Implementation of algorithm in JAX-RS-Spec (2008-04-16), Section 3.7.2 * "Request Matching" * * @return (Sub)Resource Method * @throws RequestHandledException * @throws WebApplicationException */ private ResObjAndMeth requestMatching() throws RequestHandledException, WebApplicationException { Request restletRequest = tlContext.get().getRequest(); // Part 1 RemainingPath u = new RemainingPath(restletRequest.getResourceRef() .getRemainingPart()); RroRemPathAndMatchedPath rrm = identifyRootResource(u); // Part 2 ResObjAndRemPath resourceObjectAndPath = obtainObject(rrm); Representation entity = restletRequest.getEntity(); // Part 3 MediaType givenMediaType; if (entity != null) givenMediaType = entity.getMediaType(); else givenMediaType = null; ResObjAndMeth method = identifyMethod(resourceObjectAndPath, givenMediaType); return method; } /** * Sets the Restlet that will handle the {@link Request}s, if no resource * method could be found. * * @param noResMethodHandler * the noResMethodHandler to set * @see #getNoResMethodHandler() * @see #setNoResourceClHandler(Restlet) * @see #setNoRootResClHandler(Restlet) * @see #attachDefault(Restlet) */ public void setNoResMethodHandler(Restlet noResMethodHandler) { excHandler.setNoResMethodHandler(noResMethodHandler); } /** * Sets the Restlet that will handle the {@link Request}s, if no resource * class could be found. You could remove a given Restlet by set null here.
* If no Restlet is given here, status 404 will be returned. * * @param noResourceClHandler * the noResourceClHandler to set * @see #getNoResourceClHandler() * @see #setNoResMethodHandler(Restlet) * @see #setNoRootResClHandler(Restlet) * @see #attachDefault(Restlet) */ public void setNoResourceClHandler(Restlet noResourceClHandler) { excHandler.setNoResourceClHandler(noResourceClHandler); } /** * Sets the Restlet that is called, if no root resource class could be * found. You could remove a given Restlet by set null here.
* If no Restlet is given here, status 404 will be returned. * * @param noRootResClHandler * the Restlet to call, if no root resource class could be found. * @see #getNoRootResClHandler() * @see #setNoResourceClHandler(Restlet) * @see #setNoResMethodHandler(Restlet) * @see #attachDefault(Restlet) */ public void setNoRootResClHandler(Restlet noRootResClHandler) { excHandler.setNoRootResClHandler(noRootResClHandler); } /** * Sets the ObjectFactory for root resource class and provider * instantiation. * * @param objectFactory * the ObjectFactory for root resource class and provider * instantiation. */ public void setObjectFactory(ObjectFactory objectFactory) { this.objectFactory = objectFactory; this.providers.setObjectFactory(objectFactory); } /** * Sets the {@link RoleChecker} to use. * * @param roleChecker * the roleChecker to set. Can be null, in which case the normal * Restlet security API will be used. * @see RoleChecker * @see #getRoleChecker() * @deprecated Use {@link ClientInfo#getRoles()} instead */ @Deprecated public void setRoleChecker(RoleChecker roleChecker) { this.roleChecker = roleChecker; } @Override public void start() throws Exception { providers.initAll(); super.start(); } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/AbstractUriBuilder.java0000664000175000017500000012406011757206350031526 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import static org.restlet.ext.jaxrs.internal.util.Util.append; import static org.restlet.ext.jaxrs.internal.util.Util.getPathTemplateWithoutRegExps; import static org.restlet.ext.jaxrs.internal.util.Util.indexBeginMatrixOfLastSegment; import static org.restlet.ext.jaxrs.internal.util.Util.notEndsWith; import static org.restlet.ext.jaxrs.internal.util.Util.notStartsWith; import java.io.IOException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.ws.rs.Path; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; import org.restlet.ext.jaxrs.internal.util.EncodeOrCheck; import org.restlet.routing.Template; import org.restlet.util.Resolver; /** * Abstract implementation of interface {@link UriBuilder}. Not intended for * public use. * * @author Stephan Koops * @see UriBuilder */ public abstract class AbstractUriBuilder extends UriBuilder { private class ArrayVariableResolver extends Resolver { private final boolean encoding; private int i = 0; private final Map retrievedValues = new HashMap(); private final Object[] values; ArrayVariableResolver(Object[] values, boolean encoding) { this.values = values; this.encoding = encoding; } @Override public String resolve(String variableName) { String varValue = this.retrievedValues.get(variableName); if (varValue == null) { if (this.i >= this.values.length) { throw new IllegalArgumentException( "The value given array contains not enough elements (contains " + this.values.length + ", but need at least " + (this.i + 1) + ")"); } final Object value = this.values[this.i]; if (value == null) { throw new IllegalArgumentException( "The given array contains null value at position (" + this.i + ")"); } varValue = value.toString(); varValue = EncodeOrCheck.all(varValue, this.encoding); this.i++; this.retrievedValues.put(variableName, varValue); } return varValue; } } /** * {@link String} or {@link StringBuilder}. It is flexible to avoid * unnecessary converting. */ private CharSequence fragment; /** * no converting or appending necessary. */ private String host; /** * {@link String} or {@link StringBuilder}. It is flexible to avoid * unnecessary converting. */ private CharSequence path; private String port = null; /** * {@link String} or {@link StringBuilder}. It is flexible to avoid * unnecessary converting. */ private CharSequence query; /** * no converting or appending necessary. */ private String scheme; /** * {@link String} or {@link StringBuilder}. It is flexible to avoid * unnecessary converting. */ private CharSequence userInfo; protected AbstractUriBuilder() { } /** * adds a valid (encoded or checked) path segment. The path may start with * "/" or not, but must not be null. * * @param path * @param newPathSegment */ private void addValidPathSegment(CharSequence newPathSegment) { final StringBuilder path = getPath(); if ((this.host != null) && notEndsWith(path, '/') && notStartsWith(newPathSegment, '/')) { path.append('/'); } path.append(newPathSegment); } /** * adds a valid (encoded or checked) path segment. The elements may start * with "/" or not, but must not be null. * * @param newPathSegments */ private void addValidPathSegments(List newPathSegments) { for (final CharSequence newPathSegment : newPathSegments) { addValidPathSegment(newPathSegment); } } /** * Build a URI, using the supplied values in order to replace any URI * template parameters. Values are converted to String using * their toString method and are then encoded to match the * rules of the URI component to which they pertain. All '%' characters in * the stringified values will be encoded. The state of the builder is * unaffected; this method may be called multiple times on the same builder * instance. *

* All instances of the same template parameter will be replaced by the same * value that corresponds to the position of the first instance of the * template parameter. e.g. the template "{a}/{b}/{a}" with values {"x", * "y", "z"} will result in the the URI "x/y/x", not "x/y/z". * * @param values * a list of URI template parameter values * @return the URI built from the UriBuilder * @throws IllegalArgumentException * if there are any URI template parameters without a supplied * value, or if a value is null. * @throws UriBuilderException * if a URI cannot be constructed based on the current state of * the builder. * @see javax.ws.rs.core.UriBuilder#build(java.lang.Object[]) */ @Override public URI build(Object... values) throws IllegalArgumentException, UriBuilderException { final Template template = new Template(toStringWithCheck(false)); return buildUri(template .format(new ArrayVariableResolver(values, true))); } /** * @see javax.ws.rs.core.UriBuilder#buildFromEncoded(java.lang.Object[]) */ @Override public URI buildFromEncoded(Object... values) throws IllegalArgumentException, UriBuilderException { final Template template = new Template(toStringWithCheck(false)); return buildUri(template .format(new ArrayVariableResolver(values, false))); } /** * @see javax.ws.rs.core.UriBuilder#buildFromEncodedMap(java.util.Map) */ @Override public URI buildFromEncodedMap(Map values) throws IllegalArgumentException, UriBuilderException { return this.buildFromMap(values, false); } /** * @see javax.ws.rs.core.UriBuilder#buildFromMap(java.util.Map) */ @Override public URI buildFromMap(Map values) throws IllegalArgumentException, UriBuilderException { return this.buildFromMap(values, true); } /** * Build a URI, any URI template parameters will be replaced by the value in * the supplied map. The build method does not change the state * of the UriBuilder and it may be called multiple times on the * same builder instance. * * @param values * a map of URI template parameter names and values * @param encode * true, if the value should be encoded, or false if not. * @return the URI built from the UriBuilder * @throws IllegalArgumentException * if automatic encoding is disabled and a supplied value * contains illegal characters, or if there are any URI template * parameters without a supplied value * @throws UriBuilderException * if a URI cannot be constructed based on the current state of * the builder. * @see javax.ws.rs.core.UriBuilder#build(java.util.Map) */ private URI buildFromMap(final Map values, final boolean encode) throws IllegalArgumentException, UriBuilderException { final Template template = new Template(toStringWithCheck(false)); return buildUri(template.format(new Resolver() { @Override public String resolve(String variableName) { final Object varValue = values.get(variableName); if (varValue == null) { throw new IllegalArgumentException( "The value Map must contain a value for all given Templet variables. The value for variable " + variableName + " is missing"); } return EncodeOrCheck.all(varValue.toString(), encode); } })); } /** * @param refAsString * @return * @throws UriBuilderException */ private URI buildUri(String refAsString) throws UriBuilderException { try { return new URI(refAsString); } catch (URISyntaxException e) { throw new UriBuilderException( "Could not build the URI from String " + refAsString, e); } } /** * @param uriBuilder */ protected void copyInto(AbstractUriBuilder uriBuilder) { if (this.fragment != null) { uriBuilder.fragment = this.fragment; this.fragment = this.fragment.toString(); } uriBuilder.host = this.host; uriBuilder.port = this.port; uriBuilder.scheme = this.scheme; if (this.userInfo != null) { uriBuilder.userInfo = this.userInfo; this.userInfo = this.userInfo.toString(); } if (this.path != null) { uriBuilder.path = this.path; this.path = this.path.toString(); } if (this.query != null) { uriBuilder.query = this.query; this.query = this.query.toString(); // copy this.query to new query, because typically the clone will // be changed and not the orignal. } } /** * Set the URI fragment using an unencoded value. * * @param fragment * the URI fragment, may contain URI template parameters * @return the updated UriBuilder * @throws IllegalArgumentException * if fragment is null, or if automatic encoding is disabled and * fragment contains illegal characters * @see javax.ws.rs.core.UriBuilder#fragment(java.lang.String) */ @Override public UriBuilder fragment(String fragment) throws IllegalArgumentException { if (fragment == null) { this.fragment = null; } else { this.fragment = EncodeOrCheck.fragment(fragment); } return this; } /** * @return the extension of the current state, with a "." at beginning. Is * intended to be overriden in subclass ExtendedUriBuilder. Must not * return null, "" or ".". */ protected String getExtension() { return null; } /** * @return The path as StringBuilder. Ensures, that the returned * StringBuilder is available in the instance variable. */ private StringBuilder getPath() { StringBuilder path; if (this.path instanceof StringBuilder) { return (StringBuilder) this.path; } if (this.path == null) { path = new StringBuilder(); this.path = path; } else { path = new StringBuilder(this.path); this.path = path; } return path; } /** * Set the URI host. * * @return the updated UriBuilder * @param host * the URI host, may contain URI template parameters * @throws IllegalArgumentException * if host is invalid or is null * @see javax.ws.rs.core.UriBuilder#host(java.lang.String) */ @Override public UriBuilder host(String host) throws IllegalArgumentException { if (host == null) { this.host = null; } else { this.host = EncodeOrCheck.host(host); } return this; } /** * Append a matrix parameter to the existing set of matrix parameters of the * current final segment of the URI path. If multiple values are supplied * the parameter will be added once per value. Note that the matrix * parameters are tied to a particular path segment; subsequent addition of * path segments will not affect their position in the URI path. * * @param name * the matrix parameter name, may contain URI template parameters * @param values * the matrix parameter value(s), each object will be converted * to a {@code String} using its {@code toString()} method. * Stringified values may contain URI template parameters. * @return the updated UriBuilder * @throws IllegalArgumentException * if name or value is null, or if automatic encoding is * disabled and the name or any stringified value contains * illegal characters * @see Matrix * URIs * @see javax.ws.rs.core.UriBuilder#matrixParam(String, Object...) */ @Override public UriBuilder matrixParam(String name, Object... values) throws IllegalArgumentException { if (values == null) { throw new IllegalArgumentException("The values must not be null"); } CharSequence ncs; ncs = EncodeOrCheck.nameOrValue(name, true, "matrix parameter name"); final List valuesStr = new ArrayList(); for (final Object value : values) { final String vcs = EncodeOrCheck.nameOrValue(value, true, "matrix parameter value"); valuesStr.add(vcs); } final StringBuilder path = getPath(); for (final String vcs : valuesStr) { path.append(';'); path.append(ncs); path.append('='); path.append(vcs); } return this; } /** * Appends the given path to the current path.S * * @param pathToAppend * @return the current UriBuilder * @throws IllegalArgumentException */ protected UriBuilder path(CharSequence pathToAppend) throws IllegalArgumentException { if (pathToAppend == null) throw new IllegalArgumentException( "the path to append must not be null"); CharSequence validPathSegment = EncodeOrCheck.pathSegmentsWithMatrix( pathToAppend, true); addValidPathSegment(validPathSegment); return this; } /** * Append path segments from a Path-annotated class to the existing list of * segments. When constructing the final path, each segment will be * separated by '/' if necessary. The value of the encode property of the * Path annotation will be used when processing the value of the * @{@link Path} but it will not be used to modify the state of * automatic encoding for the builder. * * @param rootResource * a resource whose @Path value will be used to obtain the * path segment. * @return the updated UriBuilder * @throws IllegalArgumentException * if resource is null, or if resource.encode is false and * resource.value contains illegal characters, or if resource is * not annotated with UrPath * @see javax.ws.rs.core.UriBuilder#path(java.lang.Class) */ @Override @SuppressWarnings("rawtypes") public UriBuilder path(Class rootResource) throws IllegalArgumentException { if (rootResource == null) { throw new IllegalArgumentException( "The root resource class must not be null"); } String newPathSegment; try { newPathSegment = getPathTemplateWithoutRegExps(rootResource); } catch (IllegalPathOnClassException e) { throw e.getCause(); } catch (MissingAnnotationException e) { throw new IllegalArgumentException("The class " + rootResource.getName() + " is not a valid root resource class. " + "A root resource class must be annotated with @Path"); } addValidPathSegment(newPathSegment); return this; } /** * Append path segments from a Path-annotated method to the existing list of * segments. When constructing the final path, each segment will be * separated by '/' if necessary. This method is a convenience shortcut to * path(Method), it can only be used in cases where there is a * single method with the specified name that is annotated with @ * {@link Path}. * * @param rootResource * the root resource class containing the method. * @param methodName * the name of the method whose @{@link Path} value will be * used to obtain the path segment. * @return the updated UriBuilder * @throws IllegalArgumentException * if resource or method is null, or if the specified method * does not exist, or there is more than or less than one * variant of the method annotated with UriPath * @see javax.ws.rs.core.UriBuilder#path(java.lang.Class, java.lang.String) */ @SuppressWarnings("rawtypes") @Override public UriBuilder path(Class rootResource, String methodName) throws IllegalArgumentException { if (methodName == null) { throw new IllegalArgumentException( "The method name must not be null"); } String resMethodPath = null; for (final Method method : rootResource.getMethods()) { if (!method.getName().equals(methodName)) { continue; } String path; try { path = getPathTemplateWithoutRegExps(method); } catch (IllegalPathOnMethodException e) { throw e.getCause(); } catch (MissingAnnotationException e) { throw new IllegalArgumentException(e); } if (path == null) { continue; } if ((resMethodPath != null) && !resMethodPath.equals(path)) { throw new IllegalArgumentException("The class " + rootResource + " has more than one methods with the name " + methodName + " annotated with @Path"); } resMethodPath = path; } if (resMethodPath == null) { throw new IllegalArgumentException("The class " + rootResource + " has no method with the name " + methodName + " annotated with @Path"); } addValidPathSegment(resMethodPath); return this; } /** * Append the path from a {@link javax.ws.rs.Path}-annotated method to the * existing path. When constructing the final path, a '/' separator will be * inserted between the existing path and the supplied path if necessary. * * @param method * a method whose {@link javax.ws.rs.Path} value will be used to * obtain the path to append to the existing path * @return the updated UriBuilder * @throws IllegalArgumentException * if any element of methods is null or is not annotated with a * {@link javax.ws.rs.Path} * @see javax.ws.rs.core.UriBuilder#path(java.lang.reflect.Method) */ @Override public UriBuilder path(Method method) throws IllegalArgumentException { if (method == null) { return this; } String validSegment; try { validSegment = getPathTemplateWithoutRegExps(method); } catch (MissingAnnotationException e) { throw new IllegalArgumentException(e); } catch (IllegalPathException e) { throw e.getCause(); } addValidPathSegment(validSegment); return this; } /** * Append path to the existing path. When constructing the final path, a '/' * separator will be inserted between the existing path and the supplied * path if necessary. Existing '/' characters are preserved thus a single * value can represent multiple URI path segments. * * @param pathToAppend * the path to append to the current path, may contain URI * template parameters * @return the updated UriBuilder * @throws IllegalArgumentException * if path is null * @see javax.ws.rs.core.UriBuilder#path(java.lang.String) */ @Override public UriBuilder path(String pathToAppend) throws IllegalArgumentException { path((CharSequence) pathToAppend); return this; } /** * append the given path segments to the current path * * @param segments * @return */ private List pathSegmentsWithMatrix(String[] segments) { if (segments == null) { return new ArrayList(0); } final int length = segments.length; final List r = new ArrayList(length); if (length == 0) { return r; } final String s = segments[0]; if ((s == null) || (s.length() == 0)) { return r; } r.add(EncodeOrCheck.pathSegmentWithMatrix(s, true)); for (int i = 1; i < length; i++) { r.add(EncodeOrCheck.pathSegmentWithMatrix(segments[i], true)); } return r; } /** * Set the URI port. * * @param port * the URI port, a value of -1 will unset an explicit port. * @return the updated UriBuilder * @throws IllegalArgumentException * if port is invalid * @see javax.ws.rs.core.UriBuilder#port(int) */ @Override public UriBuilder port(int port) throws IllegalArgumentException { if (port == -1) { this.port = null; } else if (port > 65535 || port < -1) { throw new IllegalArgumentException( "The port must between zero and 65535 or -1 to unset the explizit port"); } else { this.port = String.valueOf(port); } return this; } /** * Set the URI port. Only integers or a variable template is allowed * * @param port * the URI port (null will unset an explicit port) or a template * variable. * @return the updated UriBuilder * @throws IllegalArgumentException * if given value is invalid * @see #port(int) */ public UriBuilder port(String port) throws IllegalArgumentException { if (port == null) { this.port = null; } else if (port.startsWith("{") && port.endsWith("}")) { this.port = port; } else { this.port(Integer.parseInt(port)); } return this; } /** * Append a query parameter to the existing set of query parameters. If * multiple values are supplied the parameter will be added once per value. * * @param name * the query parameter name, may contain URI template parameters * @param values * the query parameter value(s), each object will be converted to * a {@code String} using its {@code toString()} method. * Stringified values may contain URI template parameters. * @return the updated UriBuilder * @throws IllegalArgumentException * if name or value is null, or if automatic encoding is * disabled and name or value contains illegal characters * @see javax.ws.rs.core.UriBuilder#queryParam(String, Object...) */ @Override public UriBuilder queryParam(String name, Object... values) throws IllegalArgumentException { if (values == null) { throw new IllegalArgumentException("The values must not be null"); } CharSequence ncs; ncs = EncodeOrCheck.nameOrValue(name, true, "query parameter name"); final List valuesStr = new ArrayList(); for (final Object value : values) { final String vcs = EncodeOrCheck.nameOrValue(value, true, "query parameter value"); valuesStr.add(vcs); } final Iterator valueIter = valuesStr.iterator(); StringBuilder query; if (this.query == null) { query = new StringBuilder(); this.query = query; } else if (this.query instanceof StringBuilder) { query = (StringBuilder) this.query; query.append('&'); } else { query = new StringBuilder(this.query.toString()); query.append('&'); } query.append(ncs); query.append('='); query.append(valueIter.next()); while (valueIter.hasNext()) { query.append('&'); query.append(ncs); query.append('='); query.append(valueIter.next()); } return this; } /** * Set the matrix parameters of the current final segment of the current URI * path. This method will overwrite any existing matrix parameters on the * current final segment of the current URI path. Note that the matrix * parameters are tied to a particular path segment; subsequent addition of * path segments will not affect their position in the URI path. * * @param matrix * the matrix parameters, may contain URI template parameters. A * null value will remove all matrix parameters of the current * final segment of the current URI path. * @return the updated UriBuilder * @throws IllegalArgumentException * if matrix cannot be parsed, or if automatic encoding is * disabled and any matrix parameter name or value contains * illegal characters * @see javax.ws.rs.core.UriBuilder#replaceMatrix(String) */ @Override public UriBuilder replaceMatrix(String matrix) throws IllegalArgumentException { CharSequence mpcs = null; if (matrix != null) { mpcs = EncodeOrCheck.fullMatrix(matrix); } final StringBuilder path = getPath(); // remove matrix params from last path segment final int beginLastPs = path.lastIndexOf("/"); if (beginLastPs >= 0) { final int beginMp = path.indexOf(";", beginLastPs); if (beginMp >= 0) { path.delete(beginMp, path.length()); } } // add new matrix parameters if (mpcs == null) { return this; } if ((mpcs.length() == 0) || (mpcs.charAt(0) != ';')) { path.append(";"); } path.append(mpcs); return this; } /** * @see javax.ws.rs.core.UriBuilder#replaceMatrixParam(java.lang.String, * java.lang.Object[]) */ @Override public UriBuilder replaceMatrixParam(String name, Object... values) throws IllegalArgumentException { // TODO replace matrix parameters throw new NotYetImplementedException( "Sorry, the relacement of matrix parameters is not supported yet"); } /** * Replaces the current path with the given path. This method checks, if * there is an extension in, if needed by this class. * * @param newPath * the new path. */ protected UriBuilder replacePath(CharSequence newPath) throws IllegalArgumentException { // TODO check for extension in subclass if (newPath == null || (newPath.length() > 0 && newPath.charAt(0) == '/')) { this.path = newPath; } else { this.path = null; path(newPath); } return this; } /** * Set the URI path. This method will overwrite any existing path and * associated matrix parameters. Existing '/' characters are preserved thus * a single value can represent multiple URI path segments. * * @param newPath * the path to replace the old path with, may contain URI * template parameters. A null value will unset the path * component of the URI. * @return the updated UriBuilder * @see javax.ws.rs.core.UriBuilder#replacePath(java.lang.String) */ @Override public UriBuilder replacePath(String newPath) throws IllegalArgumentException { return replacePath((CharSequence) newPath); } /** * Set the URI query string. This method will overwrite any existing query * parameters. * * @param query * the URI query string, may contain URI template parameters. A * null value will remove all query parameters. * @return the updated UriBuilder * @throws IllegalArgumentException * if query cannot be parsed * @see javax.ws.rs.core.UriBuilder#replaceQuery(java.lang.String) */ @Override public UriBuilder replaceQuery(String query) throws IllegalArgumentException { if ((query == null) || (query.length() == 0)) { this.query = null; } else { this.query = EncodeOrCheck.fullQuery(query, true); } return this; } /** * @see javax.ws.rs.core.UriBuilder#replaceQueryParam(String, Object[]) */ @Override public UriBuilder replaceQueryParam(String name, Object... values) throws IllegalArgumentException { throw new NotYetImplementedException( "Sorry, the relacement of query parameters is not supported yet"); } /** * Set the URI scheme. * * @param scheme * the URI scheme, may contain URI template parameters * @return the updated UriBuilder * @throws IllegalArgumentException * if scheme is invalid or is null * @see javax.ws.rs.core.UriBuilder#scheme(java.lang.String) */ @Override public UriBuilder scheme(String scheme) throws IllegalArgumentException { this.scheme = EncodeOrCheck.scheme(scheme); return this; } /** * Set the URI scheme-specific-part (see {@link java.net.URI}). This method * will overwrite any existing values for authority, user-info, host, port * and path. * * @param ssp * the URI scheme-specific-part, may contain URI template * parameters * @return the updated UriBuilder * @throws IllegalArgumentException * if ssp cannot be parsed or is null * @see javax.ws.rs.core.UriBuilder#schemeSpecificPart(java.lang.String) */ @Override public UriBuilder schemeSpecificPart(String ssp) throws IllegalArgumentException { if (ssp == null) { throw new IllegalArgumentException( "The scheme specific part must not be null"); } if (ssp.startsWith("//")) { ssp = ssp.substring(2); } // split schemeSpecificPart final int firstSlashPos = ssp.indexOf('/'); String authority; CharSequence path; CharSequence query; CharSequence fragment; if (firstSlashPos >= 0) { authority = ssp.substring(0, firstSlashPos); final String pathQueryFragment = ssp.substring(firstSlashPos); String pathQuery; final int firstCrosshatchPos = pathQueryFragment.indexOf('#'); if (firstCrosshatchPos >= 0) { pathQuery = pathQueryFragment.substring(0, firstCrosshatchPos); fragment = pathQueryFragment.substring(firstCrosshatchPos + 1); } else { pathQuery = pathQueryFragment; fragment = null; } final int firstQmPos = pathQuery.indexOf('?'); if (firstQmPos >= 0) { path = pathQuery.substring(0, firstQmPos); query = pathQuery.substring(firstQmPos + 1); } else { path = pathQuery; query = null; } } else { authority = ssp; path = null; query = null; fragment = null; } CharSequence userInfo; String host; String port; final int atSignPos = authority.lastIndexOf('@'); if (atSignPos >= 0) { userInfo = authority.substring(0, atSignPos); authority = authority.substring(atSignPos + 1); } else { userInfo = null; } final int colonPos = authority.lastIndexOf(':'); if (colonPos >= 0) { host = authority.substring(0, colonPos); port = authority.substring(colonPos + 1); } else { host = authority; port = null; } // check / convert values if (userInfo != null) { userInfo = EncodeOrCheck.userInfo(userInfo, true); } if (host != null) { host = EncodeOrCheck.host(host); } if (path != null) { path = EncodeOrCheck.pathSegmentsWithMatrix(path, true); } if (query != null) { query = EncodeOrCheck.fullQuery(query, true); } if (fragment != null) { fragment = EncodeOrCheck.fragment(fragment); } // check and set max. one: the port port(port); // set checked / converted this.userInfo = userInfo; this.host = host; this.replacePath(path); this.query = query; this.fragment = fragment; return this; } /** * Append path segments to the existing path. When constructing the final * path, a '/' separator will be inserted between the existing path and the * first path segment if necessary and each supplied segment will also be * separated by '/'. Existing '/' characters are encoded thus a single value * can only represent a single URI path segment. * * @param segments * the path segment values, each may contain URI template * parameters * @return the updated UriBuilder * @throws IllegalArgumentException * if segments or any element of segments is null * @see javax.ws.rs.core.UriBuilder#segment(java.lang.String[]) */ @Override public UriBuilder segment(String... segments) throws IllegalArgumentException { if (segments == null) { throw new IllegalArgumentException("The segments must not be null"); } // first check preconditions final List newPathSegments = pathSegmentsWithMatrix(segments); // than add addValidPathSegments(newPathSegments); return this; } /** * Returns the actual URI as String. * * @return the actual URI as String. * @see #toStringWithCheck(boolean) */ @Override public String toString() { return this.toString(false); } /** * Returns the actual URI as String. * * @param convertBraces * if true, all braces are converted, if false then not. * * @return the actual URI as {@link String}. Never returns null. * @see #toStringWithCheck(boolean) */ private String toString(boolean convertBraces) { try { final StringBuilder stb = new StringBuilder(); if (this.scheme != null) { append(stb, this.scheme, convertBraces); stb.append("://"); } if (this.userInfo != null) { append(stb, this.userInfo, convertBraces); stb.append('@'); } if (this.host != null) { append(stb, this.host, convertBraces); } if (this.port != null) { stb.append(':'); stb.append(this.port); } String extension = getExtension(); CharSequence thisPath = this.path; if (thisPath != null || extension != null) { if (stb.length() > 0) { if (notStartsWith(thisPath, '/') || ((thisPath == null) && (extension != null))) { stb.append('/'); } } if (extension == null) { append(stb, thisPath, convertBraces); } else { int begLastMatrix = indexBeginMatrixOfLastSegment(thisPath); if (begLastMatrix >= 0) { append(stb, thisPath, convertBraces, 0, begLastMatrix); append(stb, extension, convertBraces); append(stb, thisPath, convertBraces, begLastMatrix); } else { // no matrix parameters found append(stb, thisPath, convertBraces); append(stb, extension, convertBraces); } } } if (this.query != null) { stb.append('?'); append(stb, this.query, convertBraces); } if (this.fragment != null) { stb.append('#'); append(stb, this.fragment, convertBraces); } return stb.toString(); } catch (IOException e) { throw new RuntimeException( "Could not write the UriBuilder to a String; but this Exception could not occur normally", e); } } /** * Returns the actual URI as String. Check for valid scheme and host before * * @param convertBraces * if true, all braces are converted, if false then not. * * @return the actual URI as String. * @see #toString() */ private String toStringWithCheck(boolean convertBraces) { if (this.host == null) { if (this.port != null) { throw new UriBuilderException( "You must set a host, if you set a port"); } if ((this.userInfo != null) && (this.userInfo.length() >= 0)) { throw new UriBuilderException( "You must set a host, if you set a userInfo"); } } return toString(convertBraces); } /** * Copies the non-null components of the supplied URI to the UriBuilder * replacing any existing values for those components. * * @param uri * the URI to copy components from * @return the updated UriBuilder * @throws IllegalArgumentException * if uri is null * @see javax.ws.rs.core.UriBuilder#uri(java.net.URI) */ @Override public UriBuilder uri(URI uri) throws IllegalArgumentException { if (uri == null) { throw new IllegalArgumentException("The URI must not be null"); } if (uri.getScheme() != null) { this.scheme = uri.getScheme(); } if (uri.getHost() != null) { this.host = uri.getHost(); } this.port(uri.getPort()); if (uri.getRawUserInfo() != null) { this.userInfo = uri.getRawUserInfo(); } if (uri.getRawPath() != null) { this.replacePath(uri.getRawPath()); } if (uri.getRawQuery() != null) { this.query = uri.getRawQuery(); } if (uri.getRawFragment() != null) { this.fragment = uri.getRawFragment(); } return this; } /** * Set the URI user-info. * * @param userInfo * the URI user-info, may contain URI template parameters * @return the updated UriBuilder * @throws IllegalArgumentException * if automatic encoding is disabled and the userInfo contains * illegal characters, or if the userInfo is null. * @see javax.ws.rs.core.UriBuilder#userInfo(java.lang.String) */ @Override public UriBuilder userInfo(String userInfo) throws IllegalArgumentException { if (userInfo == null) { this.userInfo = null; } else { this.userInfo = EncodeOrCheck.userInfo(userInfo, true); } return this; } } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/ObjectFactory.java0000664000175000017500000000467011757206350030536 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; /** *

* Implement this interface to instantiate JAX-RS root resource classes and * providers yourself and register it by * {@link JaxRsApplication#setObjectFactory(ObjectFactory)}. *

*

* When using a ObjectFactory, no JAX-RS constructor dependency injection will * be performed, but instance variable and bean setter injection will still be * done. *

* * @author Bruno Dumon * @see JaxRsApplication#setObjectFactory(ObjectFactory) * @see JaxRsRestlet#setObjectFactory(ObjectFactory) */ public interface ObjectFactory { /** * Creates an instance of the given class.
* If the concrete instance could not instantiate the given class, it could * return null. Than the constructor specified by the JAX-RS specification * (section 4.2) is used. * * @param * @param jaxRsClass * the root resource class or provider class. * @return The created instance. * @throws InstantiateException */ public T getInstance(Class jaxRsClass) throws InstantiateException; // LATER if a resource class is a singelton, it must be ensured, that it // has no @*Param on fields and perhaps bean setters. } restlet-2.0.14/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/InstantiateException.java0000664000175000017500000000452111757206350032135 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import java.lang.reflect.Method; /** * Thrown if a provider, a root resource class or a resource class could not be * instantiated. * * @author Stephan Koops */ public class InstantiateException extends Exception { private static final long serialVersionUID = 951579935427584482L; /** * Use this constructor, if a resource class could not be instantiated. * * @param executeMethod * the resource method that should create the resource object. * @param cause */ public InstantiateException(Method executeMethod, Throwable cause) { super("The method " + executeMethod + " could not instantiate a resource class", cause); } /** * @param message */ public InstantiateException(String message) { super(message); } /** * @param message * @param cause */ public InstantiateException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public InstantiateException(Throwable cause) { super(cause); } } restlet-2.0.14/org.restlet.ext.slf4j/0000775000175000017500000000000012001473175020024 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.slf4j/pom.xml0000600000175000017500000000156612001473175021337 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.slf4j Restlet Extension - SLF4J Support for the SLF4J logging bridge. org.slf4j slf4j-api 1.5.8 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.slf4j/src/0000775000175000017500000000000012001473175020613 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.slf4j/src/META-INF/0000775000175000017500000000000011757206452021764 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.slf4j/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023415 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.slf4j/src/org/0000775000175000017500000000000011757206352021412 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.slf4j/src/org/restlet/0000775000175000017500000000000011757206352023074 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.slf4j/src/org/restlet/ext/0000775000175000017500000000000011757206352023674 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.slf4j/src/org/restlet/ext/slf4j/0000775000175000017500000000000011757206352024716 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.slf4j/src/org/restlet/ext/slf4j/Slf4jLogger.java0000664000175000017500000002117311757206352027707 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.slf4j; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * JULI logger that efficiently wraps a SLF4J logger. It prevents the creation * of intermediary {@link LogRecord} objects in favor of direct calls to the * SLF4J API. * * @author Jerome Louvel */ public class Slf4jLogger extends Logger { /** The wrapped SLF4J logger. */ private org.slf4j.Logger slf4jLogger; /** * Constructor. * * @param slf4jLogger * The SLF4J logger to wrap. */ public Slf4jLogger(org.slf4j.Logger slf4jLogger) { super(slf4jLogger.getName(), null); this.slf4jLogger = slf4jLogger; } /** * Constructor. * * @param name * The logger name. * @param resourceBundleName * The optional resource bundle name. */ protected Slf4jLogger(String name, String resourceBundleName) { super(name, resourceBundleName); } /** * Logs a configuration message. By default, it invokes * {@link org.slf4j.Logger#debug(String)}. * * @param msg * The message to log. */ @Override public void config(String msg) { getSlf4jLogger().debug(msg); } /** * Logs a fine trace. By default, it invokes * {@link org.slf4j.Logger#debug(String)}. * * @param msg * The message to log. */ @Override public void fine(String msg) { getSlf4jLogger().debug(msg); } /** * Logs a finer trace. By default, it invokes * {@link org.slf4j.Logger#trace(String)}. * * @param msg * The message to log. */ @Override public void finer(String msg) { getSlf4jLogger().trace(msg); } /** * Logs a finest trace. By default, it invokes * {@link org.slf4j.Logger#trace(String)}. * * @param msg * The message to log. */ @Override public void finest(String msg) { getSlf4jLogger().trace(msg); } /** * Returns the wrapped SLF4J logger. * * @return The wrapped SLF4J logger. */ public org.slf4j.Logger getSlf4jLogger() { return slf4jLogger; } /** * Logs an info message. By default, it invokes * {@link org.slf4j.Logger#info(String)}. * * @param msg * The message to log. */ @Override public void info(String msg) { getSlf4jLogger().info(msg); } @Override public boolean isLoggable(Level level) { if (Level.ALL == level) { return true; } else if (Level.CONFIG == level) { return getSlf4jLogger().isDebugEnabled(); } else if (Level.FINE == level) { return getSlf4jLogger().isDebugEnabled(); } else if (Level.FINER == level) { return getSlf4jLogger().isTraceEnabled(); } else if (Level.FINEST == level) { return getSlf4jLogger().isTraceEnabled(); } else if (Level.INFO == level) { return getSlf4jLogger().isInfoEnabled(); } else if (Level.OFF == level) { return false; } else if (Level.SEVERE == level) { return getSlf4jLogger().isErrorEnabled(); } else if (Level.WARNING == level) { return getSlf4jLogger().isWarnEnabled(); } else { return false; } } @Override public void log(Level level, String msg) { if (Level.CONFIG == level) { getSlf4jLogger().debug(msg); } else if (Level.FINE == level) { getSlf4jLogger().debug(msg); } else if (Level.FINER == level) { getSlf4jLogger().trace(msg); } else if (Level.FINEST == level) { getSlf4jLogger().trace(msg); } else if (Level.INFO == level) { getSlf4jLogger().info(msg); } else if (Level.SEVERE == level) { getSlf4jLogger().error(msg); } else if (Level.WARNING == level) { getSlf4jLogger().warn(msg); } } @Override public void log(Level level, String msg, Object param) { if (Level.CONFIG == level) { getSlf4jLogger().debug(msg, param); } else if (Level.FINE == level) { getSlf4jLogger().debug(msg, param); } else if (Level.FINER == level) { getSlf4jLogger().trace(msg, param); } else if (Level.FINEST == level) { getSlf4jLogger().trace(msg, param); } else if (Level.INFO == level) { getSlf4jLogger().info(msg, param); } else if (Level.SEVERE == level) { getSlf4jLogger().error(msg, param); } else if (Level.WARNING == level) { getSlf4jLogger().warn(msg, param); } } @Override public void log(Level level, String msg, Object[] params) { if (Level.CONFIG == level) { getSlf4jLogger().debug(msg, params); } else if (Level.FINE == level) { getSlf4jLogger().debug(msg, params); } else if (Level.FINER == level) { getSlf4jLogger().trace(msg, params); } else if (Level.FINEST == level) { getSlf4jLogger().trace(msg, params); } else if (Level.INFO == level) { getSlf4jLogger().info(msg, params); } else if (Level.SEVERE == level) { getSlf4jLogger().error(msg, params); } else if (Level.WARNING == level) { getSlf4jLogger().warn(msg, params); } } @Override public void log(Level level, String msg, Throwable thrown) { if (Level.CONFIG == level) { getSlf4jLogger().debug(msg, thrown); } else if (Level.FINE == level) { getSlf4jLogger().debug(msg, thrown); } else if (Level.FINER == level) { getSlf4jLogger().trace(msg, thrown); } else if (Level.FINEST == level) { getSlf4jLogger().trace(msg, thrown); } else if (Level.INFO == level) { getSlf4jLogger().info(msg, thrown); } else if (Level.SEVERE == level) { getSlf4jLogger().error(msg, thrown); } else if (Level.WARNING == level) { getSlf4jLogger().warn(msg, thrown); } } @Override public void log(LogRecord record) { Level level = record.getLevel(); String msg = record.getMessage(); Object[] params = record.getParameters(); Throwable thrown = record.getThrown(); if (thrown != null) { log(level, msg, thrown); } else if (params != null) { log(level, msg, params); } else { log(level, msg); } } /** * Sets the wrapped SLF4J logger. * * @param slf4jLogger * The wrapped SLF4J logger. */ public void setSlf4jLogger(org.slf4j.Logger slf4jLogger) { this.slf4jLogger = slf4jLogger; } /** * Logs a severe message. By default, it invokes * {@link org.slf4j.Logger#error(String)}. * * @param msg * The message to log. */ @Override public void severe(String msg) { getSlf4jLogger().error(msg); } /** * Logs a warning message. By default, it invokes * {@link org.slf4j.Logger#warn(String)}. * * @param msg * The message to log. */ @Override public void warning(String msg) { getSlf4jLogger().warn(msg); } } restlet-2.0.14/org.restlet.ext.slf4j/src/org/restlet/ext/slf4j/package.html0000664000175000017500000000044011757206352027175 0ustar jamespagejamespage Integration with SLF4J 1.5. This extension provides a log facade for SLF4J for the Restlet engine, allowing bridges to alternate logging mechanisms such as Log4J or LogBack. @since Restlet 2.0 @see SLF4J home restlet-2.0.14/org.restlet.ext.slf4j/src/org/restlet/ext/slf4j/Slf4jLoggerFacade.java0000664000175000017500000000467411757206352031002 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.slf4j; import java.util.logging.Logger; import org.restlet.engine.log.LoggerFacade; import org.slf4j.LoggerFactory; /** * Restlet log facade for the SLF4J {@link LoggerFactory}. In order to use SLF4J * as the logging facade for Restlet, you need to set the * "org.restlet.engine.loggerFacadeClass" system property with the * "org.restlet.ext.slf4j.Slf4jLoggerFacade" value. * * @see Slf4jLogger * @author Jerome Louvel */ public class Slf4jLoggerFacade extends LoggerFacade { /** * Returns an instance of {@link Slf4jLogger}, wrapping the result of * {@link LoggerFactory#getLogger(String)} where the logger name is "". * * @return An anonymous logger. */ @Override public Logger getAnonymousLogger() { return new Slf4jLogger(LoggerFactory.getLogger("")); } /** * Returns an instance of {@link Slf4jLogger}, wrapping the result of * {@link LoggerFactory#getLogger(String)} with the logger name. * * @param loggerName * The logger name. * @return An anonymous logger. */ @Override public Logger getLogger(String loggerName) { return new Slf4jLogger(LoggerFactory.getLogger(loggerName)); } } restlet-2.0.14/org.restlet.ext.httpclient/0000775000175000017500000000000012001473141021151 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/pom.xml0000600000175000017500000000340112001473141022452 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.httpclient Restlet Extension - Apache HTTP Client Integration with Apache Commons HTTP Client. commons-codec commons-codec 1.4 org.apache.httpcomponents httpclient 4.0.1 org.apache.httpcomponents httpcore 4.0.1 org.apache.httpcomponents httpmime 4.0.1 net.jcip jcip-annotations 1.0 commons-logging commons-logging 1.1.1 org.apache.james apache-mime4j 0.6 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.httpclient/src/0000775000175000017500000000000012001473141021740 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/src/META-INF/0000775000175000017500000000000011757206450023116 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/src/META-INF/services/0000775000175000017500000000000011757206346024745 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/src/META-INF/services/org.restlet.engine.ClientHelper0000664000175000017500000000007411757206346032762 0ustar jamespagejamespageorg.restlet.ext.httpclient.HttpClientHelper # HTTP, HTTPS restlet-2.0.14/org.restlet.ext.httpclient/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446024556 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.httpclient/src/org/0000775000175000017500000000000011757206346022551 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/0000775000175000017500000000000011757206346024233 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/0000775000175000017500000000000011757206346025033 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/0000775000175000017500000000000011757206346027211 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/HttpClientHelper.java0000664000175000017500000004067211757206346033303 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.httpclient; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.net.ssl.SSLContext; import org.apache.http.HttpHost; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.cookie.CookieSpecRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.restlet.Client; import org.restlet.Request; import org.restlet.data.Protocol; import org.restlet.engine.Engine; import org.restlet.engine.http.ClientCall; import org.restlet.engine.security.SslContextFactory; import org.restlet.engine.security.SslUtils; import org.restlet.ext.httpclient.internal.HttpIdleConnectionReaper; import org.restlet.ext.httpclient.internal.HttpMethodCall; import org.restlet.ext.httpclient.internal.IgnoreCookieSpecFactory; /** * HTTP client connector using the HttpMethodCall and Apache HTTP Client * project. Note that the response must be fully read in all cases in order to * surely release the underlying connection. Not doing so may cause future * requests to block.
*
* Here is the list of parameters that are supported. They should be set in the * Client's context before it is started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Parameter nameValue typeDefault valueDescription
followRedirectsbooleanfalseIf true, the protocol will automatically follow redirects. If false, the * protocol will not automatically follow redirects.
idleCheckIntervalint0Time between checks for idle and expired connections. The check happens * only if this property is set to a value greater than 0.
idleTimeoutlong10000Returns the time in ms beyond which idle connections are eligible for * reaping. The default value is 10000 ms.
maxConnectionsPerHostint10The maximum number of connections that will be created for any particular * host.
maxTotalConnectionsint20 (uses HttpClient's default)The maximum number of active connections.
proxyHostStringSystem property "http.proxyHost"The host name of the HTTP proxy.
proxyPortintSystem property "http.proxyPort" or "3128"The port of the HTTP proxy.
stopIdleTimeoutint1000The minimum idle time, in milliseconds, for connections to be closed when * stopping the connector.
socketTimeoutint0Sets the socket timeout to a specified timeout, in milliseconds. A * timeout of zero is interpreted as an infinite timeout.
retryHandlerStringnullClass name of the retry handler to use instead of HTTP Client default * behavior. The given class name must extend the * org.apache.http.client.HttpRequestRetryHandler class and have a default * constructor
tcpNoDelaybooleanfalseIndicate if Nagle's TCP_NODELAY algorithm should be used.
* * @see Apache HTTP Client tutorial * @see Networking * Features * @author Jerome Louvel */ public class HttpClientHelper extends org.restlet.engine.http.HttpClientHelper { private volatile DefaultHttpClient httpClient; /** the idle connection reaper. */ private volatile HttpIdleConnectionReaper idleConnectionReaper; /** * Constructor. * * @param client * The client to help. */ public HttpClientHelper(Client client) { super(client); this.httpClient = null; getProtocols().add(Protocol.HTTP); getProtocols().add(Protocol.HTTPS); } /** * Configures the HTTP client. By default, it try to set the retry handler. * * @param httpClient * The HTTP client to configure. */ protected void configure(DefaultHttpClient httpClient) { if (getRetryHandler() != null) { try { HttpRequestRetryHandler retryHandler = (HttpRequestRetryHandler) Engine .loadClass(getRetryHandler()).newInstance(); this.httpClient.setHttpRequestRetryHandler(retryHandler); } catch (Exception e) { getLogger() .log(Level.WARNING, "An error occurred during the instantiation of the retry handler.", e); } } CookieSpecRegistry csr = new CookieSpecRegistry(); csr.register("ignore", new IgnoreCookieSpecFactory()); this.httpClient.setCookieSpecs(csr); } /** * Configures the various parameters of the connection manager and the HTTP * client. * * @param params * The parameter list to update. */ protected void configure(HttpParams params) { ConnManagerParams.setMaxTotalConnections(params, getMaxTotalConnections()); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(getMaxConnectionsPerHost())); // Configure other parameters HttpClientParams.setAuthenticating(params, false); HttpClientParams.setRedirecting(params, isFollowRedirects()); HttpClientParams.setCookiePolicy(params, "ignore"); HttpConnectionParams.setTcpNoDelay(params, getTcpNoDelay()); HttpConnectionParams.setConnectionTimeout(params, getConnectTimeout()); HttpConnectionParams.setSoTimeout(params, getSocketTimeout()); String httpProxyHost = getProxyHost(); if (httpProxyHost != null) { HttpHost proxy = new HttpHost(httpProxyHost, getProxyPort()); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } } /** * Configures the scheme registry. By default, it registers the HTTP and the * HTTPS schemes. * * @param schemeRegistry * The scheme registry to configure. */ protected void configure(SchemeRegistry schemeRegistry) { schemeRegistry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); SSLSocketFactory sslSocketFactory = null; SslContextFactory sslContextFactory = SslUtils .getSslContextFactory(this); if (sslContextFactory != null) { try { SSLContext sslContext = sslContextFactory.createSslContext(); sslSocketFactory = new SSLSocketFactory(sslContext); } catch (Exception e) { throw new RuntimeException("Unable to create SSLContext.", e); } } else { sslSocketFactory = SSLSocketFactory.getSocketFactory(); } schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); } /** * Creates a low-level HTTP client call from a high-level uniform call. * * @param request * The high-level request. * @return A low-level HTTP client call. */ @Override public ClientCall create(Request request) { ClientCall result = null; try { result = new HttpMethodCall(this, request.getMethod().toString(), request.getResourceRef().toString(), request.isEntityAvailable()); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to create the HTTP client call", ioe); } return result; } /** * Creates the connection manager. By default, it creates a thread safe * connection manager. * * @param params * The configuration parameters. * @param schemeRegistry * The scheme registry to use. * @return The created connection manager. */ protected ClientConnectionManager createClientConnectionManager( HttpParams params, SchemeRegistry schemeRegistry) { return new ThreadSafeClientConnManager(params, schemeRegistry); } /** * Returns the wrapped Apache HTTP Client. * * @return The wrapped Apache HTTP Client. */ public HttpClient getHttpClient() { return this.httpClient; } /** * Time in milliseconds between two checks for idle and expired connections. * The check happens only if this property is set to a value greater than 0. * * @return A value indicating the idle connection check interval or 0 if a * value has not been provided * @see #getIdleTimeout() */ public long getIdleCheckInterval() { return Long.parseLong(getHelpedParameters().getFirstValue( "idleCheckInterval", "0")); } /** * Returns the time in ms beyond which idle connections are eligible for * reaping. The default value is 10000 ms. * * @return The time in millis beyond which idle connections are eligible for * reaping. * @see #getIdleCheckInterval() */ public long getIdleTimeout() { return Long.parseLong(getHelpedParameters().getFirstValue( "idleTimeout", "10000")); } /** * Returns the maximum number of connections that will be created for any * particular host. * * @return The maximum number of connections that will be created for any * particular host. */ public int getMaxConnectionsPerHost() { return Integer.parseInt(getHelpedParameters().getFirstValue( "maxConnectionsPerHost", "10")); } /** * Returns the maximum number of active connections. * * @return The maximum number of active connections. */ public int getMaxTotalConnections() { return Integer.parseInt(getHelpedParameters().getFirstValue( "maxTotalConnections", "20")); } /** * Returns the host name of the HTTP proxy, if specified. * * @return the host name of the HTTP proxy, if specified. */ public String getProxyHost() { return getHelpedParameters().getFirstValue("proxyHost", System.getProperty("http.proxyHost")); } /** * Returns the port of the HTTP proxy, if specified, 3128 otherwise. * * @return the port of the HTTP proxy. */ public int getProxyPort() { return Integer.parseInt(getHelpedParameters().getFirstValue( "proxyPort", System.getProperty("http.proxyPort", "3128"))); } /** * Returns the class name of the retry handler to use instead of HTTP Client * default behavior. The given class name must implement the * org.apache.commons.httpclient.HttpMethodRetryHandler interface and have a * default constructor. * * @return The class name of the retry handler. */ public String getRetryHandler() { return getHelpedParameters().getFirstValue("retryHandler", null); } /** * Returns the socket timeout value. A timeout of zero is interpreted as an * infinite timeout. * * @return The read timeout value. */ public int getSocketTimeout() { return Integer.parseInt(getHelpedParameters().getFirstValue( "socketTimeout", "0")); } /** * Returns the minimum idle time, in milliseconds, for connections to be * closed when stopping the connector. * * @return The minimum idle time, in milliseconds, for connections to be * closed when stopping the connector. */ public int getStopIdleTimeout() { return Integer.parseInt(getHelpedParameters().getFirstValue( "stopIdleTimeout", "1000")); } /** * Indicates if the protocol will use Nagle's algorithm * * @return True to enable TCP_NODELAY, false to disable. * @see java.net.Socket#setTcpNoDelay(boolean) */ public boolean getTcpNoDelay() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "tcpNoDelay", "false")); } /** * Indicates if the protocol will automatically follow redirects. * * @return True if the protocol will automatically follow redirects. */ public boolean isFollowRedirects() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "followRedirects", "false")); } /** * Sets the idle connections reaper. * * @param connectionReaper * The idle connections reaper. */ public void setIdleConnectionReaper( HttpIdleConnectionReaper connectionReaper) { this.idleConnectionReaper = connectionReaper; } @Override public void start() throws Exception { super.start(); // Define configuration parameters HttpParams params = new BasicHttpParams(); configure(params); // Set-up the scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); configure(schemeRegistry); // Create the connection manager ClientConnectionManager connectionManager = createClientConnectionManager( params, schemeRegistry); // Create and configure the HTTP client this.httpClient = new DefaultHttpClient(connectionManager, params); configure(this.httpClient); if (this.idleConnectionReaper != null) { // If a previous reaper is present, stop it this.idleConnectionReaper.stop(); } this.idleConnectionReaper = new HttpIdleConnectionReaper(httpClient, getIdleCheckInterval(), getIdleTimeout()); getLogger().info("Starting the HTTP client"); } @Override public void stop() throws Exception { if (this.idleConnectionReaper != null) { this.idleConnectionReaper.stop(); } getHttpClient().getConnectionManager().closeExpiredConnections(); getHttpClient().getConnectionManager().closeIdleConnections( getStopIdleTimeout(), TimeUnit.MILLISECONDS); getHttpClient().getConnectionManager().shutdown(); getLogger().info("Stopping the HTTP client"); } } restlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/0000775000175000017500000000000011757206346031025 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/HttpMethodCall.javarestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/HttpMethodCall.jav0000664000175000017500000003047211757206346034411 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.httpclient.internal; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.logging.Level; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpTrace; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.message.BasicHeader; import org.restlet.Request; import org.restlet.Response; import org.restlet.Uniform; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.http.ClientCall; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.ext.httpclient.HttpClientHelper; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * HTTP client connector call based on Apache HTTP Client's HttpMethod class. * * @author Jerome Louvel */ public class HttpMethodCall extends ClientCall { /** The associated HTTP client. */ private volatile HttpClientHelper clientHelper; /** The wrapped HTTP request. */ private volatile HttpUriRequest httpRequest; /** The wrapped HTTP response. */ private volatile HttpResponse httpResponse; /** Indicates if the response headers were added. */ private volatile boolean responseHeadersAdded; /** * Constructor. * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. * @param hasEntity * Indicates if the call will have an entity to send to the * server. * @throws IOException */ public HttpMethodCall(HttpClientHelper helper, final String method, final String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); this.clientHelper = helper; if (requestUri.startsWith("http")) { if (method.equalsIgnoreCase(Method.GET.getName())) { this.httpRequest = new HttpGet(requestUri); } else if (method.equalsIgnoreCase(Method.POST.getName())) { this.httpRequest = new HttpPost(requestUri); } else if (method.equalsIgnoreCase(Method.PUT.getName())) { this.httpRequest = new HttpPut(requestUri); } else if (method.equalsIgnoreCase(Method.HEAD.getName())) { this.httpRequest = new HttpHead(requestUri); } else if (method.equalsIgnoreCase(Method.DELETE.getName())) { this.httpRequest = new HttpDelete(requestUri); } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) { this.httpRequest = new HttpOptions(requestUri); } else if (method.equalsIgnoreCase(Method.TRACE.getName())) { this.httpRequest = new HttpTrace(requestUri); } else { this.httpRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } @Override public URI getURI() { try { return new URI(requestUri); } catch (URISyntaxException e) { getLogger().log(Level.WARNING, "Invalid URI syntax", e); return null; } } }; } this.responseHeadersAdded = false; setConfidential(this.httpRequest.getURI().getScheme() .equalsIgnoreCase(Protocol.HTTPS.getSchemeName())); } else { throw new IllegalArgumentException( "Only HTTP or HTTPS resource URIs are allowed here"); } } /** * Returns the HTTP request. * * @return The HTTP request. */ public HttpUriRequest getHttpRequest() { return this.httpRequest; } /** * Returns the HTTP response. * * @return The HTTP response. */ public HttpResponse getHttpResponse() { return this.httpResponse; } /** * Returns the response reason phrase. * * @return The response reason phrase. */ @Override public String getReasonPhrase() { return (getHttpResponse() == null) ? null : getHttpResponse() .getStatusLine().getReasonPhrase(); } @Override public WritableByteChannel getRequestEntityChannel() { return null; } @Override public OutputStream getRequestEntityStream() { return null; } @Override public OutputStream getRequestHeadStream() { return null; } @Override public ReadableByteChannel getResponseEntityChannel(long size) { return null; } @Override public InputStream getResponseEntityStream(long size) { InputStream result = null; try { // Return a wrapper filter that will release the connection when // needed InputStream responseStream = (getHttpResponse() == null) ? null : (getHttpResponse().getEntity() == null) ? null : getHttpResponse().getEntity().getContent(); if (responseStream != null) { result = new FilterInputStream(responseStream) { @Override public void close() throws IOException { super.close(); getHttpResponse().getEntity().consumeContent(); } }; } } catch (IOException ioe) { } return result; } /** * Returns the modifiable list of response headers. * * @return The modifiable list of response headers. */ @Override public Series getResponseHeaders() { Series result = super.getResponseHeaders(); if (!this.responseHeadersAdded) { if ((getHttpResponse() != null) && (getHttpResponse().getAllHeaders() != null)) { for (Header header : getHttpResponse().getAllHeaders()) { result.add(header.getName(), header.getValue()); } } this.responseHeadersAdded = true; } return result; } /** * Returns the response address.
* Corresponds to the IP address of the responding server. * * @return The response address. */ @Override public String getServerAddress() { return getHttpRequest().getURI().getHost(); } /** * Returns the response status code. * * @return The response status code. */ @Override public int getStatusCode() { return (getHttpResponse() == null) ? null : getHttpResponse() .getStatusLine().getStatusCode(); } /** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * * @param request * The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (Parameter header : getRequestHeaders()) { if (!header.getName().equals( HeaderConstants.HEADER_CONTENT_LENGTH)) { getHttpRequest().addHeader(header.getName(), header.getValue()); } } // For those method that accept enclosing entities, provide it if ((entity != null) && (getHttpRequest() instanceof HttpEntityEnclosingRequestBase)) { final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) getHttpRequest(); eem.setEntity(new AbstractHttpEntity() { public InputStream getContent() throws IOException, IllegalStateException { return entity.getStream(); } public long getContentLength() { return entity.getSize(); } public Header getContentType() { return new BasicHeader( HeaderConstants.HEADER_CONTENT_TYPE, (entity .getMediaType() != null) ? entity .getMediaType().toString() : null); } public boolean isRepeatable() { return !entity.isTransient(); } public boolean isStreaming() { return (entity.getSize() == Representation.UNKNOWN_SIZE); } public void writeTo(OutputStream os) throws IOException { entity.write(os); os.flush(); } }); } // Ensure that the connection is active this.httpResponse = this.clientHelper.getHttpClient().execute( getHttpRequest()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); } catch (IOException ioe) { this.clientHelper .getLogger() .log(Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); // Release the connection getHttpRequest().abort(); } return result; } @Override public void sendRequest(Request request, Response response, Uniform callback) throws Exception { // Send the request sendRequest(request); if (request.getOnSent() != null) { request.getOnSent().handle(request, response); } if (callback != null) { // Transmit to the callback, if any. callback.handle(request, response); } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/HttpIdleConnectionReaper.javarestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/HttpIdleConnection0000664000175000017500000001550111757206346034507 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.httpclient.internal; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.http.client.HttpClient; /** * Class that embodies a Reaper thread that reaps idle connections. Note that * the thread won't be started if the value of the idleCheckInterval parameter * is equal to 0. * * @author Sanjay Acharya */ public class HttpIdleConnectionReaper { /** * Thread that reaps idle and expired connections. */ private class ReaperThread extends Thread { /** Indicates if the thread is shut down. */ private volatile boolean shutdown; /** CountDownLatch used when stopping the thread. */ private final CountDownLatch shutdownLatch = new CountDownLatch(1); /** CountDownLatch used when starting the thread. */ private final CountDownLatch startupLatch = new CountDownLatch(1); @Override public void run() { try { startupLatch.countDown(); // While shutdown has not been called and the thread has not // been interrupted do the following. while (!shutdown && !isInterrupted()) { try { Thread.sleep(idleCheckInterval); } catch (InterruptedException interrupted) { continue; } httpClient.getConnectionManager().closeExpiredConnections(); httpClient.getConnectionManager().closeIdleConnections( idleTimeOut, TimeUnit.MILLISECONDS); } } finally { shutdownLatch.countDown(); } } /** * Tells the reaper thread the maximum time to wait before starting. * * @param millis * The maximum time to wait before starting the thread. * @throws InterruptedException * If the current thread was interrupted. */ void waitForStart(long millis) throws InterruptedException { startupLatch.await(millis, TimeUnit.MILLISECONDS); } /** * Tells the reaper thread the maximum time to wait before stopping. * * @param millis * The maximum time to wait before stopping the thread. * @throws InterruptedException * If the current thread was interrupted. */ void waitForStop(long millis) throws InterruptedException { shutdownLatch.await(millis, TimeUnit.MILLISECONDS); } } /** The HttpClient for which this is the reaper. */ private final HttpClient httpClient; /** The time to sleep between checks for idle connections. */ private final long idleCheckInterval; /** The age of connections to reap. */ private final long idleTimeOut; /** The thread that gleans the idle connections. */ private final ReaperThread reaperThread; /** * Constructor. * * @param httpClient * The HttpClient for which this is the reaper. * @param idleCheckInterval * The time to sleep between checks for idle connections. Note * that if this is 0, then reaping won't occur. * @param idleTimeout * The age of connections to reap. */ public HttpIdleConnectionReaper(HttpClient httpClient, long idleCheckInterval, long idleTimeout) { if (httpClient == null) { throw new IllegalArgumentException( "HttpClient is a required parameter"); } this.httpClient = httpClient; this.idleCheckInterval = idleCheckInterval; this.idleTimeOut = idleTimeout; this.reaperThread = idleCheckInterval > 0L ? new ReaperThread() : null; if (reaperThread != null) { reaperThread.start(); } } /** * Returns {@code true} if the reaper is started. * * @return {@code true} If the reaper is started. */ public boolean isStarted() { return reaperThread != null && reaperThread.isAlive(); } /** * Returns {@code true} if the reaper is stopped. * * @return {@code true} if the reaper is stopped. */ public boolean isStopped() { return (reaperThread != null || !reaperThread.isAlive()); } /** * Stops the Idle Connection Reaper if running. * * @throws InterruptedException * If the call to stop was interrupted */ public void stop() throws InterruptedException { if (reaperThread == null) { return; } reaperThread.shutdown = true; reaperThread.interrupt(); // Wait for a second to join reaperThread.join(1000L); } /** * Tells the reaper thread the maximum time to wait before starting. * * @param millis * The maximum time to wait before starting the thread. * @throws InterruptedException * If the current thread was interrupted. */ public void waitForReaperStart(long millis) throws InterruptedException { reaperThread.waitForStart(millis); } /** * Tells the reaper thread the maximum time to wait before stopping. * * @param millis * The maximum time to wait before stopping the thread. * @throws InterruptedException * If the current thread was interrupted. */ public void waitForReaperStop(long millis) throws InterruptedException { reaperThread.waitForStop(millis); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/IgnoreCookieSpecFactory.javarestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/IgnoreCookieSpecFa0000664000175000017500000000353411757206346034414 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.httpclient.internal; import org.apache.http.cookie.CookieSpec; import org.apache.http.cookie.CookieSpecFactory; import org.apache.http.params.HttpParams; /** * Factory that creates {@link IgnoreCookieSpec} instances. * * @author Jerome Louvel */ public class IgnoreCookieSpecFactory implements CookieSpecFactory { /** * Creates a new instance of {@link IgnoreCookieSpec}. * * @param params * The parameters are ignored. * @return The created instance. */ public CookieSpec newInstance(final HttpParams params) { return new IgnoreCookieSpec(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/IgnoreCookieSpec.javarestlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/internal/IgnoreCookieSpec.j0000664000175000017500000000462411757206346034376 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.httpclient.internal; import java.util.Collections; import java.util.List; import org.apache.http.Header; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.impl.cookie.CookieSpecBase; /** * Cookie specifications that ignore all cookies. * * @author Jerome Louvel */ public class IgnoreCookieSpec extends CookieSpecBase { /** * Returns an empty list. * * @return An empty list. */ public List
formatCookies(List cookies) { return Collections.emptyList(); } /** * Returns '0' as version. * * @return '0' as version. */ public int getVersion() { return 0; } /** * Returns a null version header. * * @return A null version header. */ public Header getVersionHeader() { return null; } /** * Returns an empty list. * * @return An empty list. */ public List parse(Header header, CookieOrigin origin) throws MalformedCookieException { return Collections.emptyList(); } } restlet-2.0.14/org.restlet.ext.httpclient/src/org/restlet/ext/httpclient/package.html0000664000175000017500000000044611757206346031476 0ustar jamespagejamespage Integration with Apache HTTP Client 4.0. Provides an HTTP and HTTPS client connector with advanced multi-threading and connection reuse support. @since Restlet 1.0 @see Apache HTTP client project restlet-2.0.14/org.restlet.ext.crypto/0000775000175000017500000000000012001473203020312 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.crypto/pom.xml0000600000175000017500000000134612001473203021621 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.crypto Restlet Extension - Crypto Support for cryptography. org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.crypto/src/0000775000175000017500000000000012001473202021100 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.crypto/src/META-INF/0000775000175000017500000000000011757206450022260 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.crypto/src/META-INF/services/0000775000175000017500000000000011757206352024104 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.ext.crypto/src/META-INF/services/org.restlet.engine.security.AuthenticatorHelperrestlet-2.0.14/org.restlet.ext.crypto/src/META-INF/services/org.restlet.engine.security.Authenticato0000664000175000017500000000032111757206352034034 0ustar jamespagejamespageorg.restlet.ext.crypto.internal.HttpAwsS3Helper org.restlet.ext.crypto.internal.HttpDigestHelper org.restlet.ext.crypto.internal.HttpSharedKeyHelper org.restlet.ext.crypto.internal.HttpSharedKeyLiteHelper restlet-2.0.14/org.restlet.ext.crypto/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446023720 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.crypto/src/org/0000775000175000017500000000000011757206352021710 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/0000775000175000017500000000000011757206352023372 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/0000775000175000017500000000000011757206352024172 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/0000775000175000017500000000000011757206352025512 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/DigestVerifier.java0000664000175000017500000002053411757206352031274 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.Digest; import org.restlet.security.LocalVerifier; import org.restlet.security.SecretVerifier; /** * Wrapper verifier that can verify digested secrets. If the provided secret is * a digest, then the local secret must either be a digest of the same algorithm * or the wrapped verifier must be a {@link LocalVerifier} returning secrets in * clear.
*
* If the provided secret is a regular secret, then the local secret can be in * any digest algorithm or a regular secret. * * @see Digest * @see DigestAuthenticator * @author Jerome Louvel */ public class DigestVerifier extends SecretVerifier { /** The digest algorithm of provided secrets. */ private String algorithm; /** The digest algorithm of secrets returned by the wrapped verifier. */ private String wrappedAlgorithm; /** The wrapped secret verifier. */ private T wrappedVerifier; /** * Constructor. * * @param algorithm * The digest algorithm of provided secrets. * @param wrappedVerifier * The wrapped secret verifier. * @param wrappedAlgorithm * The digest algorithm of secrets provided by the wrapped * verifier. * @see Digest */ public DigestVerifier(String algorithm, T wrappedVerifier, String wrappedAlgorithm) { this.algorithm = algorithm; this.wrappedAlgorithm = wrappedAlgorithm; this.wrappedVerifier = wrappedVerifier; } /** * Computes the digest of a secret according to a specified algorithm. By * default, MD5 hashes (represented as a sequence of 32 hexadecimal digits) * and SHA-1 hashes are supported. For additional algorithm, override this * method. * * @param identifier * The user identifier. * @param secret * The regular secret to digest. * @param algorithm * The digest algorithm to use. * @return The digested secret. * @see Digest */ protected char[] digest(String identifier, char[] secret, String algorithm) { return DigestUtils.digest(secret, algorithm); } /** * Returns the digest algorithm of provided secrets. Provided secrets are * the ones sent by clients when attempting to authenticate. * * @return The digest algorithm of input secrets. */ public String getAlgorithm() { return algorithm; } /** * Returns the digest algorithm of secrets returned by the wrapped verifier. * The secrets from the wrapped verifier are the ones used by the verifier * to compare those sent by clients when attempting to authenticate. * * @return The digest algorithm of secrets returned by the wrapped verifier. */ public String getWrappedAlgorithm() { return wrappedAlgorithm; } /** * Returns the wrapped secret associated to a given identifier. This method * can only be called if the wrapped verifier is a {@link LocalVerifier}. * * @param identifier * The identifier to lookup. * @return The secret associated to the identifier or null. */ public char[] getWrappedSecret(String identifier) { char[] result = null; if (getWrappedVerifier() instanceof LocalVerifier) { LocalVerifier localVerifier = (LocalVerifier) getWrappedVerifier(); result = localVerifier.getLocalSecret(identifier); } else { Context .getCurrentLogger() .log( Level.WARNING, "The wrapped verifier must be a LocalVerifier to allow digesting of wrapped secrets."); } return result; } /** * Returns the digest of the wrapped secret associated to a given * identifier. If the wrapped algorithm is null it returns the digest of the * wrapped secret, otherwise the algorithms must be identical. This method * can only be called if the wrapped verifier is a {@link LocalVerifier}. * * @param identifier * The identifier to lookup. * @return The secret associated to the identifier or null. */ public char[] getWrappedSecretDigest(String identifier) { char[] result = null; if (getWrappedAlgorithm() == null) { result = digest(identifier, getWrappedSecret(identifier), getAlgorithm()); } else if (getAlgorithm().equals(getWrappedAlgorithm())) { result = getWrappedSecret(identifier); } else { Context.getCurrentLogger().log(Level.WARNING, "The digest algorithms can't be different."); } return result; } /** * Returns the wrapped secret verifier. * * @return The wrapped secret verifier. */ public T getWrappedVerifier() { return wrappedVerifier; } /** * Sets the digest algorithm of provided secrets. Provided secrets are the * ones sent by clients when attempting to authenticate. * * @param algorithm * The digest algorithm of secrets provided by the user. * @see Digest */ public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } /** * Sets the digest algorithm of secrets returned by the wrapped verifier. * The secrets from the wrapped verifier are the ones used by the verifier * to compare those sent by clients when attempting to authenticate. * * @param wrappedAlgorithm * The digest algorithm of secrets returned by the wrapped * verifier. * @see Digest */ public void setWrappedAlgorithm(String wrappedAlgorithm) { this.wrappedAlgorithm = wrappedAlgorithm; } /** * Sets the wrapped secret verifier. * * @param wrappedVerifier * The wrapped secret verifier. */ public void setWrappedVerifier(T wrappedVerifier) { this.wrappedVerifier = wrappedVerifier; } @Override public boolean verify(String identifier, char[] secret) { boolean result = false; char[] secretDigest = secret; if (getAlgorithm() == null) { if (getWrappedAlgorithm() != null) { secretDigest = digest(identifier, secret, getWrappedAlgorithm()); } else { // Both secrets should be in clear } result = getWrappedVerifier().verify(identifier, secretDigest); } else { if (getWrappedAlgorithm() == null) { result = compare(secretDigest, getWrappedSecretDigest(identifier)); } else if (getAlgorithm().equals(getWrappedAlgorithm())) { result = getWrappedVerifier().verify(identifier, secretDigest); } else { Context.getCurrentLogger().log(Level.WARNING, "The input and output algorithms can't be different."); } } return result; } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/0000775000175000017500000000000011757206352027326 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/HttpSharedKeyLiteHelper.javarestlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/HttpSharedKeyLiteHelper.ja0000664000175000017500000001053011757206352034336 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto.internal; import java.util.Date; import org.restlet.Request; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.security.AuthenticatorHelper; import org.restlet.engine.util.Base64; import org.restlet.engine.util.DateUtils; import org.restlet.ext.crypto.DigestUtils; import org.restlet.util.Series; /** * Implements the Shared Key Lite authentication for Azure services. This * concerns Table storage on Azure Storage.
*
* More documentation is available here * * @author Thierry Boileau */ public class HttpSharedKeyLiteHelper extends AuthenticatorHelper { /** * Returns the canonicalized resource name. * * @param resourceRef * The resource reference. * @return The canonicalized resource name. */ private static String getCanonicalizedResourceName(Reference resourceRef) { Form form = resourceRef.getQueryAsForm(); Parameter param = form.getFirst("comp", true); if (param != null) { StringBuilder sb = new StringBuilder(resourceRef.getPath()); return sb.append("?").append("comp=").append(param.getValue()) .toString(); } return resourceRef.getPath(); } /** * Constructor. */ public HttpSharedKeyLiteHelper() { super(ChallengeScheme.HTTP_AZURE_SHAREDKEY_LITE, true, false); } @Override public void formatRawResponse(ChallengeWriter cw, ChallengeResponse challenge, Request request, Series httpHeaders) { // Setup the Date header String date = ""; if (httpHeaders.getFirstValue("x-ms-date", true) == null) { // X-ms-Date header didn't override the standard Date header date = httpHeaders.getFirstValue(HeaderConstants.HEADER_DATE, true); if (date == null) { // Add a fresh Date header date = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123 .get(0)); httpHeaders.add(HeaderConstants.HEADER_DATE, date); } } else { date = httpHeaders.getFirstValue("x-ms-date", true); } // Setup the canonicalized path final String canonicalizedResource = getCanonicalizedResourceName(request .getResourceRef()); // Setup the message part final StringBuilder rest = new StringBuilder(); rest.append(date).append('\n').append('/').append( challenge.getIdentifier()).append(canonicalizedResource); // Append the SharedKey credentials cw.append(challenge.getIdentifier()).append(':').append( Base64.encode(DigestUtils.toHMac256(rest.toString(), Base64 .decode(challenge.getSecret())), true)); } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/HttpDigestHelper.java0000664000175000017500000004703111757206352033415 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto.internal; import java.io.IOException; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Digest; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.security.AuthenticatorHelper; import org.restlet.engine.security.AuthenticatorUtils; import org.restlet.engine.util.Base64; import org.restlet.ext.crypto.DigestUtils; import org.restlet.security.Guard; import org.restlet.util.Series; /** * Implements the HTTP DIGEST authentication. * * @author Jerome Louvel */ @SuppressWarnings("deprecation") public class HttpDigestHelper extends AuthenticatorHelper { /** * Return the hashed secret. * * @param identifier * The user identifier to hash. * @param guard * The associated guard to callback. * * @return A hash of the user name, realm, and password, specified as A1 in * section 3.2.2.2 of RFC2617, or null if the identifier has no * corresponding secret. */ @Deprecated private static String getHashedSecret(String identifier, Guard guard) { char[] secret = guard.getSecretResolver().resolve(identifier); if (secret != null) { return DigestUtils.toHttpDigest(identifier, secret, guard .getRealm()); } // The given identifier is not known return null; } /** * Checks whether the specified nonce is valid with respect to the specified * secretKey, and further confirms that the nonce was generated less than * lifespanMillis milliseconds ago * * @param nonce * The nonce value. * @param secretKey * The same secret value that was inserted into the nonce when it * was generated * @param lifespan * The nonce lifespan in milliseconds. * @return True if the nonce was generated less than lifespan milliseconds * ago, false otherwise. * @throws Exception * If the nonce does not match the specified secretKey, or if it * can't be parsed */ public static boolean isNonceValid(String nonce, String secretKey, long lifespan) throws Exception { try { String decodedNonce = new String(Base64.decode(nonce)); long nonceTimeMS = Long.parseLong(decodedNonce.substring(0, decodedNonce.indexOf(':'))); if (decodedNonce.equals(nonceTimeMS + ":" + DigestUtils.toMd5(nonceTimeMS + ":" + secretKey))) { // Valid with regard to the secretKey, now check lifespan return lifespan > (System.currentTimeMillis() - nonceTimeMS); } } catch (Exception e) { throw new Exception("Error detected parsing nonce: " + e); } throw new Exception("The nonce does not match secretKey"); } /** * Constructor. */ public HttpDigestHelper() { super(ChallengeScheme.HTTP_DIGEST, true, true); } @Deprecated @Override public int authenticate(ChallengeResponse cr, Request request, Guard guard) { Series parameters = cr.getParameters(); String username = cr.getIdentifier(); String response = new String(cr.getSecret()); String nonce = parameters.getFirstValue("nonce"); String uri = parameters.getFirstValue("uri"); String qop = parameters.getFirstValue("qop"); String nc = parameters.getFirstValue("nc"); String cnonce = parameters.getFirstValue("cnonce"); try { if (!isNonceValid(nonce, guard.getServerKey(), guard .getNonceLifespan())) { // Nonce expired, send challenge request with // stale=true return Guard.AUTHENTICATION_STALE; } } catch (Exception ce) { // Invalid nonce, probably doesn't match serverKey return Guard.AUTHENTICATION_INVALID; } if (!AuthenticatorUtils.anyNull(username, nonce, response, uri)) { Reference resourceRef = request.getResourceRef(); String requestUri = resourceRef.getPath(); if ((resourceRef.getQuery() != null) && (uri.indexOf('?') > -1)) { // IE neglects to include the query string, so // the workaround is to leave it off // unless both the calculated URI and the // specified URI contain a query string requestUri += "?" + resourceRef.getQuery(); } if (uri.equals(requestUri)) { String a1 = getHashedSecret(username, guard); if (a1 != null) { String a2 = DigestUtils.toMd5(request.getMethod() + ":" + requestUri); StringBuffer expectedResponse = new StringBuffer(a1) .append(':').append(nonce); if (!AuthenticatorUtils.anyNull(qop, cnonce, nc)) { expectedResponse.append(':').append(nc).append(':') .append(cnonce).append(':').append(qop); } expectedResponse.append(':').append(a2); if (response.equals(DigestUtils.toMd5(expectedResponse .toString()))) { return Guard.AUTHENTICATION_VALID; } } } return Guard.AUTHENTICATION_INVALID; } return Guard.AUTHENTICATION_MISSING; } @Deprecated @Override public void challenge(Response response, boolean stale, Guard guard) { super.challenge(response, stale, guard); // This is temporary, pending Guard re-factoring. We still assume // there is only one challenge scheme, that of the Guard. ChallengeRequest mainChallengeRequest = null; for (ChallengeRequest challengeRequest : response .getChallengeRequests()) { if (challengeRequest.getScheme().equals(guard.getScheme())) { mainChallengeRequest = challengeRequest; break; } } if (mainChallengeRequest != null) { mainChallengeRequest.setDomainUris(guard.getDomainUris()); mainChallengeRequest.setStale(stale); mainChallengeRequest.setServerNonce(CryptoUtils.makeNonce(guard .getServerKey())); } } @Override public void formatRawRequest(ChallengeWriter cw, ChallengeRequest challenge, Response response, Series httpHeaders) throws IOException { if (challenge.getRealm() != null) { cw.appendQuotedChallengeParameter("realm", challenge.getRealm()); } if (!challenge.getDomainRefs().isEmpty()) { cw.append(", domain=\""); for (int i = 0; i < challenge.getDomainRefs().size(); i++) { if (i > 0) { cw.append(' '); } cw.append(challenge.getDomainRefs().get(i).toString()); } cw.append('"'); } if (challenge.getServerNonce() != null) { cw.appendQuotedChallengeParameter("nonce", challenge .getServerNonce()); } if (challenge.getOpaque() != null) { cw.appendQuotedChallengeParameter("opaque", challenge.getOpaque()); } if (challenge.isStale()) { cw.appendChallengeParameter("stale", "true"); } if (challenge.getDigestAlgorithm() != null) { cw.appendChallengeParameter("algorithm", challenge .getDigestAlgorithm()); } if (!challenge.getQualityOptions().isEmpty()) { cw.append(", qop=\""); for (int i = 0; i < challenge.getQualityOptions().size(); i++) { if (i > 0) { cw.append(','); } cw.appendToken(challenge.getQualityOptions().get(i).toString()); } cw.append('"'); } for (Parameter param : challenge.getParameters()) { if (HeaderUtils.isToken(param.getValue())) { cw.appendChallengeParameter(param); } else { cw.appendQuotedChallengeParameter(param); } } } @Override public void formatRawResponse(ChallengeWriter cw, ChallengeResponse challenge, Request request, Series httpHeaders) { if (challenge.getIdentifier() != null) { cw.appendQuotedChallengeParameter("username", challenge .getIdentifier()); } if (challenge.getRealm() != null) { cw.appendQuotedChallengeParameter("realm", challenge.getRealm()); } if (challenge.getServerNonce() != null) { cw.appendQuotedChallengeParameter("nonce", challenge .getServerNonce()); } if (challenge.getDigestRef() != null) { challenge.setDigestRef(new Reference(request.getResourceRef() .getPath())); cw.appendQuotedChallengeParameter("uri", challenge.getDigestRef() .toString()); } char[] secret = formatSecret(challenge, request, null, challenge.getIdentifier(), challenge.getSecret(), Digest.ALGORITHM_NONE); if (secret != null) { cw.appendQuotedChallengeParameter("response", new String(secret)); } if ((challenge.getDigestAlgorithm() != null) && !Digest.ALGORITHM_MD5.equals(challenge.getDigestAlgorithm())) { cw.appendChallengeParameter("algorithm", challenge .getDigestAlgorithm()); } if (challenge.getClientNonce() != null) { cw.appendQuotedChallengeParameter("cnonce", challenge .getClientNonce()); } if (challenge.getOpaque() != null) { cw.appendQuotedChallengeParameter("opaque", challenge.getOpaque()); } if (challenge.getQuality() != null) { cw.appendChallengeParameter("qop", challenge.getQuality()); } if ((challenge.getQuality() != null) && (challenge.getServerNounceCount() > 0)) { cw.appendChallengeParameter("nc", challenge .getServerNounceCountAsHex()); } for (Parameter param : challenge.getParameters()) { if (HeaderUtils.isToken(param.getValue())) { cw.appendChallengeParameter(param); } else { cw.appendQuotedChallengeParameter(param); } } } @Override public char[] formatSecret(ChallengeResponse challengeResponse, Request request, Response response, String identifier, char[] baseSecret, String baseSecretAlgorithm) { String a1 = null; if (!Digest.ALGORITHM_HTTP_DIGEST.equals(baseSecretAlgorithm)) { if (!AuthenticatorUtils.anyNull(challengeResponse.getIdentifier(), baseSecret, challengeResponse.getRealm())) { a1 = DigestUtils.toHttpDigest(identifier, baseSecret, challengeResponse.getRealm()); } } else { a1 = new String(baseSecret); } if (a1 != null && !AuthenticatorUtils.anyNull(request.getMethod(), challengeResponse.getDigestRef())) { String a2 = DigestUtils.toMd5(request.getMethod().toString() + ":" + challengeResponse.getDigestRef().toString()); StringBuilder sb = new StringBuilder().append(a1).append(':') .append(challengeResponse.getServerNonce()); if (!AuthenticatorUtils.anyNull(challengeResponse.getQuality(), challengeResponse.getClientNonce(), challengeResponse .getServerNounceCount())) { sb.append(':').append( AuthenticatorUtils.formatNonceCount(challengeResponse .getServerNounceCount())).append(':').append( challengeResponse.getClientNonce()).append(':').append( challengeResponse.getQuality()); } sb.append(':').append(a2); return DigestUtils.toMd5(sb.toString()).toCharArray(); } return null; } @Override public void parseRequest(ChallengeRequest challenge, Response response, Series httpHeaders) { if (challenge.getRawValue() != null) { HeaderReader hr = new HeaderReader(challenge .getRawValue()); try { Parameter param = hr.readParameter(); while (param != null) { try { if ("realm".equals(param.getName())) { challenge.setRealm(param.getValue()); } else if ("domain".equals(param.getName())) { challenge.getDomainRefs().add( new Reference(param.getValue())); } else if ("nonce".equals(param.getName())) { challenge.setServerNonce(param.getValue()); } else if ("opaque".equals(param.getName())) { challenge.setOpaque(param.getValue()); } else if ("stale".equals(param.getName())) { challenge.setStale(Boolean .valueOf(param.getValue())); } else if ("algorithm".equals(param.getName())) { challenge.setDigestAlgorithm(param.getValue()); } else if ("qop".equals(param.getName())) { // challenge.setDigestAlgorithm(param.getValue()); } else { challenge.getParameters().add(param); } if (hr.skipValueSeparator()) { param = hr.readParameter(); } else { param = null; } } catch (Exception e) { Context .getCurrentLogger() .log( Level.WARNING, "Unable to parse the challenge request header parameter", e); } } } catch (Exception e) { Context .getCurrentLogger() .log( Level.WARNING, "Unable to parse the challenge request header parameter", e); } } } @Override public void parseResponse(ChallengeResponse challenge, Request request, Series httpHeaders) { if (challenge.getCredentials() != null) { HeaderReader hr = new HeaderReader(challenge .getCredentials()); try { Parameter param = hr.readParameter(); while (param != null) { try { if ("username".equals(param.getName())) { challenge.setIdentifier(param.getValue()); } else if ("realm".equals(param.getName())) { challenge.setRealm(param.getValue()); } else if ("nonce".equals(param.getName())) { challenge.setServerNonce(param.getValue()); } else if ("uri".equals(param.getName())) { challenge.setDigestRef(new Reference(param .getValue())); } else if ("response".equals(param.getName())) { challenge.setSecret(param.getValue()); } else if ("algorithm".equals(param.getName())) { challenge.setDigestAlgorithm(param.getValue()); } else if ("cnonce".equals(param.getName())) { challenge.setClientNonce(param.getValue()); } else if ("opaque".equals(param.getName())) { challenge.setOpaque(param.getValue()); } else if ("qop".equals(param.getName())) { challenge.setQuality(param.getValue()); } else if ("nc".equals(param.getName())) { challenge.setServerNounceCount(Integer.valueOf( param.getValue(), 16)); } else { challenge.getParameters().add(param); } } catch (Throwable e) { Context .getCurrentLogger() .log( Level.WARNING, "Unable to parse the challenge request header parameter", e); } if (hr.skipValueSeparator()) { param = hr.readParameter(); } else { param = null; } } } catch (Exception e) { Context .getCurrentLogger() .log( Level.WARNING, "Unable to parse the challenge request header parameter", e); } } } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/HttpAwsS3Helper.java0000664000175000017500000002117611757206352033140 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto.internal; import java.util.Date; import java.util.Iterator; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.restlet.Request; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.io.BioUtils; import org.restlet.engine.security.AuthenticatorHelper; import org.restlet.engine.util.Base64; import org.restlet.engine.util.DateUtils; import org.restlet.engine.util.SystemUtils; import org.restlet.ext.crypto.DigestUtils; import org.restlet.util.Series; /** * Implements the HTTP authentication for the Amazon S3 service. * * @author Jerome Louvel */ public class HttpAwsS3Helper extends AuthenticatorHelper { /** * Returns the canonicalized AMZ headers. * * @param requestHeaders * The list of request headers. * @return The canonicalized AMZ headers. */ private static String getCanonicalizedAmzHeaders( Series requestHeaders) { // Filter out all the AMZ headers required for AWS authentication final SortedMap amzHeaders = new TreeMap(); String headerName; for (final Parameter param : requestHeaders) { headerName = param.getName().toLowerCase(); if (headerName.startsWith("x-amz-")) { if (!amzHeaders.containsKey(headerName)) { amzHeaders.put(headerName, requestHeaders.getValues(headerName)); } } } // Concatenate all AMZ headers final StringBuilder sb = new StringBuilder(); for (Iterator iterator = amzHeaders.keySet().iterator(); iterator .hasNext();) { String key = iterator.next(); sb.append(key).append(':').append(amzHeaders.get(key)).append("\n"); } return sb.toString(); } /** * Returns the canonicalized resource name. * * @param reference * The resource reference. * @return The canonicalized resource name. */ private static String getCanonicalizedResourceName(Reference reference) { String hostName = reference.getHostDomain(); String path = reference.getPath(); Pattern hostNamePattern = Pattern .compile("s3[a-z0-1\\-]*.amazonaws.com"); StringBuilder sb = new StringBuilder(); // Append the bucket if (hostName != null) { // If the host name contains a port number remove it if (hostName.contains(":")) hostName = hostName.substring(0, hostName.indexOf(":")); Matcher hostNameMatcher = hostNamePattern.matcher(hostName); if (hostName.endsWith(".s3.amazonaws.com")) { String bucketName = hostName.substring(0, hostName.length() - 17); sb.append("/" + bucketName); } else if (!hostNameMatcher.matches()) { sb.append("/" + hostName); } } int queryIdx = path.indexOf("?"); // Append the resource path if (queryIdx >= 0) sb.append(path.substring(0, queryIdx)); else sb.append(path.substring(0, path.length())); // Append the AWS sub-resource if (queryIdx >= 0) { String query = path.substring(queryIdx - 1, path.length()); if (query.contains("?acl")) sb.append("?acl"); else if (query.contains("?location")) sb.append("?location"); else if (query.contains("?logging")) sb.append("?logging"); else if (query.contains("?torrent")) sb.append("?torrent"); } return sb.toString(); } /** * Constructor. */ public HttpAwsS3Helper() { super(ChallengeScheme.HTTP_AWS_S3, true, false); } @Override public void formatRawResponse(ChallengeWriter cw, ChallengeResponse challenge, Request request, Series httpHeaders) { // Setup the method name final String methodName = request.getMethod().getName(); // Setup the Date header String date = ""; if (httpHeaders.getFirstValue("X-Amz-Date", true) == null) { // X-Amz-Date header didn't override the standard Date header date = httpHeaders.getFirstValue(HeaderConstants.HEADER_DATE, true); if (date == null) { // Add a fresh Date header date = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123.get(0)); httpHeaders.add(HeaderConstants.HEADER_DATE, date); } } // Setup the Content-MD5 header String contentMd5 = httpHeaders.getFirstValue( HeaderConstants.HEADER_CONTENT_MD5, true); if (contentMd5 == null) { contentMd5 = ""; } // Setup the ContentType header String contentType = httpHeaders.getFirstValue( HeaderConstants.HEADER_CONTENT_TYPE, true); if (contentType == null) { boolean applyPatch = false; // This patch seems to apply to Sun JVM only. final String jvmVendor = System.getProperty("java.vm.vendor"); if ((jvmVendor != null) && (jvmVendor.toLowerCase()).startsWith("sun")) { final int majorVersionNumber = SystemUtils .getJavaMajorVersion(); final int minorVersionNumber = SystemUtils .getJavaMinorVersion(); if (majorVersionNumber == 1) { if (minorVersionNumber < 5) { applyPatch = true; } else if (minorVersionNumber == 5) { // Sun fixed the bug in update 10 applyPatch = (SystemUtils.getJavaUpdateVersion() < 10); } } } if (applyPatch && !request.getMethod().equals(Method.PUT)) { contentType = "application/x-www-form-urlencoded"; } else { contentType = ""; } } // Setup the canonicalized AmzHeaders final String canonicalizedAmzHeaders = getCanonicalizedAmzHeaders(httpHeaders); // Setup the canonicalized resource name final String canonicalizedResource = getCanonicalizedResourceName(request .getResourceRef()); // Setup the message part final StringBuilder rest = new StringBuilder(); rest.append(methodName).append('\n').append(contentMd5).append('\n') .append(contentType).append('\n').append(date).append('\n') .append(canonicalizedAmzHeaders).append(canonicalizedResource); // Append the AWS credentials cw.append(challenge.getIdentifier()) .append(':') .append(Base64.encode( DigestUtils.toHMac(rest.toString(), BioUtils.toByteArray(challenge.getSecret())), false)); } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/HttpDigestVerifier.java0000664000175000017500000001743211757206352033753 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto.internal; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.Digest; import org.restlet.data.Reference; import org.restlet.engine.security.AuthenticatorUtils; import org.restlet.ext.crypto.DigestAuthenticator; import org.restlet.ext.crypto.DigestUtils; import org.restlet.ext.crypto.DigestVerifier; import org.restlet.security.LocalVerifier; import org.restlet.security.User; /** * Verifier for the HTTP DIGEST authentication scheme. Note that the "A1" hash * specified in RFC 2617 is available via the * {@link #getWrappedSecretDigest(String)} method. * * @author Jerome Louvel */ public class HttpDigestVerifier extends DigestVerifier { /** The associated digest authenticator. */ private DigestAuthenticator digestAuthenticator; /** * Constructor. * * @param digestAuthenticator * The associated digest authenticator. * @param wrappedAlgorithm * The digest algorithm of secrets provided by the wrapped * verifier. * @param wrappedVerifier * The wrapped secret verifier. */ public HttpDigestVerifier(DigestAuthenticator digestAuthenticator, LocalVerifier wrappedVerifier, String wrappedAlgorithm) { super(Digest.ALGORITHM_HTTP_DIGEST, wrappedVerifier, wrappedAlgorithm); this.digestAuthenticator = digestAuthenticator; } /** * If the algorithm is {@link Digest#ALGORITHM_HTTP_DIGEST}, then is * retrieves the realm for {@link #getDigestAuthenticator()} to compute the * digest, otherwise, it keeps the default behavior. */ @Override protected char[] digest(String identifier, char[] secret, String algorithm) { if (Digest.ALGORITHM_HTTP_DIGEST.equals(algorithm)) { String result = DigestUtils.toHttpDigest(identifier, secret, getDigestAuthenticator().getRealm()); if (result != null) { return result.toCharArray(); } return null; } return super.digest(identifier, secret, algorithm); } /** * Returns the associated digest authenticator. * * @return The associated digest authenticator. */ public DigestAuthenticator getDigestAuthenticator() { return digestAuthenticator; } /** * Sets the associated digest authenticator. * * @param digestAuthenticator * The associated digest authenticator. */ public void setDigestAuthenticator(DigestAuthenticator digestAuthenticator) { this.digestAuthenticator = digestAuthenticator; } @Override public int verify(Request request, Response response) { int result = RESULT_VALID; ChallengeResponse cr = request.getChallengeResponse(); if (cr == null) { result = RESULT_MISSING; } else { String nonce = cr.getServerNonce(); String uri = (cr.getDigestRef() == null) ? null : cr.getDigestRef() .toString(); String qop = cr.getQuality(); int nc = cr.getServerNounceCount(); String cnonce = cr.getClientNonce(); String username = getIdentifier(request, response); String cresponse = null; char[] secret = getSecret(request, response); if (secret != null) { cresponse = new String(secret); } else { result = RESULT_INVALID; } try { if (!HttpDigestHelper.isNonceValid(nonce, getDigestAuthenticator().getServerKey(), getDigestAuthenticator().getMaxServerNonceAge())) { // Nonce expired, send challenge request with stale=true result = RESULT_STALE; } } catch (Exception ce) { // Invalid nonce, probably doesn't match serverKey result = RESULT_INVALID; } if (result == RESULT_VALID) { if (AuthenticatorUtils.anyNull(nonce, uri)) { result = RESULT_MISSING; } else { Reference resourceRef = request.getResourceRef(); String requestUri = resourceRef.getPath(); if ((resourceRef.getQuery() != null) && (uri.indexOf('?') > -1)) { // IE neglects to include the query string, so // the workaround is to leave it off // unless both the calculated URI and the // specified URI contain a query string requestUri += "?" + resourceRef.getQuery(); } if (uri.equals(requestUri)) { char[] a1 = getWrappedSecretDigest(username); if (a1 != null) { String a2 = DigestUtils.toMd5(request.getMethod() .toString() + ":" + requestUri); StringBuilder expectedResponse = new StringBuilder() .append(a1).append(':').append(nonce); if (!AuthenticatorUtils.anyNull(qop, cnonce, nc)) { expectedResponse.append(':') .append( AuthenticatorUtils .formatNonceCount(nc)) .append(':').append(cnonce).append(':') .append(qop); } expectedResponse.append(':').append(a2); if (!DigestUtils.toMd5(expectedResponse.toString()) .equals(cresponse)) { result = RESULT_INVALID; } } else { // The HA1 is null result = RESULT_INVALID; } } else { // The request URI doesn't match result = RESULT_INVALID; } } } if (result == RESULT_VALID) { request.getClientInfo().setUser(new User(username)); } } return result; } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/CryptoUtils.java0000664000175000017500000001227111757206352032475 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto.internal; import java.security.GeneralSecurityException; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import org.restlet.engine.util.Base64; import org.restlet.ext.crypto.DigestUtils; /** * Simple usage of standard cipher features from JRE. * * @author Remi Dewitte */ public final class CryptoUtils { /** * Creates a cipher for a given algorithm and secret. * * @param algo * The cryptographic algorithm. * @param base64Secret * The cryptographic secret, encoded as a Base64 string. * @param mode * The cipher mode, either {@link Cipher#ENCRYPT_MODE} or * {@link Cipher#DECRYPT_MODE}. * @return The new cipher. * @throws GeneralSecurityException */ private static Cipher createCipher(String algo, String base64Secret, int mode) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(algo); cipher.init(mode, new SecretKeySpec(Base64.decode(base64Secret), algo)); return cipher; } /** * Decrypts a bytes array. * * @param algo * The cryptographic algorithm. * @param base64Secret * The cryptographic secret, encoded as a Base64 string. * @param encrypted * The encrypted bytes. * @return The decrypted content string. * @throws GeneralSecurityException */ public static String decrypt(String algo, String base64Secret, byte[] encrypted) throws GeneralSecurityException { byte[] original = doFinal(algo, base64Secret, Cipher.DECRYPT_MODE, encrypted); return new String(original); } /** * Does final processing. * * @param algo * The cryptographic algorithm. * @param base64Secret * The cryptographic secret, encoded as a Base64 string. * @param mode * The processing mode, either {@link Cipher#DECRYPT_MODE} or * {@link Cipher#ENCRYPT_MODE}. * @param what * The byte array to process. * @return The processed byte array. * @throws GeneralSecurityException */ private static byte[] doFinal(String algo, String base64Secret, int mode, byte[] what) throws GeneralSecurityException { return createCipher(algo, base64Secret, mode).doFinal(what); } /** * Encrypts a content string. * * @param algo * The cryptographic algorithm. * @param base64Secret * The cryptographic secret, encoded as a Base64 string. * @param content * The content string to encrypt. * @return The encrypted bytes. * @throws GeneralSecurityException */ public static byte[] encrypt(String algo, String base64Secret, String content) throws GeneralSecurityException { return doFinal(algo, base64Secret, Cipher.ENCRYPT_MODE, content .getBytes()); } /** * Generates a nonce as recommended in section 3.2.1 of RFC-2617, but * without the ETag field. The format is:
     * Base64.encodeBytes(currentTimeMS + ":"
     *         + md5String(currentTimeMS + ":" + secretKey))
     * 
* * @param secretKey * a secret value known only to the creator of the nonce. It's * inserted into the nonce, and can be used later to validate the * nonce. */ public static String makeNonce(String secretKey) { final long currentTimeMS = System.currentTimeMillis(); return Base64.encode((currentTimeMS + ":" + DigestUtils .toMd5(currentTimeMS + ":" + secretKey)).getBytes(), true); } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private CryptoUtils() { } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/HttpSharedKeyHelper.java0000664000175000017500000001710111757206352034050 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto.internal; import java.util.Date; import java.util.Iterator; import java.util.SortedMap; import java.util.TreeMap; import org.restlet.Request; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.security.AuthenticatorHelper; import org.restlet.engine.util.Base64; import org.restlet.engine.util.DateUtils; import org.restlet.engine.util.SystemUtils; import org.restlet.ext.crypto.DigestUtils; import org.restlet.util.Series; /** * Implements the Shared Key authentication for Azure services. This concerns * Blob and Queues on Azure Storage.
*
* More documentation is available here * * @author Thierry Boileau */ public class HttpSharedKeyHelper extends AuthenticatorHelper { /** * Returns the canonicalized Azure headers. * * @param requestHeaders * The list of request headers. * @return The canonicalized Azure headers. */ private static String getCanonicalizedAzureHeaders( Series requestHeaders) { // Filter out all the Azure headers required for SharedKey // authentication final SortedMap azureHeaders = new TreeMap(); String headerName; for (final Parameter param : requestHeaders) { headerName = param.getName().toLowerCase(); if (headerName.startsWith("x-ms-")) { if (!azureHeaders.containsKey(headerName)) { azureHeaders.put(headerName, requestHeaders .getValues(headerName)); } } } // Concatenate all Azure headers final StringBuilder sb = new StringBuilder(); for (Iterator iterator = azureHeaders.keySet().iterator(); iterator .hasNext();) { String key = iterator.next(); sb.append(key).append(':').append(azureHeaders.get(key)).append( "\n"); } return sb.toString(); } /** * Returns the canonicalized resource name. * * @param resourceRef * The resource reference. * @return The canonicalized resource name. */ private static String getCanonicalizedResourceName(Reference resourceRef) { Form form = resourceRef.getQueryAsForm(); Parameter param = form.getFirst("comp", true); if (param != null) { StringBuilder sb = new StringBuilder(resourceRef.getPath()); return sb.append("?").append("comp=").append(param.getValue()) .toString(); } return resourceRef.getPath(); } /** * Constructor. */ public HttpSharedKeyHelper() { super(ChallengeScheme.HTTP_AZURE_SHAREDKEY, true, false); } @Override public void formatRawResponse(ChallengeWriter cw, ChallengeResponse challenge, Request request, Series httpHeaders) { // Setup the method name final String methodName = request.getMethod().getName(); // Setup the Date header String date = ""; if (httpHeaders.getFirstValue("x-ms-date", true) == null) { // X-ms-Date header didn't override the standard Date header date = httpHeaders.getFirstValue(HeaderConstants.HEADER_DATE, true); if (date == null) { // Add a fresh Date header date = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123 .get(0)); httpHeaders.add(HeaderConstants.HEADER_DATE, date); } } // Setup the ContentType header String contentMd5 = httpHeaders.getFirstValue( HeaderConstants.HEADER_CONTENT_MD5, true); if (contentMd5 == null) { contentMd5 = ""; } // Setup the ContentType header String contentType = httpHeaders.getFirstValue( HeaderConstants.HEADER_CONTENT_TYPE, true); if (contentType == null) { boolean applyPatch = false; // This patch seems to apply to Sun JVM only. final String jvmVendor = System.getProperty("java.vm.vendor"); if ((jvmVendor != null) && (jvmVendor.toLowerCase()).startsWith("sun")) { final int majorVersionNumber = SystemUtils .getJavaMajorVersion(); final int minorVersionNumber = SystemUtils .getJavaMinorVersion(); if (majorVersionNumber == 1) { if (minorVersionNumber < 5) { applyPatch = true; } else if (minorVersionNumber == 5) { // Sun fixed the bug in update 10 applyPatch = (SystemUtils.getJavaUpdateVersion() < 10); } } } if (applyPatch && !request.getMethod().equals(Method.PUT)) { contentType = "application/x-www-form-urlencoded"; } else { contentType = ""; } } // Setup the canonicalized AzureHeaders final String canonicalizedAzureHeaders = getCanonicalizedAzureHeaders(httpHeaders); // Setup the canonicalized path final String canonicalizedResource = getCanonicalizedResourceName(request .getResourceRef()); // Setup the message part final StringBuilder rest = new StringBuilder(); rest.append(methodName).append('\n').append(contentMd5).append('\n') .append(contentType).append('\n').append(date).append('\n') .append(canonicalizedAzureHeaders).append('/').append( challenge.getIdentifier()) .append(canonicalizedResource); // Append the SharedKey credentials cw.append(challenge.getIdentifier()).append(':').append( Base64.encode(DigestUtils.toHMac256(rest.toString(), Base64 .decode(challenge.getSecret())), true)); } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/DigestUtils.java0000664000175000017500000002631611757206352030625 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.restlet.data.Digest; import org.restlet.engine.util.Base64; /** * Security data manipulation utilities. * * @author Jerome Louvel */ public class DigestUtils { /** * General regex pattern to extract comma separated name-value components. * This pattern captures one name and value per match(), and is repeatedly * applied to the input string to extract all components. Must handle both * quoted and unquoted values as RFC2617 isn't consistent in this respect. * Pattern is immutable and thread-safe so reuse one static instance. */ private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); /** * Converts a source string to its HMAC/SHA-1 value. * * @param source * The source string to convert. * @param secretKey * The secret key to use for conversion. * @return The HMac value of the source string. */ public static byte[] toHMac(String source, byte[] secretKey) { byte[] result = null; try { // Create the HMAC/SHA1 key final SecretKeySpec signingKey = new SecretKeySpec(secretKey, "HmacSHA1"); // Create the message authentication code (MAC) final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // Compute the HMAC value result = mac.doFinal(source.getBytes()); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException( "Could not find the SHA-1 algorithm. HMac conversion failed.", nsae); } catch (InvalidKeyException ike) { throw new RuntimeException( "Invalid key exception detected. HMac conversion failed.", ike); } return result; } /** * Converts a source string to its HMAC/SHA-1 value. * * @param source * The source string to convert. * @param secretKey * The secret key to use for conversion. * @return The HMac value of the source string. */ public static byte[] toHMac(String source, String secretKey) { return toHMac(source, secretKey.getBytes()); }; /** * Converts a source string to its HMAC/SHA256 value. * * @param source * The source string to convert. * @param secretKey * The secret key to use for conversion. * @return The HMac value of the source string. */ public static byte[] toHMac256(String source, byte[] secretKey) { byte[] result = null; try { // Create the HMAC/SHA256 key final SecretKeySpec signingKey = new SecretKeySpec(secretKey, "HmacSHA256"); // Create the message authentication code (MAC) final Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); // Compute the HMAC value result = mac.doFinal(source.getBytes("UTF-8")); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException( "Could not find the SHA256 algorithm. HMac conversion failed.", nsae); } catch (InvalidKeyException ike) { throw new RuntimeException( "Invalid key exception detected. HMac conversion failed.", ike); } catch (IllegalStateException ise) { throw new RuntimeException( "IIllegal state exception detected. HMac conversion failed.", ise); } catch (UnsupportedEncodingException uee) { throw new RuntimeException( "Unsuported encoding UTF-8. HMac conversion failed.", uee); } return result; } /** * Converts a source string to its HMAC/SHA256 value. * * @param source * The source string to convert. * @param secretKey * The secret key to use for conversion. * @return The HMac value of the source string. */ public static byte[] toHMac256(String source, String secretKey) { return toHMac256(source, secretKey.getBytes()); } /** * Return the HTTP DIGEST hashed secret. It concatenates the identifier, * realm and secret, separated by a comma and digest them using MD5. * * @param identifier * The user identifier to hash. * @param secret * The user secret. * @param realm * The authentication realm. * @return A hash of the user name, realm, and password, specified as A1 in * section 3.2.2.2 of RFC2617, or null if the identifier has no * corresponding secret. */ public static String toHttpDigest(String identifier, char[] secret, String realm) { if (secret != null) { return toMd5(identifier + ":" + realm + ":" + new String(secret)); } return null; } /** * Returns the MD5 digest of the target string. Target is decoded to bytes * using the US-ASCII charset. The returned hexadecimal String always * contains 32 lowercase alphanumeric characters. For example, if target is * "HelloWorld", this method returns "68e109f0f40ca72a15e05cc22786f8e6". * * @param target * The string to encode. * @return The MD5 digest of the target string. */ public static String toMd5(String target) { try { return toMd5(target, "US-ASCII"); } catch (UnsupportedEncodingException uee) { // Unlikely, US-ASCII comes with every JVM throw new RuntimeException( "US-ASCII is an unsupported encoding, unable to compute MD5"); } } /** * Returns the MD5 digest of target string. Target is decoded to bytes using * the named charset. The returned hexadecimal String always contains 32 * lowercase alphanumeric characters. For example, if target is * "HelloWorld", this method returns "68e109f0f40ca72a15e05cc22786f8e6". * * @param target * The string to encode. * @param charsetName * The character set. * @return The MD5 digest of the target string. * * @throws UnsupportedEncodingException */ public static String toMd5(String target, String charsetName) throws UnsupportedEncodingException { try { final byte[] md5 = MessageDigest.getInstance("MD5").digest( target.getBytes(charsetName)); final char[] md5Chars = new char[32]; int i = 0; for (final byte b : md5) { md5Chars[i++] = HEXDIGITS[(b >> 4) & 0xF]; md5Chars[i++] = HEXDIGITS[b & 0xF]; } return new String(md5Chars); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException( "No MD5 algorithm, unable to compute MD5"); } } /** * Returns the SHA1 digest of the target string. Target is decoded to bytes * using the US-ASCII charset. * * @param target * The string to encode. * @return The MD5 digest of the target string. */ public static String toSha1(String target) { try { return toSha1(target, "US-ASCII"); } catch (UnsupportedEncodingException uee) { // Unlikely, US-ASCII comes with every JVM throw new RuntimeException( "US-ASCII is an unsupported encoding, unable to compute SHA1"); } } /** * Returns the digest of the target string. Target is decoded to bytes using * the US-ASCII charset. Supports MD5 and SHA-1 algorithms. * * @param target * The string to encode. * @param algorithm * The digest algorithm to use. * @return The digest of the target string. */ public static char[] digest(char[] target, String algorithm) { return DigestUtils.digest(new String(target), algorithm).toCharArray(); } /** * Returns the digest of the target string. Target is decoded to bytes using * the US-ASCII charset. Supports MD5 and SHA-1 algorithms. * * @param target * The string to encode. * @param algorithm * The digest algorithm to use. * @return The digest of the target string. */ public static String digest(String target, String algorithm) { if (Digest.ALGORITHM_MD5.equals(algorithm)) { return toMd5(target); } else if (Digest.ALGORITHM_SHA_1.equals(algorithm)) { return toSha1(target); } throw new IllegalArgumentException("Unsupported algorithm."); } /** * Returns the SHA1 digest of target string. Target is decoded to bytes * using the named charset. * * @param target * The string to encode. * @param charsetName * The character set. * @return The SHA1 digest of the target string. * * @throws UnsupportedEncodingException */ public static String toSha1(String target, String charsetName) throws UnsupportedEncodingException { try { return Base64.encode(MessageDigest.getInstance("SHA1").digest( target.getBytes(charsetName)), false); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException( "No SHA1 algorithm, unable to compute SHA1"); } } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private DigestUtils() { } } restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/package.html0000664000175000017500000000021511757206352027771 0ustar jamespagejamespage Support for cryptography including Amazon S3 and Windows Azure client authentication. @since Restlet 2.0 restlet-2.0.14/org.restlet.ext.crypto/src/org/restlet/ext/crypto/DigestAuthenticator.java0000664000175000017500000002206611757206352032335 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.crypto; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Context; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeScheme; import org.restlet.data.Digest; import org.restlet.data.Reference; import org.restlet.ext.crypto.internal.CryptoUtils; import org.restlet.ext.crypto.internal.HttpDigestVerifier; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.LocalVerifier; import org.restlet.security.Verifier; /** * Authenticator supporting the digest challenge authentication schemes. By * default, it only knows about the {@link ChallengeScheme#HTTP_DIGEST} scheme. * * @see DigestVerifier * @see DigestAuthenticator * @author Jerome Louvel */ public class DigestAuthenticator extends ChallengeAuthenticator { /** Default lifespan for generated nonces (5 minutes). */ private static final long DEFAULT_MAX_SERVER_NONCE_AGE = 5 * 60 * 1000L; /** The URI references that define the protection domains. */ private volatile List domainRefs; /** Lifespan of nonce in milliseconds */ private volatile long maxServerNonceAge; /** The secret key known only to server. */ private volatile String serverKey; /** * Constructor. Sets the challenge scheme to * {@link ChallengeScheme#HTTP_DIGEST} and the nonce lifespan to 5 minutes * by default. * * @param context * The context. * @param optional * Indicates if the authentication success is optional. * @param realm * The authentication realm. * @param domainRefs * The URI references that define the protection domains. * @param serverKey * The secret key known only to server. */ public DigestAuthenticator(Context context, boolean optional, String realm, List domainRefs, String serverKey) { super(context, optional, ChallengeScheme.HTTP_DIGEST, realm); this.domainRefs = domainRefs; this.maxServerNonceAge = DEFAULT_MAX_SERVER_NONCE_AGE; this.serverKey = serverKey; setVerifier(new HttpDigestVerifier(this, null, null)); } /** * Constructor. By default, it set the "optional" property to 'false' and * the "domainUris" property to a single '/' URI. * * @param context * The context. * @param realm * The authentication realm. * @param serverKey * secret key known only to server */ public DigestAuthenticator(Context context, String realm, String serverKey) { this(context, false, realm, null, serverKey); } @Override protected ChallengeRequest createChallengeRequest(boolean stale) { ChallengeRequest result = super.createChallengeRequest(stale); result.setDomainRefs(getDomainRefs()); result.setStale(stale); result.setServerNonce(generateServerNonce()); return result; } /** * Generates a server nonce. * * @return A new server nonce. */ public String generateServerNonce() { return CryptoUtils.makeNonce(getServerKey()); } /** * Returns the base URI references that collectively define the protected * domains for the digest authentication. By default it return a list with a * single "/" URI reference. * * @return The base URI references. */ public List getDomainRefs() { // Lazy initialization with double-check. List r = this.domainRefs; if (r == null) { synchronized (this) { r = this.domainRefs; if (r == null) { this.domainRefs = r = new CopyOnWriteArrayList(); this.domainRefs.add(new Reference("/")); } } } return r; } /** * Return the hashed secret. By default, it knows how to hash HTTP DIGEST * secrets, specified as A1 in section 3.2.2.2 of RFC2617, or null if the * identifier has no corresponding secret. * * @param identifier * The user identifier to hash. * @param secret * The user secret. * @return A hash of the user name, realm, and password. */ public String getHashedSecret(String identifier, char[] secret) { if (ChallengeScheme.HTTP_DIGEST.equals(getScheme())) { return DigestUtils.toHttpDigest(identifier, secret, getRealm()); } return null; } /** * Returns the number of milliseconds between each mandatory nonce refresh. * * @return The server nonce lifespan. */ public long getMaxServerNonceAge() { return this.maxServerNonceAge; } /** * Returns the secret key known only by server. * * @return The server secret key. */ public String getServerKey() { return this.serverKey; } @SuppressWarnings("unchecked") @Override public DigestVerifier getVerifier() { return (DigestVerifier) super.getVerifier(); } /** * Sets the URI references that define the protection domains for the digest * authentication. * * @param domainRefs * The base URI references. */ public void setDomainRefs(List domainRefs) { this.domainRefs = domainRefs; } /** * Sets the number of milliseconds between each mandatory nonce refresh. * * @param maxServerNonceAge * The nonce lifespan in milliseconds. */ public void setMaxServerNonceAge(long maxServerNonceAge) { this.maxServerNonceAge = maxServerNonceAge; } /** * Sets the secret key known only by server. * * @param serverKey * The server secret key. */ public void setServerKey(String serverKey) { this.serverKey = serverKey; } /** * Set the internal verifier. In general you shouldn't replace it and * instead use the {@link #setWrappedVerifier(LocalVerifier)} method. * * @param verifier * The internal verifier. */ @Override public void setVerifier(Verifier verifier) { if (ChallengeScheme.HTTP_DIGEST.equals(getScheme())) { if (!(verifier instanceof HttpDigestVerifier)) { throw new IllegalArgumentException( "Only subclasses on HttpDigestVerifier are allowed. You might want to set the \"wrappedVerifier\" property instead."); } super.setVerifier(verifier); } else { if (!(verifier instanceof DigestVerifier)) { throw new IllegalArgumentException( "Only subclasses on DigestVerifier are allowed. You might want to set the \"wrappedVerifier\" property instead."); } super.setVerifier(verifier); } } /** * Sets the digest algorithm of secrets returned by the wrapped verifier. * The secrets from the wrapped verifier are the ones used by the verifier * to compare those sent by clients when attempting to authenticate. * * @param wrappedAlgorithm * The digest algorithm of secrets returned by the wrapped * verifier. * @see Digest */ public void setWrappedAlgorithm(String wrappedAlgorithm) { getVerifier().setWrappedAlgorithm(wrappedAlgorithm); } /** * Sets the secret verifier that will be wrapped by real verifier supporting * all the HTTP DIGEST verifications (nonce, domain URIs, etc.). * * @param localVerifier * The local verifier to wrap. */ public void setWrappedVerifier(LocalVerifier localVerifier) { getVerifier().setWrappedVerifier(localVerifier); } } restlet-2.0.14/org.restlet.ext.jdbc/0000775000175000017500000000000012001473143017677 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/pom.xml0000600000175000017500000000202012001473142021173 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.jdbc Restlet Extension - JDBC Integration with Java DataBase Connectivity (JDBC). commons-dbcp commons-dbcp 1.3 commons-pool commons-pool 1.5 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.jdbc/src/0000775000175000017500000000000012001473142020465 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/META-INF/0000775000175000017500000000000011757206452021644 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/META-INF/services/0000775000175000017500000000000011757206346023471 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/META-INF/services/org.restlet.engine.ClientHelper0000664000175000017500000000005611757206346031506 0ustar jamespagejamespageorg.restlet.ext.jdbc.JdbcClientHelper # JDBC ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jdbc/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.jdbc/src/META-INF/services/org.restlet.engine.converter.ConverterHelp0000664000175000017500000000004211757206346033711 0ustar jamespagejamespageorg.restlet.ext.jdbc.JdbcConverterrestlet-2.0.14/org.restlet.ext.jdbc/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023275 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.jdbc/src/org/0000775000175000017500000000000011757206346021275 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/0000775000175000017500000000000011757206346022757 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/0000775000175000017500000000000011757206346023557 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/0000775000175000017500000000000011757206346024461 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/JdbcResult.java0000664000175000017500000000564711757206346027401 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jdbc; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * JDBC result wrapper. Used by the JDBC client connector as a response entity * of JDBC calls. * * @author Jerome Louvel */ public class JdbcResult implements Serializable { private static final long serialVersionUID = 1L; /** The JDBC statement. */ private volatile transient Statement statement; /** * Constructor. * * @param statement * The JDBC statement. */ public JdbcResult(Statement statement) { this.statement = statement; } /** * Returns the generated keys. * * @return The generated keys. * @throws SQLException */ public ResultSet getGeneratedKeys() throws SQLException { return this.statement.getGeneratedKeys(); } /** * Returns the result set. * * @return The result set. * @throws SQLException */ public ResultSet getResultSet() throws SQLException { return this.statement.getResultSet(); } /** * Returns the update count. * * @return The update count. * @throws SQLException */ public int getUpdateCount() throws SQLException { return this.statement.getUpdateCount(); } /** * Release the statement connection. To call when result navigation is done. * * @throws SQLException */ public void release() throws SQLException { // One connection per jdbcResult // releasing the instance means releasing the connection too // and not only the statement. this.statement.getConnection().close(); } } restlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/JdbcConverter.java0000664000175000017500000000724111757206346030062 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jdbc; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.sql.rowset.WebRowSet; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * A converter helper to convert from {@link WebRowSet}, {@link JdbcResult} or * {@link ResultSet} objects to Representation. * * @author Thierry Boileau */ public class JdbcConverter extends ConverterHelper { @Override public List> getObjectClasses(Variant source) { return null; } @Override public List getVariants(Class source) { return null; } @Override public float score(Representation source, Class target, UniformResource resource) { return 0; } @Override public float score(Object source, Variant target, UniformResource resource) { if (source instanceof WebRowSet || source instanceof JdbcResult || source instanceof ResultSet) { return 1.0f; } return -1.0f; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { return null; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { if (source instanceof WebRowSet) { return new RowSetRepresentation((WebRowSet) source); } else if (source instanceof JdbcResult) { try { return new RowSetRepresentation((JdbcResult) source); } catch (SQLException e) { throw new IOException( "Cannot convert the JdbcResult source object as a RowSetRepresentation due to:" + e.getMessage()); } } else if (source instanceof ResultSet) { try { return new RowSetRepresentation((ResultSet) source); } catch (SQLException e) { throw new IOException( "Cannot convert the ResultSet source object as a RowSetRepresentation due to:" + e.getMessage()); } } return null; } } restlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/RowSetRepresentation.java0000664000175000017500000001513711757206346031501 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jdbc; import java.io.IOException; import java.io.Writer; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import javax.sql.rowset.WebRowSet; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.representation.WriterRepresentation; /** * XML Representation of a ResultSet instance wrapped either in a JdbcResult * instance or in a WebRowSet. Leverage the WebRowSet API to create the Response * entity.
* Give access to the JdbcResult instance and to the WebRowSet for retrieval of * the connected ResultSet in the same JVM (for advanced use cases). * * @see WebRowSet Interface * @author Thierry Boileau * @author Jerome Louvel */ public class RowSetRepresentation extends WriterRepresentation { /** * Creates a WebRowSet from a ResultSet. * * @param resultSet * The result set to use to populate the Web row set. * @param start * The start index of the page or 0 for the first result. * @param limit * The page size or -1 if no limit is set. * @return A WebRowSet from a ResultSet. * @throws SQLException */ private static WebRowSet create(ResultSet resultSet, int start, int limit) throws SQLException { WebRowSet result = null; try { result = (WebRowSet) Class.forName("com.sun.rowset.WebRowSetImpl") .newInstance(); } catch (Throwable t) { Context.getCurrentLogger().log(Level.WARNING, "Unable to instantiate the Sun's WebRowSet implementation", t); } if (resultSet != null) { if (limit > -1) { result.setPageSize(limit); result.setMaxRows(limit); } result.populate(resultSet, start < 0 ? 1 : start + 1); } return result; } /** JdbcResult instance that gives access to the resultSet. */ private volatile JdbcResult jdbcResult; /** Inner WebRowSet Instance. */ private volatile WebRowSet webRowSet; /** * Constructor. * * @param jdbcResult * The inner JdbcResult. * @throws SQLException */ public RowSetRepresentation(JdbcResult jdbcResult) throws SQLException { this(jdbcResult, -1, -1); } /** * Constructor with paging. * * @param jdbcResult * The inner JdbcResult. * @param start * The start index of the page or 0 for the first result. * @param limit * The page size or -1 if no limit is set. * @throws SQLException */ public RowSetRepresentation(JdbcResult jdbcResult, int start, int limit) throws SQLException { this(create((jdbcResult == null) ? null : jdbcResult.getResultSet(), start, limit)); this.jdbcResult = jdbcResult; } /** * Constructor. * * @param resultSet * The result set to use to populate the Web row set. * @throws SQLException */ public RowSetRepresentation(ResultSet resultSet) throws SQLException { this(resultSet, -1, -1); } /** * Constructor with paging. * * @param resultSet * The result set to use to populate the Web row set. * @param start * The start index of the page or 1 for the first result. * @param limit * The page size or -1 if no limit is set. * @throws SQLException */ public RowSetRepresentation(ResultSet resultSet, int start, int limit) throws SQLException { this(create(resultSet, start, limit)); } /** * Constructor. * * @param webRowSet * The inner WebRowSet. */ public RowSetRepresentation(WebRowSet webRowSet) { super(MediaType.TEXT_XML); this.webRowSet = webRowSet; } /** * Returns the inner JdbcResult instance or null. * * @return The inner JdbcResult instance or null. */ public JdbcResult getJdbcResult() { return this.jdbcResult; } /** * Returns the inner WebRowSet instance. * * @return The inner WebRowSet instance. */ public WebRowSet getWebRowSet() { return this.webRowSet; } @Override public void write(Writer writer) throws IOException { try { this.webRowSet.writeXml(writer); } catch (SQLException se) { throw new IOException(se.getMessage()); } try { if (this.jdbcResult != null) { this.jdbcResult.release(); } } catch (SQLException se) { throw new IOException( "SQL exception while releasing the JdbcResult instance after writing the representation. " + se.getMessage()); } try { if (this.webRowSet != null) { this.webRowSet.release(); this.webRowSet.close(); } } catch (SQLException se) { throw new IOException( "Error while releasing the WebRowSet instance after writing the representation. " + se.getMessage()); } } } restlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/internal/0000775000175000017500000000000011757206346026275 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/internal/ConnectionSource.java0000664000175000017500000000457611757206346032434 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jdbc.internal; import java.util.Properties; import org.apache.commons.dbcp.PoolingDataSource; import org.restlet.ext.jdbc.JdbcClientHelper; /** * Pooling data source which remembers its connection properties and URI. * * @author Jerome Louvel */ public class ConnectionSource extends PoolingDataSource { /** The connection properties. */ protected Properties properties; /** The connection URI. */ protected String uri; /** * Constructor. * * @param uri * The connection URI. * @param properties * The connection properties. */ public ConnectionSource(String uri, Properties properties) { super(JdbcClientHelper.createConnectionPool(uri, properties)); this.uri = uri; this.properties = properties; } /** * Returns the connection properties. * * @return The connection properties. */ public Properties getProperties() { return this.properties; } /** * Returns the connection URI. * * @return The connection URI. */ public String getUri() { return this.uri; } } restlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/package.html0000664000175000017500000000063111757206346026742 0ustar jamespagejamespage Integration with Java DataBase Connectivity (JDBC) 3.0. JDBC is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases - SQL databases and other tabular data sources, such as spreadsheets or flat files. @since Restlet 1.0 @see JDBC product page restlet-2.0.14/org.restlet.ext.jdbc/src/org/restlet/ext/jdbc/JdbcClientHelper.java0000664000175000017500000003316711757206346030477 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.pool.ObjectPool; import org.apache.commons.pool.impl.GenericObjectPool; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.ClientHelper; import org.restlet.engine.Engine; import org.restlet.ext.jdbc.internal.ConnectionSource; import org.restlet.representation.Representation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Client connector to a JDBC database. To send a request to the server, create * a new instance of a client supporting the JDBC Protocol and invoke the * handle() method. Alternatively, you can create a new {@link Request} with the * JDBC URI as the resource reference and use an XML request as the entity. *

* Database connections are optionally pooled using Apache Commons DBCP. In this * case, a different connection pool is created for each unique combination of * JDBC URI and connection properties. *

* Paging is supported via two header elements: "start" for the index of the * first result (0 by default) and "limit" for the maximum number of results * retrieved (unlimited by default). *

* Do not forget to register your JDBC drivers before using this client. See * JDBC DriverManager API for details. *

* Sample XML request:
*
* {@code }
* {@code }
*   {@code

}
*     {@code }
*       {@code true}
*       {@code scott}
*       {@code tiger}
*       {@code 1234}
*       {@code true}
*     {@code
}
*     {@code 10}
* 20}
* true}
*   {@code
}
*   {@code }
*     {@code UPDATE myTable SET * myField1="value1" }
*     {@code SELECT msField1, myField2 FROM * myTable}
*   {@code }
* {@code } *

* Several SQL Statements can be specified. A RowSetRepresentation of the last * correctly executed SQL request is returned to the Client. * * @see org.restlet.ext.jdbc.RowSetRepresentation * * @author Jerome Louvel * @author Thierry Boileau */ public class JdbcClientHelper extends ClientHelper { /** * Creates an uniform call. * * @param jdbcURI * The database's JDBC URI (ex: * jdbc:mysql://[hostname]/[database]). * @param request * The request to send (valid XML request). */ public static Request create(String jdbcURI, Representation request) { Request result = new Request(); result.getClientInfo().setAgent(Engine.VERSION_HEADER); result.setMethod(Method.POST); result.setResourceRef(jdbcURI); result.setEntity(request); return result; } /** * Creates a connection pool for a given connection configuration. * * @param uri * The connection URI. * @param properties * The connection properties. * @return The new connection pool. */ public static ObjectPool createConnectionPool(String uri, Properties properties) { // Create an ObjectPool that will serve as the actual pool of // connections ObjectPool result = new GenericObjectPool(null); // Create a ConnectionFactory that the pool will use to create // Connections ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( uri, properties); // Create the PoolableConnectionFactory, which wraps the "real" // Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( connectionFactory, result, null, null, false, false); // To remove warnings poolableConnectionFactory.getPool(); return result; } /** * Escapes quotes in a SQL query. * * @param query * The SQL query to escape. * @return The escaped SQL query. */ public static String sqlEncode(String query) { StringBuilder result = new StringBuilder(query.length() + 10); char currentChar; for (int i = 0; i < query.length(); i++) { currentChar = query.charAt(i); if (currentChar == '\'') { result.append("''"); } else { result.append(currentChar); } } return result.toString(); } /** Map of connection factories. */ private volatile List connectionSources; /** * Constructor. * * @param client * The client to help. */ public JdbcClientHelper(Client client) { super(client); getProtocols().add(Protocol.JDBC); // Set up the list of factories this.connectionSources = new ArrayList(); } /** * Returns a JDBC connection. * * @param uri * The connection URI. * @param properties * The connection properties. * @param usePooling * Indicates if the connection pooling should be used. * @return The JDBC connection. * @throws SQLException */ protected Connection getConnection(String uri, Properties properties, boolean usePooling) throws SQLException { Connection result = null; if (usePooling) { for (ConnectionSource c : this.connectionSources) { // Check if the connection URI is identical // and if the same number of properties is present if ((result == null) && c.getUri().equalsIgnoreCase(uri) && (properties.size() == c.getProperties().size())) { // Check that the properties tables are equivalent boolean equal = true; for (Object key : c.getProperties().keySet()) { if (equal && properties.containsKey(key)) { equal = equal && (properties.get(key).equals(c .getProperties().get(key))); } else { equal = false; } } if (equal) { result = c.getConnection(); } } } if (result == null) { // No existing connection source found ConnectionSource cs = new ConnectionSource(uri, properties); this.connectionSources.add(cs); result = cs.getConnection(); } } else { result = DriverManager.getConnection(uri, properties); } return result; } /** * Handles a call. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { Connection connection = null; if (request.getMethod().equals(Method.POST)) { try { // Parse the JDBC URI String connectionURI = request.getResourceRef().toString(); // Parse the request to extract necessary info DocumentBuilder docBuilder = DocumentBuilderFactory .newInstance().newDocumentBuilder(); Document requestDoc = docBuilder.parse(new InputSource(request .getEntity().getReader())); Element rootElt = (Element) requestDoc.getElementsByTagName( "request").item(0); Element headerElt = (Element) rootElt.getElementsByTagName( "header").item(0); Element connectionElt = (Element) headerElt .getElementsByTagName("connection").item(0); // Read the connection pooling setting Node usePoolingNode = connectionElt.getElementsByTagName( "usePooling").item(0); boolean usePooling = usePoolingNode.getTextContent().equals( "true") ? true : false; // Read the paging setting Node startNode = headerElt.getElementsByTagName("start") .item(0); int start = startNode != null && startNode.getTextContent().trim().length() > 0 ? Integer .parseInt(startNode.getTextContent()) : 0; Node limitNode = headerElt.getElementsByTagName("limit") .item(0); int limit = limitNode != null && limitNode.getTextContent().trim().length() > 0 ? Integer .parseInt(limitNode.getTextContent()) : -1; // Read the connection properties NodeList propertyNodes = connectionElt .getElementsByTagName("property"); Node propertyNode = null; Properties properties = null; String name = null; String value = null; for (int i = 0; i < propertyNodes.getLength(); i++) { propertyNode = propertyNodes.item(i); if (properties == null) { properties = new Properties(); } name = propertyNode.getAttributes().getNamedItem("name") .getTextContent(); value = propertyNode.getTextContent(); properties.setProperty(name, value); } Node returnGeneratedKeysNode = headerElt.getElementsByTagName( "returnGeneratedKeys").item(0); boolean returnGeneratedKeys = returnGeneratedKeysNode .getTextContent().equals("true") ? true : false; // Read the SQL body and get the list of sql statements Element bodyElt = (Element) rootElt .getElementsByTagName("body").item(0); NodeList statementNodes = bodyElt .getElementsByTagName("statement"); List sqlRequests = new ArrayList(); for (int i = 0; i < statementNodes.getLength(); i++) { String sqlRequest = statementNodes.item(i).getTextContent(); sqlRequests.add(sqlRequest); } // Execute the List of SQL requests connection = getConnection(connectionURI, properties, usePooling); JdbcResult result = handleSqlRequests(connection, returnGeneratedKeys, sqlRequests); response.setEntity(new RowSetRepresentation(result, start, limit)); } catch (SQLException se) { getLogger().log(Level.WARNING, "Error while processing the SQL request", se); response.setStatus(Status.SERVER_ERROR_INTERNAL, se); } catch (ParserConfigurationException pce) { getLogger().log(Level.WARNING, "Error with XML parser configuration", pce); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, pce); } catch (SAXException se) { getLogger().log(Level.WARNING, "Error while parsing the XML document", se); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, se); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Input/Output exception", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); } } else { throw new IllegalArgumentException( "Only the POST method is supported"); } } /** * Helper * * @param connection * @param returnGeneratedKeys * @param sqlRequests * @return the result of the last executed SQL request */ private JdbcResult handleSqlRequests(Connection connection, boolean returnGeneratedKeys, List sqlRequests) { JdbcResult result = null; try { connection.setAutoCommit(true); Statement statement = connection.createStatement(); for (String sqlRequest : sqlRequests) { statement.execute(sqlRequest, returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); result = new JdbcResult(statement); } // Commit any changes to the database if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException se) { getLogger().log(Level.WARNING, "Error while processing the SQL requests", se); try { if (!connection.getAutoCommit()) { connection.rollback(); } } catch (SQLException se2) { getLogger().log(Level.WARNING, "Error while rollbacking the transaction", se); } } return result; } } restlet-2.0.14/org.restlet.ext.ssl/0000775000175000017500000000000012001473131017573 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.ssl/pom.xml0000600000175000017500000000157412001473131021105 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.ssl Restlet Extension - SSL support Utilities to configure SSL support. org.jsslutils jsslutils 1.0.5 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.ssl/src/0000775000175000017500000000000012001473131020362 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.ssl/src/META-INF/0000775000175000017500000000000011757206452021543 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.ssl/src/META-INF/MANIFEST.MF0000664000175000017500000000016411757206450023174 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) Class-Path: restlet-2.0.14/org.restlet.ext.ssl/src/org/0000775000175000017500000000000011757206344021172 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.ssl/src/org/restlet/0000775000175000017500000000000011757206344022654 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.ssl/src/org/restlet/ext/0000775000175000017500000000000011757206344023454 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.ssl/src/org/restlet/ext/ssl/0000775000175000017500000000000011757206344024255 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.ssl/src/org/restlet/ext/ssl/PkixSslContextFactory.java0000664000175000017500000002303311757206344031413 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.ssl; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.security.auth.callback.UnsupportedCallbackException; import org.jsslutils.keystores.KeyStoreLoader; import org.jsslutils.sslcontext.PKIXSSLContextFactory; import org.jsslutils.sslcontext.SSLContextFactory.SSLContextFactoryException; import org.jsslutils.sslcontext.keymanagers.FixedServerAliasKeyManager; import org.restlet.data.Parameter; import org.restlet.engine.security.DefaultSslContextFactory; import org.restlet.engine.security.SslContextFactory; import org.restlet.util.Series; /** * This SslContextFactory uses PKIXSSLContextFactory from jSSLutils and can be * configured via parameters. * * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) */ public class PkixSslContextFactory extends SslContextFactory { private String sslProtocol = "TLS"; private PKIXSSLContextFactory sslContextFactory; /** * Creates a configured and initialised SSLContext by delegating the call to * the PKIXSSLContextFactory with has been initialised using 'init'. * * @see PKIXSSLContextFactory#buildSSLContext() */ @Override public SSLContext createSslContext() throws Exception { synchronized (this) { return this.sslContextFactory.buildSSLContext(this.sslProtocol); } } /** * Sets the following options according to parameters that may have been set * up directly in the HttpsServerHelper parameters. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Parameter nameValue typeDefault valueDescription
keystorePathStringjavax.net.ssl.keyStore system propertySSL keystore path.
keystorePasswordStringjavax.net.ssl.keyStorePassword system propertySSL keystore password.
keystoreTypeStringjavax.net.ssl.keyStoreType system property, otherwise default typeSSL keystore type
keystoreProviderStringjavax.net.ssl.keyStoreProvider system property, otherwise default * providerSSL keystore provider
keyPasswordStringSSL key password.
truststorePathStringjavax.net.ssl.trustStore system propertySSL truststore path.
truststorePasswordStringjavax.net.ssl.trustStorePassword system propertySSL truststore password.
truststoreTypeStringjavax.net.ssl.trustStoreType system property, otherwise default typeSSL truststore type
truststoreProviderStringjavax.net.ssl.trustStoreProvider system property, otherwise default * providerSSL truststore provider
sslServerAliasStringalias to use on the server side
sslProtocolString: TLS/SSLv3TLSSSL protocol
disableCrlString (true/false)falseSet to true if you want not to use the CRLs
crlUrlString (URL)URL of CRL to load (there can be multiple occurrences of this * parameter).
* * @param parameters * Typically, the parameters that would have been obtained from * HttpsServerHelper.getParameters() * */ @Override public void init(Series parameters) { KeyStoreLoader keyStoreLoader = KeyStoreLoader .getKeyStoreDefaultLoader(); String keyStorePath = parameters.getFirstValue("keystorePath"); if (keyStorePath != null) { keyStoreLoader.setKeyStorePath(keyStorePath); } String keyStorePassword = parameters.getFirstValue("keystorePassword"); if (keyStorePassword != null) { keyStoreLoader.setKeyStorePassword(keyStorePassword); } String keyStoreType = parameters.getFirstValue("keystoreType"); if (keyStoreType != null) { keyStoreLoader.setKeyStoreType(keyStoreType); } String keyStoreProvider = parameters.getFirstValue("keystoreProvider"); if (keyStoreProvider != null) { keyStoreLoader.setKeyStoreProvider(keyStoreProvider); } KeyStoreLoader trustStoreLoader = KeyStoreLoader .getTrustStoreDefaultLoader(); String trustStorePath = parameters.getFirstValue("truststorePath"); if (trustStorePath != null) { trustStoreLoader.setKeyStorePath(trustStorePath); } String trustStorePassword = parameters .getFirstValue("truststorePassword"); if (trustStorePassword != null) { trustStoreLoader.setKeyStorePassword(trustStorePassword); } String trustStoreType = parameters.getFirstValue("truststoreType"); if (trustStoreType != null) { trustStoreLoader.setKeyStoreType(trustStoreType); } String trustStoreProvider = parameters .getFirstValue("truststoreProvider"); if (trustStoreProvider != null) { trustStoreLoader.setKeyStoreProvider(trustStoreProvider); } String keyPassword = parameters.getFirstValue("keyPassword", ""); String sslProtocol = parameters.getFirstValue("sslProtocol"); String serverAlias = parameters.getFirstValue("sslServerAlias"); boolean disableRevocation = Boolean.parseBoolean(parameters .getFirstValue("disableCrl")); try { KeyStore keyStore = keyStoreLoader.loadKeyStore(); KeyStore trustStore = trustStoreLoader.loadKeyStore(); PKIXSSLContextFactory sslContextFactory = new PKIXSSLContextFactory( keyStore, keyPassword, trustStore, !disableRevocation); if (serverAlias != null) { sslContextFactory .setKeyManagerWrapper(new FixedServerAliasKeyManager.Wrapper( serverAlias)); } String[] crlArray = parameters.getValuesArray("crlUrl"); if (crlArray != null) { for (String crlUrl : crlArray) { sslContextFactory.addCrl(crlUrl); } } synchronized (this) { this.sslContextFactory = sslContextFactory; if (sslProtocol != null) { this.sslProtocol = sslProtocol; } } } catch (SSLContextFactoryException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (NoSuchProviderException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (CertificateException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (UnsupportedCallbackException e) { throw new RuntimeException(e); } } /** * This class is likely to contain sensitive information; cloning is * therefore not allowed. */ @Override protected final DefaultSslContextFactory clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } restlet-2.0.14/org.restlet.ext.ssl/src/org/restlet/ext/ssl/package.html0000664000175000017500000000027111757206344026536 0ustar jamespagejamespage Support for SSL utilities and integration with jSSLutils library. @since Restlet 1.1 @see jSSLutils home restlet-2.0.14/org.restlet.ext.ssl/src/org/restlet/ext/ssl/JsslutilsSslContextFactory.java0000664000175000017500000000572411757206344032503 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.ssl; import javax.net.ssl.SSLContext; import org.jsslutils.sslcontext.SSLContextFactory; import org.restlet.data.Parameter; import org.restlet.engine.security.SslContextFactory; import org.restlet.util.Series; /** * This SslContextFactory is a wrapper for the SSLContextFactory of jSSLutils. * * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) */ public class JsslutilsSslContextFactory extends SslContextFactory { /** * The wrapped SSLContextFactory. */ private final SSLContextFactory sslContextFactory; /** * Builds JsslutilsSslContextFactory that wraps an instance of * jsslutils.sslcontext.SSLContextFactory. * * @param sslContextFactory * SSLContextFactory (from jSSLutils) to wrap. */ public JsslutilsSslContextFactory(SSLContextFactory sslContextFactory) { this.sslContextFactory = sslContextFactory; } /** * Creates a configured and initialised SSLContext by delegating the call to * the SSLContextFactory with which the target instance was built. Please * set the SSLContext protocol in that factory; it is 'SSLv3' in version 0.3 * of jSSLutils. * * @see SSLContextFactory#buildSSLContext() */ @Override public SSLContext createSslContext() throws Exception { return this.sslContextFactory.buildSSLContext(); } /** * Returns the wrapped SSLContextFactory with which this instance was built. * * @return the wrapped SSLContextFactory. */ public SSLContextFactory getSslContextFactory() { return this.sslContextFactory; } @Override public void init(Series parameters) { } } restlet-2.0.14/org.restlet.ext.rdf/0000775000175000017500000000000012001473146017553 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/pom.xml0000600000175000017500000000161012001473146021054 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.rdf Restlet Extension - RDF Support for the RDF parsing and generation. org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 restlet-2.0.14/org.restlet.ext.rdf/src/0000775000175000017500000000000012001473146020342 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/META-INF/0000775000175000017500000000000011757206452021515 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/META-INF/services/0000775000175000017500000000000011757206350023335 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.rdf/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.rdf/src/META-INF/services/org.restlet.engine.converter.ConverterHelpe0000664000175000017500000000004011757206350033720 0ustar jamespagejamespageorg.restlet.ext.rdf.RdfConverterrestlet-2.0.14/org.restlet.ext.rdf/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023146 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.rdf/src/org/0000775000175000017500000000000011757206350021141 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/0000775000175000017500000000000011757206350022623 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/0000775000175000017500000000000011757206350023423 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/0000775000175000017500000000000011757206350024176 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/GraphBuilder.java0000664000175000017500000000512711757206350027416 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import org.restlet.data.Reference; /** * Graph handler used when parsing an RDF representation. It completes the inner * set of links with all detected ones. */ public class GraphBuilder extends GraphHandler { /** The inner graph of links. */ private Graph linkSet; /** * * @param linkSet * The graph of links. */ public GraphBuilder(Graph linkSet) { super(); this.linkSet = linkSet; } @Override public void link(Graph source, Reference typeRef, Literal target) { if (source != null && typeRef != null && target != null) { this.linkSet.add(source, typeRef, target); } } @Override public void link(Graph source, Reference typeRef, Reference target) { if (source != null && typeRef != null && target != null) { this.linkSet.add(source, typeRef, target); } } @Override public void link(Reference source, Reference typeRef, Literal target) { if (source != null && typeRef != null && target != null) { this.linkSet.add(source, typeRef, target); } } @Override public void link(Reference source, Reference typeRef, Reference target) { if (source != null && typeRef != null && target != null) { this.linkSet.add(source, typeRef, target); } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/0000775000175000017500000000000011757206350026012 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/RdfConstants.java0000664000175000017500000000733311757206350031273 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal; import org.restlet.data.Reference; /** * Constants related to RDF documents. * * @author Thierry Boileau */ public class RdfConstants { /** List "first". */ public static final Reference LIST_FIRST = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#first"); /** List "rest". */ public static final Reference LIST_REST = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"); /** Object "nil". */ public static final Reference OBJECT_NIL = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"); /** Predicate "implies" . */ public static final Reference PREDICATE_IMPLIES = new Reference( "http://www.w3.org/2000/10/swap/log#implies"); /** Predicate "object". */ public static final Reference PREDICATE_OBJECT = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#object"); /** Predicate "predicate". */ public static final Reference PREDICATE_PREDICATE = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"); /** Predicate "same as". */ public static final Reference PREDICATE_SAME = new Reference( "http://www.w3.org/2002/07/owl#sameAs"); /** Predicate "statement". */ public static final Reference PREDICATE_STATEMENT = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"); /** Predicate "subject". */ public static final Reference PREDICATE_SUBJECT = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject"); /** Predicate "is a". */ public static final Reference PREDICATE_TYPE = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); /** Rdf schema. */ public static final Reference RDF_SCHEMA = new Reference( "http://www.w3.org/2000/01/rdf-schema#"); /** Rdf syntax. */ public static final Reference RDF_SYNTAX = new Reference( "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); /** XML schema. */ public static final Reference XML_SCHEMA = new Reference( "http://www.w3.org/2001/XMLSchema#"); /** Float type of the XML schema. */ public static final Reference XML_SCHEMA_TYPE_FLOAT = new Reference( "http://www.w3.org/2001/XMLSchema#float"); /** Integer type of the XML schema. */ public static final Reference XML_SCHEMA_TYPE_INTEGER = new Reference( "http://www.w3.org/2001/XMLSchema#int"); } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/ntriples/0000775000175000017500000000000011757206350027652 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/ntriples/RdfNTriplesReader.java0000664000175000017500000003343411757206350034043 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.ntriples; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.data.Reference; import org.restlet.engine.io.IoUtils; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Link; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.internal.RdfReader; import org.restlet.representation.Representation; /** * Handler of RDF content according to the N-Triples notation. * * @author Thierry Boileau */ public class RdfNTriplesReader extends RdfReader { /** Internal buffered reader. */ private BufferedReader br; /** The reading buffer. */ private final char[] buffer; /** Size of the reading buffer. */ private final int BUFFER_SIZE = 4096; /** End of reading buffer marker. */ public final int EOF = 0; /** * Index that discovers the end of the current token and the beginning of * the futur one. */ private int scoutIndex; /** Start index of current lexical unit. */ private int startTokenIndex; /** * Constructor. * * @param rdfRepresentation * The representation to read. * @param graphHandler * The graph handler invoked during the parsing. * @throws IOException */ public RdfNTriplesReader(Representation rdfRepresentation, GraphHandler graphHandler) throws IOException { super(rdfRepresentation, graphHandler); // Initialize the buffer in two parts this.buffer = new char[(BUFFER_SIZE + 1) * 2]; // Mark the upper index of each part. this.buffer[BUFFER_SIZE] = this.buffer[2 * BUFFER_SIZE + 1] = EOF; this.scoutIndex = 2 * BUFFER_SIZE; this.startTokenIndex = 0; this.br = new BufferedReader(getRdfRepresentation().getReader(), IoUtils.getBufferSize()); } /** * Discard all read characters until the end of the statement is reached * (marked by a '.'). * * @throws IOException */ protected void consumeStatement() throws IOException { int c = getChar(); while (!isEndOfFile(c) && c != '.') { c = step(); } if (getChar() == '.') { // A further step at the right of the statement. step(); } discard(); } /** * Discard all read characters. A call to {@link getCurrentToken} will * return a single character. * * @throws IOException */ protected void consumeWhiteSpaces() throws IOException { while (isWhiteSpace(getChar())) { step(); } discard(); } /** * Discard all read characters. A call to {@link getCurrentToken} will * return a single character. */ protected void discard() { startTokenIndex = scoutIndex; } /** * Returns the current parsed character. * * @return The current parsed character. */ protected char getChar() { return buffer[scoutIndex]; } /** * Returns the current token. * * @return The current token. */ protected String getCurrentToken() { StringBuilder builder = new StringBuilder(); if (startTokenIndex <= scoutIndex) { if (scoutIndex <= BUFFER_SIZE) { for (int i = startTokenIndex; i < scoutIndex; i++) { builder.append(buffer[i]); } } else { for (int i = startTokenIndex; i < BUFFER_SIZE; i++) { builder.append(buffer[i]); } for (int i = BUFFER_SIZE + 1; i < scoutIndex; i++) { builder.append(buffer[i]); } } } else { if (startTokenIndex <= BUFFER_SIZE) { for (int i = startTokenIndex; i < BUFFER_SIZE; i++) { builder.append(buffer[i]); } for (int i = BUFFER_SIZE + 1; i < (2 * BUFFER_SIZE + 1); i++) { builder.append(buffer[i]); } for (int i = 0; i < scoutIndex; i++) { builder.append(buffer[i]); } } else { for (int i = startTokenIndex; i < (2 * BUFFER_SIZE + 1); i++) { builder.append(buffer[i]); } for (int i = 0; i < scoutIndex; i++) { builder.append(buffer[i]); } } } // the current token is consumed. startTokenIndex = scoutIndex; return builder.toString(); } /** * Returns a message describing the current state of the parsing process. * * @return A message describing the current state of the parsing process. */ public String getParsingMessage() { return getParsingMessage(buffer, startTokenIndex, scoutIndex); } /** * Returns a message describing the current state of the parsing process. * * @param buffer * The current buffer. * @param startTokenIndex * The start index of parsing. * @param scoutIndex * The index of the probable future token. * @return */ protected String getParsingMessage(char[] buffer, int startTokenIndex, int scoutIndex) { StringBuilder sb = new StringBuilder("Parsing data ["); sb.append(startTokenIndex); sb.append(","); sb.append(scoutIndex); sb.append("] near "); if (startTokenIndex < 25) { sb.append(buffer, buffer.length - 30, 28); sb.append(buffer, 0, 25); } else if (startTokenIndex > (buffer.length - 25)) { sb.append(buffer, buffer.length - 30, 28); sb.append(buffer, 0, 20); } else { sb.append(buffer, startTokenIndex - 25, 50); } return sb.toString(); } /** * Returns true if the given character is alphanumeric. * * @param c * The given character to check. * @return true if the given character is alphanumeric. */ protected boolean isAlphaNum(int c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); } /** * Returns true if the given character is a delimiter. * * @param c * The given character to check. * @return true if the given character is a delimiter. */ protected boolean isDelimiter(int c) { return isWhiteSpace(c) || c == '"' || c == '.'; } protected boolean isEndOfFile(int c) { return c == EOF; } /** * Returns true if the given character is a whitespace. * * @param c * The given character to check. * @return true if the given character is a whitespace. */ protected boolean isWhiteSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; } /** * Parses the current representation. * * @throws IOException */ @Override public void parse() throws Exception { // Init the reading. step(); do { consumeWhiteSpaces(); switch (getChar()) { case '#': parseComment(); break; case '.': step(); break; default: parseStatement(); break; } } while (!isEndOfFile(getChar())); } /** * Parses a comment. * * @throws IOException */ protected void parseComment() throws IOException { int c; do { c = step(); } while (!isEndOfFile(getChar()) && c != '\n' && c != '\r'); discard(); } /** * Reads the current statement until its end, and parses it. * * @param context * The current context. * @throws Exception */ protected void parseStatement() throws Exception { List lexicalUnits = new ArrayList(); String object = null; do { consumeWhiteSpaces(); switch (getChar()) { case '<': lexicalUnits.add(new Reference(parseUri())); break; case '_': lexicalUnits.add(Link.createBlankRef(parseToken())); break; case '"': int c = step(); discard(); while (!isEndOfFile(c) && (c != '"')) { c = step(); } object = getCurrentToken(); step(); discard(); break; case '.': break; case '#': parseComment(); break; case EOF: break; default: throw new Exception( "This document does not seem to follow the N-Triples syntax. " + getParsingMessage()); } } while (!isEndOfFile(getChar()) && getChar() != '.' && getChar() != '}'); // Generate the links if (!lexicalUnits.isEmpty()) { if (object != null) { getGraphHandler().link(lexicalUnits.get(0), lexicalUnits.get(1), new Literal(object)); } else { getGraphHandler().link(lexicalUnits.get(0), lexicalUnits.get(1), lexicalUnits.get(2)); } } } /** * Returns the value of the current token. * * @return The value of the current token. * @throws IOException */ protected String parseToken() throws IOException { int c; do { c = step(); } while (!isEndOfFile(c) && !isDelimiter(c)); String result = getCurrentToken(); return result; } /** * Returns the value of the current URI. * * @return The value of the current URI. * @throws IOException */ protected String parseUri() throws IOException { StringBuilder builder = new StringBuilder(); // Suppose the current character is "<". int c = step(); while (c != EOF && c != '>') { if (!isWhiteSpace(c)) { // Discard white spaces. builder.append((char) c); } c = step(); } if (c == '>') { // Set the cursor at the right of the uri. step(); } discard(); return builder.toString(); } /** * Read a new character. * * @return The new read character. * @throws IOException */ protected int step() throws IOException { scoutIndex++; if (buffer[scoutIndex] == EOF) { if (scoutIndex == BUFFER_SIZE) { // Reached the end of the first part of the buffer, read into // the second one. scoutIndex++; int len = this.br.read(buffer, 0, BUFFER_SIZE); if (len == -1) { // End of the stream reached buffer[scoutIndex] = EOF; } else { buffer[BUFFER_SIZE + len + 1] = EOF; } } else if (scoutIndex == (2 * BUFFER_SIZE + 1)) { scoutIndex = 0; // Reached the end of the second part of the buffer, read into // the first one. int len = this.br.read(buffer, 0, BUFFER_SIZE); if (len == -1) { // End of the stream reached buffer[scoutIndex] = EOF; } else { buffer[len] = EOF; } } else { // Reached the end of the stream. } } return buffer[scoutIndex]; } /** * Steps forward. * * @param n * The number of steps to go forward. * @throws IOException */ protected void step(int n) throws IOException { for (int i = 0; i < n; i++) { step(); } } /** * Steps back of one step. * */ protected void stepBack() { stepBack(1); } /** * Steps back. * * @param n * The number of steps to go back. */ protected void stepBack(int n) { scoutIndex -= n; if (scoutIndex < 0) { scoutIndex = BUFFER_SIZE * 2 + 1 - scoutIndex; } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/ntriples/RdfNTriplesWriter.java0000664000175000017500000001057111757206350034112 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.ntriples; import java.io.IOException; import java.io.Writer; import org.restlet.data.Reference; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Link; import org.restlet.ext.rdf.Literal; /** * Handler of RDF content according to the N-Triples notation. * * @author Thierry Boileau */ public class RdfNTriplesWriter extends GraphHandler { /** The character writer. */ private Writer writer; /** * Constructor. * * @param writer * The character writer. * @throws IOException */ public RdfNTriplesWriter(Writer writer) throws IOException { super(); this.writer = writer; } @Override public void endGraph() throws IOException { this.writer.flush(); } @Override public void link(Graph source, Reference typeRef, Literal target) { org.restlet.Context.getCurrentLogger().warning( "Subjects as Graph are not supported in N-Triples."); } @Override public void link(Graph source, Reference typeRef, Reference target) { org.restlet.Context.getCurrentLogger().warning( "Subjects as Graph are not supported in N-Triples."); } @Override public void link(Reference source, Reference typeRef, Literal target) { try { write(source); this.writer.write(" "); write(typeRef); this.writer.write(" "); write(target); this.writer.write(".\n"); } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to: " + e.getMessage()); } } @Override public void link(Reference source, Reference typeRef, Reference target) { try { write(source); this.writer.write(" "); write(typeRef); this.writer.write(" "); write(target); this.writer.write(".\n"); } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to: " + e.getMessage()); } } /** * Writes the representation of a literal. * * @param literal * The literal to write. * @throws IOException */ private void write(Literal literal) throws IOException { // Write it as a string this.writer.write("\""); this.writer.write(literal.getValue()); this.writer.write("\""); } /** * Writes the representation of a given reference. * * @param reference * The reference to write. * @throws IOException */ private void write(Reference reference) throws IOException { String uri = reference.toString(); if (Link.isBlankRef(reference)) { this.writer.write(uri); } else { this.writer.append("<"); this.writer.append(uri); this.writer.append(">"); } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/RdfReader.java0000664000175000017500000000513011757206350030512 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal; import java.io.IOException; import org.restlet.ext.rdf.GraphHandler; import org.restlet.representation.Representation; /** * Super class of all RDF readers. * */ public abstract class RdfReader { /** The graph handler invoked when parsing. */ private GraphHandler graphHandler; /** The representation to read. */ private Representation rdfRepresentation; /** * Constructor. * * @param rdfRepresentation * The representation to read. * @param graphHandler * The graph handler invoked during the parsing. * @throws IOException */ public RdfReader(Representation rdfRepresentation, GraphHandler graphHandler) { super(); this.rdfRepresentation = rdfRepresentation; this.graphHandler = graphHandler; } /** * Returns the graph handler invoked when parsing. * * @return The graph handler invoked when parsing. */ public GraphHandler getGraphHandler() { return graphHandler; } /** * Returns the representation to read. * * @return The representation to read. */ public Representation getRdfRepresentation() { return rdfRepresentation; } /** * Parses the content. * * @throws Exception */ public abstract void parse() throws Exception; } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/0000775000175000017500000000000011757206350026612 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ContentReader.java0000664000175000017500000005754011757206350032225 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.xml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.data.Language; import org.restlet.data.Reference; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Link; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.RdfRepresentation; import org.restlet.ext.rdf.internal.RdfConstants; import org.restlet.representation.Representation; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Content reader part. * * @author Thierry Boileau */ class ContentReader extends DefaultHandler { public enum State { LITERAL, NONE, OBJECT, PREDICATE, SUBJECT } /** Increment used to identify inner blank nodes. */ private static int blankNodeId = 0; /** * Returns the identifier of a new blank node. * * @return The identifier of a new blank node. */ private static String newBlankNodeId() { return "#_bn" + blankNodeId++; } /** The value of the "base" URI. */ private ScopedProperty base; /** Container for string content. */ private StringBuilder builder; /** Indicates if the string content must be consumed. */ private boolean consumingContent; /** Current data type. */ private String currentDataType; /** Current language. */ private ScopedProperty language; /** Current object. */ private Object currentObject; /** Current predicate. */ private Reference currentPredicate; /** The graph handler to call when a link is detected. */ private GraphHandler graphHandler; /** Used to get the content of XMl literal. */ private int nodeDepth; /** The list of known prefixes. */ private Map prefixes; /** * True if {@link RdfRepresentation#RDF_SYNTAX} is the default namespace. */ private boolean rdfDefaultNamespace; /** Used when a statement must be reified. */ private Reference reifiedRef; /** Heap of states. */ private List states; /** Heap of subjects. */ private List subjects; /** * * * @param graphHandler * */ /** * Constructor. * * @param graphHandler * The graph handler to call when a link is detected. * @param representation * The input representation. */ public ContentReader(Representation representation, GraphHandler graphHandler) { super(); this.graphHandler = graphHandler; this.base = new ScopedProperty(); this.language = new ScopedProperty(); if (representation.getLocationRef() != null) { this.base.add(representation.getLocationRef().getTargetRef()); this.base.incrDepth(); } if (representation.getLanguages().size() == 1) { this.language.add(representation.getLanguages().get(1)); this.language.incrDepth(); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (consumingContent) { builder.append(ch, start, length); } } /** * Returns true if the given qualified name is in the RDF namespace and is * equal to the given local name. * * @param localName * The local name to compare to. * @param qName * The qualified name */ private boolean checkRdfQName(String localName, String qName) { boolean result = qName.equals("rdf:" + localName); if (!result) { int index = qName.indexOf(":"); // The qualified name has no prefix. result = rdfDefaultNamespace && (index == -1) && localName.equals(qName); } return result; } @Override public void endDocument() throws SAXException { this.builder = null; this.currentObject = null; this.currentPredicate = null; this.graphHandler = null; this.prefixes.clear(); this.prefixes = null; this.states.clear(); this.states = null; this.subjects.clear(); this.subjects = null; this.nodeDepth = 0; } @Override public void endElement(String uri, String localName, String name) throws SAXException { ContentReader.State state = popState(); if (state == State.SUBJECT) { popSubject(); } else if (state == State.PREDICATE) { if (this.consumingContent) { link(getCurrentSubject(), this.currentPredicate, getLiteral( builder.toString(), null, this.language.getValue())); this.consumingContent = false; } } else if (state == State.OBJECT) { } else if (state == State.LITERAL) { if (nodeDepth == 0) { // End of the XML literal link(getCurrentSubject(), this.currentPredicate, getLiteral( builder.toString(), this.currentDataType, this.language .getValue())); } else { // Still gleaning the content of an XML literal // Glean the XML content this.builder.append(""); nodeDepth--; pushState(state); } } this.base.decrDepth(); this.language.decrDepth(); } @Override public void endPrefixMapping(String prefix) throws SAXException { this.prefixes.remove(prefix); } /** * Returns the state at the top of the heap. * * @return The state at the top of the heap. */ private ContentReader.State getCurrentState() { ContentReader.State result = null; int size = this.states.size(); if (size > 0) { result = this.states.get(size - 1); } return result; } /** * Returns the subject at the top of the heap. * * @return The subject at the top of the heap. */ private Reference getCurrentSubject() { Reference result = null; int size = this.subjects.size(); if (size > 0) { result = this.subjects.get(size - 1); } return result; } /** * Returns a Literal object according to the given parameters. * * @param value * The value of the literal. * @param datatype * The datatype of the literal. * @param language * The language of the literal. * @return A Literal object */ private Literal getLiteral(String value, String datatype, Language language) { Literal literal = new Literal(value); if (datatype != null) { literal.setDatatypeRef(new Reference(datatype)); } if (language != null) { literal.setLanguage(language); } return literal; } /** * A new statement has been detected with the current subject, predicate and * object. */ private void link() { Reference currentSubject = getCurrentSubject(); if (currentSubject != null) { if (this.currentObject instanceof Reference) { link(currentSubject, this.currentPredicate, (Reference) this.currentObject); } else if (this.currentObject instanceof Literal) { link(currentSubject, this.currentPredicate, (Literal) this.currentObject); } else { org.restlet.Context .getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } } else { org.restlet.Context .getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the subject is not a Reference."); } } /** * Creates a statement and reify it, if necessary. * * @param subject * The subject of the statement. * @param predicate * The predicate of the statement. * @param object * The object of the statement. */ private void link(Reference subject, Reference predicate, Literal object) { this.graphHandler.link(subject, predicate, object); if (this.reifiedRef != null) { this.graphHandler.link(this.reifiedRef, RdfConstants.PREDICATE_SUBJECT, subject); this.graphHandler.link(this.reifiedRef, RdfConstants.PREDICATE_PREDICATE, predicate); this.graphHandler.link(this.reifiedRef, RdfConstants.PREDICATE_OBJECT, object); this.graphHandler.link(reifiedRef, RdfConstants.PREDICATE_TYPE, RdfConstants.PREDICATE_STATEMENT); this.reifiedRef = null; } } /** * Creates a statement and reify it, if necessary. * * @param subject * The subject of the statement. * @param predicate * The predicate of the statement. * @param object * The object of the statement. */ private void link(Reference subject, Reference predicate, Reference object) { this.graphHandler.link(subject, predicate, object); if (this.reifiedRef != null) { this.graphHandler.link(this.reifiedRef, RdfConstants.PREDICATE_SUBJECT, subject); this.graphHandler.link(this.reifiedRef, RdfConstants.PREDICATE_PREDICATE, predicate); this.graphHandler.link(this.reifiedRef, RdfConstants.PREDICATE_OBJECT, object); this.graphHandler.link(reifiedRef, RdfConstants.PREDICATE_TYPE, RdfConstants.PREDICATE_STATEMENT); this.reifiedRef = null; } } /** * Returns the RDF URI of the given node represented by its namespace uri, * local name, name, and attributes. It also generates the available * statements, thanks to some shortcuts provided by the RDF XML syntax. * * @param uri * @param localName * @param name * @param attributes * @return The RDF URI of the given node. */ private Reference parseNode(String uri, String localName, String name, Attributes attributes) { Reference result = null; // Stores the arcs List arcs = new ArrayList(); boolean found = false; if (attributes.getIndex("xml:base") != -1) { this.base.add(new Reference(attributes.getValue("xml:base"))); } // Get the RDF URI of this node for (int i = 0; i < attributes.getLength(); i++) { String qName = attributes.getQName(i); if (checkRdfQName("about", qName)) { found = true; result = resolve(attributes.getValue(i), false); } else if (checkRdfQName("nodeID", qName)) { found = true; result = Link.createBlankRef(attributes.getValue(i)); } else if (checkRdfQName("ID", qName)) { found = true; result = resolve(attributes.getValue(i), true); } else if ("xml:lang".equals(qName)) { this.language.add(Language.valueOf(attributes.getValue(i))); } else if ("xml:base".equals(qName)) { // Already stored } else { if (!qName.startsWith("xmlns")) { String[] arc = { qName, attributes.getValue(i) }; arcs.add(arc); } } } if (!found) { // Blank node with no given ID result = Link.createBlankRef(ContentReader.newBlankNodeId()); } // Create the available statements if (!checkRdfQName("Description", name)) { // Handle typed node this.graphHandler.link(result, RdfConstants.PREDICATE_TYPE, resolve(uri, name)); } for (String[] arc : arcs) { this.graphHandler.link(result, resolve(null, arc[0]), getLiteral( arc[1], null, this.language.getValue())); } return result; } /** * Returns the state at the top of the heap and removes it from the heap. * * @return The state at the top of the heap. */ private ContentReader.State popState() { ContentReader.State result = null; int size = this.states.size(); if (size > 0) { result = this.states.remove(size - 1); } return result; } /** * Returns the subject at the top of the heap and removes it from the heap. * * @return The subject at the top of the heap. */ private Reference popSubject() { Reference result = null; int size = this.subjects.size(); if (size > 0) { result = this.subjects.remove(size - 1); } return result; } /** * Adds a new state at the top of the heap. * * @param state * The state to add. */ private void pushState(ContentReader.State state) { this.states.add(state); } /** * Adds a new subject at the top of the heap. * * @param subject * The subject to add. */ private void pushSubject(Reference subject) { this.subjects.add(subject); } /** * Returns the absolute reference for a given value. If this value is not an * absolute URI, then the base URI is used. * * @param value * The value. * @param fragment * True if the value is a fragment to add to the base reference. * @return Returns the absolute reference for a given value. */ private Reference resolve(String value, boolean fragment) { Reference result = null; if (fragment) { result = new Reference(this.base.getValue()); result.setFragment(value); } else { result = new Reference(value); if (result.isRelative()) { result = new Reference(this.base.getValue(), value); } } return result.getTargetRef(); } /** * Returns the absolute reference of a parsed element according to its URI, * qualified name. In case the base URI is null or empty, then an attempt is * made to look for the mapped URI according to the qName. * * @param uri * The base URI. * @param qName * The qualified name of the parsed element. * @return Returns the absolute reference of a parsed element. */ private Reference resolve(String uri, String qName) { Reference result = null; int index = qName.indexOf(":"); String prefix = null; String localName = null; if (index != -1) { prefix = qName.substring(0, index); localName = qName.substring(index + 1); } else { localName = qName; prefix = ""; } if (uri != null && !"".equals(uri)) { if (!uri.endsWith("#") && !uri.endsWith("/")) { result = new Reference(uri + "/" + localName); } else { result = new Reference(uri + localName); } } else { String baseUri = this.prefixes.get(prefix); if (baseUri != null) { result = new Reference(baseUri + localName); } } return (result == null) ? null : result.getTargetRef(); } @Override public void startDocument() throws SAXException { this.prefixes = new HashMap(); this.builder = new StringBuilder(); this.states = new ArrayList(); this.subjects = new ArrayList(); nodeDepth = 0; pushState(State.NONE); } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { ContentReader.State state = getCurrentState(); this.base.incrDepth(); this.language.incrDepth(); if (!this.consumingContent && this.builder != null) { this.builder = null; } if (state == State.NONE) { if (checkRdfQName("RDF", name)) { // Top element String base = attributes.getValue("xml:base"); if (base != null) { this.base.add(new Reference(base)); } } else { // Parse the current subject pushSubject(parseNode(uri, localName, name, attributes)); pushState(State.SUBJECT); } } else if (state == State.SUBJECT) { // Parse the current predicate List arcs = new ArrayList(); pushState(State.PREDICATE); this.consumingContent = true; Reference currentSubject = getCurrentSubject(); this.currentPredicate = resolve(uri, name); Reference currentObject = null; for (int i = 0; i < attributes.getLength(); i++) { String qName = attributes.getQName(i); if (checkRdfQName("resource", qName)) { this.consumingContent = false; currentObject = resolve(attributes.getValue(i), false); popState(); pushState(State.OBJECT); } else if (checkRdfQName("datatype", qName)) { // The object is a literal this.consumingContent = true; popState(); pushState(State.LITERAL); this.currentDataType = attributes.getValue(i); } else if (checkRdfQName("parseType", qName)) { String value = attributes.getValue(i); if ("Literal".equals(value)) { this.consumingContent = true; // The object is an XML literal popState(); pushState(State.LITERAL); this.currentDataType = RdfConstants.RDF_SYNTAX + "XMLLiteral"; nodeDepth = 0; } else if ("Resource".equals(value)) { this.consumingContent = false; // Create a new blank node currentObject = Link.createBlankRef(ContentReader .newBlankNodeId()); popState(); pushState(State.SUBJECT); pushSubject(currentObject); } else { this.consumingContent = false; // Error } } else if (checkRdfQName("nodeID", qName)) { this.consumingContent = false; currentObject = Link.createBlankRef(attributes.getValue(i)); popState(); pushState(State.SUBJECT); pushSubject(currentObject); } else if (checkRdfQName("ID", qName)) { // Reify the statement reifiedRef = resolve(attributes.getValue(i), true); } else if ("xml:lang".equals(qName)) { this.language.add(Language.valueOf(attributes.getValue(i))); } else { if (!qName.startsWith("xmlns")) { // Add arcs. String[] arc = { qName, attributes.getValue(i) }; arcs.add(arc); } } } if (currentObject != null) { link(currentSubject, this.currentPredicate, currentObject); } if (!arcs.isEmpty()) { // Create arcs that starts from a blank node and ends to // literal values. This blank node is the object of the // current statement. boolean found = false; Reference blankNode = Link.createBlankRef(ContentReader .newBlankNodeId()); for (String[] arc : arcs) { Reference pRef = resolve(null, arc[0]); // Silently remove unrecognized attributes if (pRef != null) { found = true; this.graphHandler.link(blankNode, pRef, new Literal( arc[1])); } } if (found) { link(currentSubject, this.currentPredicate, blankNode); popState(); pushState(State.OBJECT); } } if (this.consumingContent) { builder = new StringBuilder(); } } else if (state == State.PREDICATE) { this.consumingContent = false; // Parse the current object, create the current link Reference object = parseNode(uri, localName, name, attributes); this.currentObject = object; link(); pushSubject(object); pushState(State.SUBJECT); } else if (state == State.OBJECT) { } else if (state == State.LITERAL) { // Glean the XML content nodeDepth++; this.builder.append("<"); if (uri != null && !"".equals(uri)) { this.builder.append(uri).append(":"); } this.builder.append(localName).append(">"); } } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { this.rdfDefaultNamespace = this.rdfDefaultNamespace || ((prefix == null || "".equals(prefix) && RdfConstants.RDF_SYNTAX.toString(true, true).equals( uri))); if (!uri.endsWith("#") && !uri.endsWith("/")) { this.prefixes.put(prefix, uri + "/"); } else { this.prefixes.put(prefix, uri); } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlReader.java0000664000175000017500000000532711757206350032003 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.xml; import java.io.IOException; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.internal.RdfReader; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.representation.Representation; /** * Handler of RDF content according to the RDF/XML format. * * @author Thierry Boileau */ public class RdfXmlReader extends RdfReader { /** * Constructor. * * @param rdfRepresentation * The representation to read. * @param graphHandler * The graph handler invoked during the parsing. * @throws IOException */ public RdfXmlReader(Representation rdfRepresentation, GraphHandler graphHandler) { super(rdfRepresentation, graphHandler); } /** * Parses the current representation. * * @throws Exception */ public void parse() throws Exception { SaxRepresentation saxRepresentation; if (getRdfRepresentation() instanceof SaxRepresentation) { saxRepresentation = (SaxRepresentation) getRdfRepresentation(); } else { saxRepresentation = new SaxRepresentation(getRdfRepresentation()); // Transmit the identifier used as a base for the resolution of // relative URIs. saxRepresentation.setLocationRef(getRdfRepresentation().getLocationRef()); } saxRepresentation.parse(new ContentReader(saxRepresentation, getGraphHandler())); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ScopedProperty.java0000664000175000017500000000622411757206350032443 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.xml; import java.util.ArrayList; import java.util.List; /** * Used to handle properties that have a scope such as the base URI, the * xml:lang property. * * @param * The type of the property. * @author Thierry Boileau */ class ScopedProperty { private int[] depths; private List values; private int size; /** * Constructor. */ public ScopedProperty() { super(); this.depths = new int[10]; this.values = new ArrayList(); this.size = 0; } /** * Constructor. * * @param value * Value. */ public ScopedProperty(E value) { this(); add(value); incrDepth(); } /** * Add a new value. * * @param value * The value to be added. */ public void add(E value) { this.values.add(value); if (this.size == this.depths.length) { int[] temp = new int[2 * this.depths.length]; System.arraycopy(this.depths, 0, temp, 0, this.depths.length); this.depths = temp; } this.size++; this.depths[size - 1] = 0; } /** * Decrements the depth of the current value, and remove it if necessary. */ public void decrDepth() { if (this.size > 0) { this.depths[size - 1]--; if (this.depths[size - 1] < 0) { this.size--; this.values.remove(size); } } } /** * Returns the current value. * * @return The current value. */ public E getValue() { if (this.size > 0) { return this.values.get(this.size - 1); } return null; } /** * Increments the depth of the current value. */ public void incrDepth() { if (this.size > 0) { this.depths[size - 1]++; } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlWriter.java0000664000175000017500000002276711757206350032064 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.xml; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; import org.restlet.Context; import org.restlet.data.Reference; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Link; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.internal.RdfConstants; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Handler of RDF content according to the RDF XML syntax. * * @author Thierry Boileau */ public class RdfXmlWriter extends GraphHandler { /** URI of the RDF SYNTAX namespace. */ private final String RDF_SYNTAX = RdfConstants.RDF_SYNTAX.toString(true, true); /** XML writer. */ private XmlWriter writer; /** The last source reference written, to try to factor statements. */ private Reference lastSource; /** * Constructor. * * @param writer * The character writer. * @throws UnsupportedEncodingException */ public RdfXmlWriter(Writer writer) throws UnsupportedEncodingException { super(); this.writer = new XmlWriter(writer); this.lastSource = null; } @Override public void endGraph() throws IOException { try { if (this.lastSource != null) { // We need to end the previous source this.writer.endElement(RDF_SYNTAX, "Description"); } this.writer.endElement(RDF_SYNTAX, "RDF"); this.writer.endDocument(); } catch (SAXException e) { Context.getCurrentLogger().warning( "Cannot write the end of the graph: " + e.getMessage()); } this.writer.flush(); } /** * Returns the namespace of the given reference. * * @param reference * the given reference. * @return The namespace of the given reference. */ private String getNamespace(Reference reference) { String prefix = getPrefix(reference); String ref = reference.toString(true, true); if (prefix != null) { return ref.substring(0, ref.length() - prefix.length()); } return ref; } /** * Returns the prefix of the qualified name representing the given * reference. * * @param ref * the given reference. * @return The prefix of the qualified name representing the given * reference. Context .getCurrentLogger() .warning( * "Cannot write the end of the graph" + e.getMessage()); */ private String getPrefix(Reference ref) { String result = null; if (ref.hasFragment()) { result = ref.getFragment(); } else { result = ref.getLastSegment(); } return result; } @Override public void link(Graph source, Reference typeRef, Literal target) { Context.getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the subject is not a Reference."); } @Override public void link(Graph source, Reference typeRef, Reference target) { Context.getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the subject is not a Reference."); } @Override public void link(Reference source, Reference typeRef, Literal target) { try { if (this.lastSource == null) { writeNode(source, true); } else if (!source.equals(this.lastSource)) { // We need to first end the previous source this.writer.endElement(RDF_SYNTAX, "Description"); writeNode(source, true); } this.lastSource = source; String typeRefNs = getNamespace(typeRef.getTargetRef()); String typeRefPrefix = getPrefix(typeRef.getTargetRef()); if (target.getLanguage() != null || target.getDatatypeRef() != null) { AttributesImpl attr = new AttributesImpl(); if (target.getLanguage() != null) { attr.addAttribute(null, "lang", "xml:lang", "text", target .getLanguage().getName()); } if (target.getDatatypeRef() != null) { attr.addAttribute(RDF_SYNTAX, "datatype", "rdf:datatype", "text", target.getDatatypeRef() .toString(true, true)); } this.writer.startElement(typeRefNs, typeRefPrefix, null, attr); } else { this.writer.startElement(typeRefNs, typeRefPrefix); } this.writer.characters(target.getValue()); this.writer.endElement(typeRefNs, typeRefPrefix); } catch (SAXException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to: " + e.getMessage()); } } @Override public void link(Reference source, Reference typeRef, Reference target) { try { if (this.lastSource == null) { writeNode(source, true); } else if (!source.equals(this.lastSource)) { // We need to first end the previous source this.writer.endElement(RDF_SYNTAX, "Description"); writeNode(source, true); } this.lastSource = source; String typeRefNs = getNamespace(typeRef.getTargetRef()); String typeRefPrefix = getPrefix(typeRef.getTargetRef()); this.writer.startElement(typeRefNs, typeRefPrefix); writeNode(target, false); this.writer.endElement(typeRefNs, typeRefPrefix); } catch (SAXException e) { Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to: " + e.getMessage()); } } @Override public void startGraph() throws IOException { this.writer.setPrefix(RDF_SYNTAX, "rdf"); this.writer.setPrefix(RdfConstants.XML_SCHEMA.toString(true, true), "type"); writer.setDataFormat(true); writer.setIndentStep(3); try { this.writer.startDocument(); this.writer.startElement(RDF_SYNTAX, "RDF"); } catch (SAXException e) { Context.getCurrentLogger().warning( "Cannot write the start of the graph: " + e.getMessage()); } } @Override public void startPrefixMapping(String prefix, Reference reference) { if (prefix == null) { writer.forceNSDecl(getNamespace(reference.getTargetRef())); } else { writer.forceNSDecl(getNamespace(reference.getTargetRef()), prefix); } } /** * Writes a subject or object node. * * @param ref * The reference of the subject or object node. * @param subject * True if the node is the subject of a predicate * @throws SAXException */ private void writeNode(Reference reference, boolean subject) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (Link.isBlankRef(reference)) { atts.addAttribute(RDF_SYNTAX, "NodeId", "rdf:NodeId", "text", reference.getTargetRef().toString(true, true)); } else { atts.addAttribute(RDF_SYNTAX, "about", "rdf:about", "text", reference.getTargetRef().toString(true, true)); } try { if (!subject) { this.writer.emptyElement(RDF_SYNTAX, "Description", "rdf:Description", atts); } else { this.writer.startElement(RDF_SYNTAX, "Description", "rdf:Description", atts); } } catch (SAXException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to: " + e.getMessage()); } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/0000775000175000017500000000000011757206350027331 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/Token.java0000664000175000017500000000667511757206350031272 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.internal.RdfConstants; /** * Represents a still unidentified Turtle token. * * @author Thierry Boileau */ public class Token extends LexicalUnit { /** * Constructor with arguments. * * @param contentHandler * The document's parent handler. * @param context * The parsing context. */ public Token(RdfTurtleReader contentHandler, Context context) throws IOException { super(contentHandler, context); this.parse(); } /** * Constructor with value. * * @param value * The value of the current lexical unit. */ public Token(String value) { super(value); } @Override public void parse() throws IOException { getContentReader().parseToken(this); } @Override public Object resolve() { Object result = null; if ((getContext() != null) && getContext().isQName(getValue())) { result = (getContext() != null) ? getContext().resolve(getValue()) : getValue(); } else { // Must be a literal if (getValue().charAt(0) > '0' && getValue().charAt(0) < '9') { if (getValue().contains(".")) { // Consider it as a float result = new Literal(getValue(), RdfConstants.XML_SCHEMA_TYPE_FLOAT); } else { // Consider it as an integer result = new Literal(getValue(), RdfConstants.XML_SCHEMA_TYPE_INTEGER); } } else { org.restlet.Context.getCurrentLogger().warning( "Cannot identify this token value: " + getValue()); if (getContentReader() != null) { org.restlet.Context.getCurrentLogger().warning( getContentReader().getParsingMessage()); } } } return result; } @Override public String toString() { return getValue(); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/Context.java0000664000175000017500000001101511757206350031616 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.data.Reference; /** * Contains essentials data updated during the parsing of a N3 document such as * the list of known namespaces, keywords. * * @author Thierry Boileau */ public class Context { /** The value of the "base" keyword. */ private Reference base; /** The list of known keywords. */ private List keywords; /** The list of known prefixes. */ private Map prefixes; /** * Default constructor. */ public Context() { super(); this.prefixes = new HashMap(); // "#" is the default URI of the "null" prefix this.prefixes.put(":", "#"); this.keywords = new ArrayList(); } /** * Returns the base reference. * * @return The base reference. */ public Reference getBase() { if (base == null) { base = new Reference(); } return base; } /** * Returns the list of known keywords. * * @return The list of known keywords. */ public List getKeywords() { return keywords; } /** * Returns the list of known prefixes. * * @return The list of known prefixes. */ public Map getPrefixes() { return prefixes; } /** * Returns true if the given value is a qualified name. * * @param value * The value to test. * @return True if the given value is a qualified name. */ public boolean isQName(String value) { boolean result = (value.indexOf(":") != -1) || getKeywords().contains(value); return result; } /** * Resolves a qualified name according to the current context. * * @param qname * The qualified name to resolve. * @return The RDF URI reference. */ public Reference resolve(String qname) { Reference result = null; int index = qname.indexOf(":"); if (index != -1) { String prefix = qname.substring(0, index + 1); String base = getPrefixes().get(prefix); if (base != null) { result = new Reference(base + qname.substring(index + 1)); } else { org.restlet.Context.getCurrentLogger().warning( "Error, this prefix " + prefix + " has not been declared!"); } } else { if (getKeywords().contains(qname)) { String base = getPrefixes().get(":"); if (base != null) { result = new Reference(base + qname); } else { org.restlet.Context.getCurrentLogger().warning( "Error, the empty prefix has not been declared!"); } } else { result = new Reference(getBase().toString() + qname); } } return result; } /** * Sets the base reference. * * @param base * The base reference. */ public void setBase(Reference base) { this.base = base; } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/BlankNodeToken.java0000664000175000017500000000666311757206350033045 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.data.Reference; import org.restlet.ext.rdf.Link; /** * Represents a blank node inside a RDF N3 document. Contains all the logic to * parse a blank node in N3 documents. * * @author Thierry Boileau */ public class BlankNodeToken extends LexicalUnit { /** List of lexical units contained by this blank node. */ private List lexicalUnits; public List getLexicalUnits() { return lexicalUnits; } /** Indicates if the given blank node has been already resolved. */ private boolean resolved = false; /** * Constructor. The blank node is given a new identifier thanks to the * context. * * @param contentHandler * The parent content handler. * @param context * The context used to resolved references. * @throws IOException */ public BlankNodeToken(RdfTurtleReader contentHandler, Context context) throws IOException { super(contentHandler, context); lexicalUnits = new ArrayList(); this.setValue("_:" + contentHandler.newBlankNodeId()); lexicalUnits.add(this); this.parse(); } /** * Constructor * * @param value * The value of this blank node. */ public BlankNodeToken(String value) { super(value); this.resolved = true; } @Override public void parse() throws IOException { getContentReader().parseBlankNode(this); } @Override public Object resolve() { if (!this.resolved) { this.resolved = true; if (getContentReader() != null) { getContentReader().generateLinks(lexicalUnits); } } if (getValue() != null) { if (getValue().startsWith("_:")) { return new Reference(getValue()); } return Link.createBlankRef(getValue()); } org.restlet.Context.getCurrentLogger().warning( "A blank node has been detected with a null value."); return null; } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/RdfTurtleWriter.java0000664000175000017500000002611211757206350033306 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; import java.io.Writer; import java.util.Map; import org.restlet.data.Reference; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Link; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.internal.RdfConstants; /** * Handler of RDF content according to the N3 notation. * * @author Thierry Boileau */ public class RdfTurtleWriter extends GraphHandler { /** Buffered writer. */ private Writer writer; /** The current context object. */ private Context context; /** The preceding predicate used for factorization matter. */ private Reference precPredicate; /** The preceding source used for factorization matter. */ private Reference precSource; /** Indicates if the end of the statement is to be written. */ private boolean writingExtraDot; /** * Constructor. * * @param writer * The character writer. * @throws IOException */ public RdfTurtleWriter(Writer writer) throws IOException { super(); this.writer = writer; this.context = new Context(); Map prefixes = context.getPrefixes(); prefixes.put(RdfConstants.RDF_SCHEMA.toString(), "rdf"); prefixes.put(RdfConstants.RDF_SYNTAX.toString(), "rdfs"); prefixes.put("http://www.w3.org/2001/XMLSchema#", "type"); for (String key : prefixes.keySet()) { this.writer.append("@prefix ").append(prefixes.get(key)).append( ": <").append(key).append(">.\n"); } this.writer.append("@keywords a, is, of, has.\n"); } @Override public void endGraph() throws IOException { this.writer.write(".\n"); this.writer.flush(); } @Override public void link(Graph source, Reference typeRef, Literal target) { try { this.writingExtraDot = false; this.writer.write("{"); write(source); this.writer.write("} "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); write(target); this.precSource = null; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } @Override public void link(Graph source, Reference typeRef, Reference target) { try { this.writingExtraDot = false; this.writer.write("{"); write(source); this.writer.write("} "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); write(target, this.context.getPrefixes()); this.precSource = null; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } @Override public void link(Reference source, Reference typeRef, Literal target) { try { if (source.equals(this.precSource)) { if (typeRef.equals(this.precPredicate)) { this.writer.write(", "); } else { this.writer.write("; "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } } else { if (this.writingExtraDot) { this.writer.write(".\n"); } write(source, this.context.getPrefixes()); this.writer.write(" "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } write(target); this.precSource = source; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } @Override public void link(Reference source, Reference typeRef, Reference target) { try { if (source.equals(this.precSource)) { this.writingExtraDot = false; if (typeRef.equals(this.precPredicate)) { this.writer.write(", "); } else { this.writer.write("; "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } } else { if (this.writingExtraDot) { this.writer.write(".\n"); } write(source, this.context.getPrefixes()); this.writer.write(" "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } write(target, this.context.getPrefixes()); this.precSource = source; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } @Override public void startGraph() { } /** * Write the representation of the given graph of links. * * @param linkset * the given graph of links. * @throws IOException */ private void write(Graph linkset) throws IOException { for (Link link : linkset) { if (link.hasReferenceSource()) { if (link.hasReferenceTarget()) { link(link.getSourceAsReference(), link.getTypeRef(), link .getTargetAsReference()); } else if (link.hasLiteralTarget()) { link(link.getSourceAsReference(), link.getTypeRef(), link .getTargetAsLiteral()); } else if (link.hasLinkTarget()) { // TODO Hande source as link. } else { org.restlet.Context .getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } } else if (link.hasGraphSource()) { this.writingExtraDot = false; if (link.hasReferenceTarget()) { link(link.getSourceAsGraph(), link.getTypeRef(), link .getTargetAsReference()); } else if (link.hasLiteralTarget()) { link(link.getSourceAsGraph(), link.getTypeRef(), link .getTargetAsLiteral()); } else if (link.hasLinkTarget()) { // TODO Handle source as link. } else { org.restlet.Context .getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } this.writer.write(".\n"); } this.precSource = link.getSourceAsReference(); this.precPredicate = link.getTypeRef(); } if (writingExtraDot) { this.writer.write(".\n"); } } /** * Writes the representation of a literal. * * @param literal * The literal to write. * @throws IOException */ private void write(Literal literal) throws IOException { // Write it as a string this.writer.write("\""); if (literal.getValue().contains("\n")) { this.writer.write("\""); this.writer.write("\""); this.writer.write(literal.getValue()); this.writer.write("\""); this.writer.write("\""); } else { this.writer.write(literal.getValue()); } this.writer.write("\""); if (literal.getDatatypeRef() != null) { this.writer.write("^^"); write(literal.getDatatypeRef(), context.getPrefixes()); } if (literal.getLanguage() != null) { this.writer.write("@"); this.writer.write(literal.getLanguage().toString()); } } /** * Writes the representation of a given reference. * * @param reference * The reference to write. * @param prefixes * The map of known namespaces. * @throws IOException */ private void write(Reference reference, Map prefixes) throws IOException { String uri = reference.toString(); if (Link.isBlankRef(reference)) { this.writer.write(uri); } else { boolean found = false; for (String key : prefixes.keySet()) { if (uri.startsWith(key)) { found = true; this.writer.append(prefixes.get(key)); this.writer.append(":"); this.writer.append(uri.substring(key.length())); break; } } if (!found) { this.writer.append("<"); this.writer.append(uri); this.writer.append(">"); } } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/StringToken.java0000664000175000017500000000640511757206350032450 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; import org.restlet.data.Language; import org.restlet.ext.rdf.Literal; /** * Represents a string of characters. This string could have a type and a * language. * * @author Thierry Boileau */ public class StringToken extends LexicalUnit { /** The language of the value. */ private String language; public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getType() { return type; } public void setType(String type) { this.type = type; } /** Does this string contains at least a new line character? */ private boolean multiLines; /** The type of the represented value. */ private String type; /** * Constructor with arguments. * * @param contentHandler * The document's parent handler. * @param context * The parsing context. */ public StringToken(RdfTurtleReader contentHandler, Context context) throws IOException { super(contentHandler, context); multiLines = false; this.parse(); } /** * Returns true if this string of characters contains at least one newline * character. * * @return */ public boolean isMultiLines() { return multiLines; } @Override public void parse() throws IOException { getContentReader().parseString(this); } @Override public Object resolve() { Literal result = new Literal(getValue()); if (this.type != null) { result.setDatatypeRef(getContext().resolve(this.type)); } if (this.language != null) { result.setLanguage(Language.valueOf(this.language)); } return result; } public void setMultiLines(boolean multiLines) { this.multiLines = multiLines; } @Override public String toString() { return getValue(); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/UriToken.java0000664000175000017500000000414211757206350031735 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; import org.restlet.data.Reference; /** * Represents a URI token inside a RDF Turtle document. * * @author Thierry Boileau */ public class UriToken extends LexicalUnit { /** * Constructor with arguments. * * @param contentHandler * The document's parent handler. * @param context * The parsing context. */ public UriToken(RdfTurtleReader contentHandler, Context context) throws IOException { super(contentHandler, context); this.parse(); } @Override public void parse() throws IOException { getContentReader().parseUri(this); } @Override public Reference resolve() { return new Reference(getValue()); } @Override public String toString() { return getValue(); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/ListToken.java0000664000175000017500000000725611757206350032122 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.data.Reference; import org.restlet.ext.rdf.internal.RdfConstants; /** * Represents a list of Turtle tokens. * * @author Thierry Boileau */ public class ListToken extends LexicalUnit { /** The list of contained tokens. */ List lexicalUnits; public List getLexicalUnits() { return lexicalUnits; } /** * Constructor with arguments. * * @param contentHandler * The document's parent handler. * @param context * The parsing context. */ public ListToken(RdfTurtleReader contentHandler, Context context) throws IOException { super(contentHandler, context); lexicalUnits = new ArrayList(); this.parse(); } @Override public Object resolve() { Reference currentBlankNode = (Reference) new BlankNodeToken( getContentReader().newBlankNodeId()).resolve(); for (LexicalUnit lexicalUnit : lexicalUnits) { Object element = lexicalUnit.resolve(); if (element instanceof Reference) { getContentReader().link(currentBlankNode, RdfConstants.LIST_FIRST, element); } else if (element instanceof String) { getContentReader().link(currentBlankNode, RdfConstants.LIST_FIRST, new Reference((String) element)); } else { org.restlet.Context .getCurrentLogger() .warning( "The list contains an element which is neither a Reference nor a literal."); } Reference restBlankNode = (Reference) new BlankNodeToken( getContentReader().newBlankNodeId()).resolve(); getContentReader().link(currentBlankNode, RdfConstants.LIST_REST, restBlankNode); currentBlankNode = restBlankNode; } getContentReader().link(currentBlankNode, RdfConstants.LIST_REST, RdfConstants.OBJECT_NIL); return currentBlankNode; } @Override public String getValue() { return lexicalUnits.toString(); } @Override public void parse() throws IOException { getContentReader().parseList(this); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/RdfTurtleReader.java0000664000175000017500000004641711757206350033246 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.restlet.data.Reference; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.internal.RdfConstants; import org.restlet.ext.rdf.internal.ntriples.RdfNTriplesReader; import org.restlet.representation.Representation; /** * Handler of RDF content according to the RDF Turtle notation. * * @author Thierry Boileau */ public class RdfTurtleReader extends RdfNTriplesReader { /** Increment used to identify inner blank nodes. */ private int blankNodeId = 0; /** The current context object. */ private Context context; /** * Constructor. * * @param rdfRepresentation * The representation to read. * @param graphHandler * The graph handler invoked during the parsing. * @throws IOException */ public RdfTurtleReader(Representation rdfN3Representation, GraphHandler graphHandler) throws IOException { super(rdfN3Representation, graphHandler); this.context = new Context(); context.getKeywords().addAll( Arrays.asList("a", "is", "of", "this", "has")); } /** * Loops over the given list of lexical units and generates the adequat * calls to link* methods. * * @see GraphHandler#link(Graph, Reference, Reference) * @see GraphHandler#link(Reference, Reference, Literal) * @see GraphHandler#link(Reference, Reference, Reference) * @param lexicalUnits * The list of lexical units used to generate the links. */ protected void generateLinks(List lexicalUnits) { Object currentSubject = null; Reference currentPredicate = null; Object currentObject = null; int nbTokens = 0; boolean swapSubjectObject = false; for (int i = 0; i < lexicalUnits.size(); i++) { LexicalUnit lexicalUnit = lexicalUnits.get(i); nbTokens++; switch (nbTokens) { case 1: if (",".equals(lexicalUnit.getValue())) { nbTokens++; } else if (!";".equals(lexicalUnit.getValue())) { currentSubject = lexicalUnit.resolve(); } break; case 2: if ("is".equalsIgnoreCase(lexicalUnit.getValue())) { nbTokens--; swapSubjectObject = true; } else if ("has".equalsIgnoreCase(lexicalUnit.getValue())) { nbTokens--; } else if ("a".equalsIgnoreCase(lexicalUnit.getValue())) { currentPredicate = RdfConstants.PREDICATE_TYPE; } else if ("!".equalsIgnoreCase(lexicalUnit.getValue())) { currentObject = new BlankNodeToken(newBlankNodeId()) .resolve(); currentPredicate = getPredicate(lexicalUnits.get(++i)); this.link(currentSubject, currentPredicate, currentObject); currentSubject = currentObject; nbTokens = 1; } else if ("^".equalsIgnoreCase(lexicalUnit.getValue())) { currentObject = currentSubject; currentPredicate = getPredicate(lexicalUnits.get(++i)); currentSubject = new BlankNodeToken(newBlankNodeId()) .resolve(); this.link(currentSubject, currentPredicate, currentObject); nbTokens = 1; } else { currentPredicate = getPredicate(lexicalUnit); } break; case 3: if ("of".equalsIgnoreCase(lexicalUnit.getValue())) { nbTokens--; } else { if (swapSubjectObject) { this.link(lexicalUnit.resolve(), currentPredicate, currentSubject); } else { currentObject = lexicalUnit.resolve(); this.link(currentSubject, currentPredicate, currentObject); } nbTokens = 0; swapSubjectObject = false; } break; default: break; } } } /** * Returns the current context. * * @return The current context. */ protected Context getContext() { return context; } /** * Returns the given lexical unit as a predicate. * * @param lexicalUnit * The lexical unit to get as a predicate. * @return A RDF URI reference of the predicate. */ private Reference getPredicate(LexicalUnit lexicalUnit) { Reference result = null; Object p = lexicalUnit.resolve(); if (p instanceof Reference) { result = (Reference) p; } else if (p instanceof String) { result = new Reference((String) p); } return result; } /** * Returns true if the given character is a delimiter. * * @param c * The given character to check. * @return true if the given character is a delimiter. */ @Override protected boolean isDelimiter(int c) { return isWhiteSpace(c) || c == '^' || c == '!' || c == '=' || c == '<' || c == '"' || c == '[' || c == ']' || c == '(' || c == ')' || c == '.' || c == ';' || c == ',' || c == '@'; } /** * Callback method used when a link is parsed or written. * * @param source * The source or subject of the link. * @param typeRef * The type reference of the link. * @param target * The target or object of the link. */ protected void link(Object source, Reference typeRef, Object target) { if (source instanceof Reference) { if (target instanceof Reference) { getGraphHandler().link((Reference) source, typeRef, (Reference) target); } else if (target instanceof Literal) { getGraphHandler().link((Reference) source, typeRef, (Literal) target); } else { org.restlet.Context .getCurrentLogger() .warning( "The RDF Turtle document contains an object which is neither a Reference nor a literal: " + target); org.restlet.Context.getCurrentLogger().warning( getParsingMessage()); } } else if (source instanceof Graph) { if (target instanceof Reference) { getGraphHandler().link((Graph) source, typeRef, (Reference) target); } else if (target instanceof Literal) { getGraphHandler().link((Graph) source, typeRef, (Literal) target); } else { org.restlet.Context .getCurrentLogger() .warning( "The RDF Turtle document contains an object which is neither a Reference nor a literal: " + target); org.restlet.Context.getCurrentLogger().warning( getParsingMessage()); } } } /** * Returns the identifier of a new blank node. * * @return The identifier of a new blank node. */ protected String newBlankNodeId() { return "#_bn" + blankNodeId++; } /** * Parses the current representation. * * @throws IOException */ @Override public void parse() throws Exception { // Init the reading. step(); do { consumeWhiteSpaces(); switch (getChar()) { case '@': parseDirective(this.context); break; case '#': parseComment(); break; case '.': step(); break; default: parseStatement(this.context); break; } } while (!isEndOfFile(getChar())); } /** * Parse the given blank node. * * @param blankNode * The blank node to parse. * @throws IOException */ protected void parseBlankNode(BlankNodeToken blankNode) throws IOException { step(); do { consumeWhiteSpaces(); switch (getChar()) { case '(': blankNode.getLexicalUnits().add( new ListToken(this, this.context)); break; case '<': stepBack(); blankNode.getLexicalUnits().add( new UriToken(this, this.context)); break; case '_': blankNode.getLexicalUnits().add( new BlankNodeToken(this.parseToken())); break; case '"': blankNode.getLexicalUnits().add( new StringToken(this, this.context)); break; case '[': blankNode.getLexicalUnits().add( new BlankNodeToken(this, this.context)); break; case ']': break; default: if (!isEndOfFile(getChar())) { blankNode.getLexicalUnits().add( new Token(this, this.context)); } break; } } while (!isEndOfFile(getChar()) && getChar() != ']'); if (getChar() == ']') { // Set the cursor at the right of the list token. step(); } } /** * Parse the current directive and update the context according to the kind * of directive ("base", "prefix", etc). * * @param context * The context to update. * @throws IOException */ protected void parseDirective(Context context) throws IOException { // Remove the leading '@' character. step(); discard(); String currentKeyword = parseToken(); if ("base".equalsIgnoreCase(currentKeyword)) { consumeWhiteSpaces(); String base = parseUri(); Reference ref = new Reference(base); if (ref.isRelative()) { context.getBase().addSegment(base); } else { context.setBase(ref); } consumeStatement(); } else if ("prefix".equalsIgnoreCase(currentKeyword)) { consumeWhiteSpaces(); String prefix = parseToken(); consumeWhiteSpaces(); String uri = parseUri(); context.getPrefixes().put(prefix, uri); consumeStatement(); } else if ("keywords".equalsIgnoreCase(currentKeyword)) { consumeWhiteSpaces(); int c; do { c = step(); } while (!isEndOfFile(c) && c != '.'); String strKeywords = getCurrentToken(); String[] keywords = strKeywords.split(","); context.getKeywords().clear(); for (String keyword : keywords) { context.getKeywords().add(keyword.trim()); } consumeStatement(); } else { org.restlet.Context.getCurrentLogger().warning( "@" + currentKeyword + " directive is not supported."); consumeStatement(); } } /** * Parse the given list token. * * @param listToken * The list token to parse. * @throws IOException */ protected void parseList(ListToken listToken) throws IOException { step(); do { consumeWhiteSpaces(); switch (getChar()) { case '(': listToken.getLexicalUnits().add( new ListToken(this, this.context)); break; case '<': stepBack(); listToken.getLexicalUnits().add( new UriToken(this, this.context)); break; case '_': listToken.getLexicalUnits().add( new BlankNodeToken(parseToken())); break; case '"': listToken.getLexicalUnits().add( new StringToken(this, this.context)); break; case '[': listToken.getLexicalUnits().add( new BlankNodeToken(this, this.context)); break; case ')': break; default: if (!isEndOfFile(getChar())) { listToken.getLexicalUnits().add( new Token(this, this.context)); } break; } } while (!isEndOfFile(getChar()) && getChar() != ')'); if (getChar() == ')') { // Set the cursor at the right of the list token. step(); } } /** * Reads the current statement until its end, and parses it. * * @param context * The current context. * @throws IOException */ protected void parseStatement(Context context) throws IOException { List lexicalUnits = new ArrayList(); do { consumeWhiteSpaces(); switch (getChar()) { case '(': lexicalUnits.add(new ListToken(this, context)); break; case '<': stepBack(); lexicalUnits.add(new UriToken(this, context)); break; case '_': lexicalUnits.add(new BlankNodeToken(parseToken())); break; case '"': lexicalUnits.add(new StringToken(this, context)); break; case '[': lexicalUnits.add(new BlankNodeToken(this, context)); break; case '!': lexicalUnits.add(new Token("!")); step(); discard(); break; case '^': lexicalUnits.add(new Token("^")); step(); discard(); break; case '@': // Remove the leading '@' character. step(); discard(); lexicalUnits.add(new Token(this, context)); discard(); break; case ';': step(); discard(); lexicalUnits.add(new Token(";")); break; case ',': step(); discard(); lexicalUnits.add(new Token(",")); break; case '#': parseComment(); break; case '.': break; default: if (!isEndOfFile(getChar())) { lexicalUnits.add(new Token(this, context)); } break; } } while (!isEndOfFile(getChar()) && getChar() != '.'); // Generate the links generateLinks(lexicalUnits); } /** * Parse the given String token. * * @param stringToken * The String token to parse. * @throws IOException */ protected void parseString(StringToken stringToken) throws IOException { // Answer the question : is it multi lines or not? // That is to say, is it delimited by 3 quotes or not? int c1 = step(); int c2 = step(); if ((c1 == c2) && (c1 == '"')) { stringToken.setMultiLines(true); step(); discard(); int[] tab = new int[3]; int cpt = 0; // Number of consecutives '"' characters. int c = getChar(); while (!isEndOfFile(c)) { if (c == '"') { tab[++cpt - 1] = c; } else { cpt = 0; } if (cpt == 3) { // End of the string reached. stepBack(2); stringToken.setValue(getCurrentToken()); step(3); discard(); break; } c = step(); } } else { stringToken.setMultiLines(false); stepBack(1); discard(); int c = getChar(); while (!isEndOfFile(c) && (c != '"')) { c = step(); } stringToken.setValue(getCurrentToken()); step(); discard(); } // Parse the type and language of literals int c = getChar(); if (c == '@') { stringToken.setLanguage(parseToken()); } else if (c == '^') { c = step(); if (c == '^') { stringToken.setType(parseToken()); } else { stepBack(); } } } /** * Parses the given token. * * @param token * The token to parse. * @throws IOException */ protected void parseToken(Token token) throws IOException { int c; do { c = step(); } while (!isEndOfFile(c) && !isDelimiter(c)); token.setValue(getCurrentToken()); } /** * Parses the given URI token. * * @param token * The URI token to parse. * @throws IOException */ protected void parseUri(UriToken uriToken) throws IOException { uriToken.setValue(parseUri()); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/turtle/LexicalUnit.java0000664000175000017500000000715311757206350032423 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.turtle; import java.io.IOException; /** * Represents a lexical unit inside a Turtle document. * * @author Thierry Boileau */ public abstract class LexicalUnit { /** The content handler of the current Turtle document. */ private RdfTurtleReader contentReader; /** The context maintained during the parsing. */ private Context context; /** The parsed value as a simple string of characters. */ private String value; /** * Constructor with arguments. * * @param contentHandler * The document's parent handler. * @param context * The parsing context. */ public LexicalUnit(RdfTurtleReader contentReader, Context context) { super(); this.contentReader = contentReader; this.context = context; } /** * Constructor with value. * * @param value * The value of the current lexical unit. */ public LexicalUnit(String value) { super(); setValue(value); } /** * Returns the document's reader. * * @return The document's reader. */ public RdfTurtleReader getContentReader() { return contentReader; } /** * Returns the parsing context. * * @return The parsing context. */ public Context getContext() { return context; } /** * Returns the current value. * * @return The current value. */ public String getValue() { return value; } /** * Contains the parsing logic of this lexical unit. * * @throws IOException */ public abstract void parse() throws IOException; /** * Resolves the current value as a reference or a literal or a graph of * links according to the current context. * * @return The current value as a reference or a literal or a graph of links * according to the current context. */ public abstract Object resolve(); /** * Sets the parsing context. * * @param context * The parsing context. */ public void setContext(Context context) { this.context = context; } /** * Sets the value. * * @param value * The current value. */ public void setValue(String value) { this.value = value; } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/0000775000175000017500000000000011757206350026332 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3Writer.java0000664000175000017500000002557611757206350031325 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.n3; import java.io.IOException; import java.io.Writer; import java.util.Map; import org.restlet.data.Reference; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Link; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.internal.RdfConstants; import org.restlet.ext.rdf.internal.turtle.Context; /** * Handler of RDF content according to the N3 notation. * * @author Thierry Boileau */ public class RdfN3Writer extends GraphHandler { /** The current context object. */ private Context context; /** The preceding predicate used for factorization matter. */ private Reference precPredicate; /** The preceding source used for factorization matter. */ private Reference precSource; /** The character writer. */ private Writer writer; /** Indicates if the end of the statement is to be written. */ private boolean writingExtraDot; /** * Constructor. * * @param writer * The character writer to write to. * @throws IOException */ public RdfN3Writer(Writer writer) throws IOException { super(); this.context = new Context(); this.writer = writer; Map prefixes = context.getPrefixes(); prefixes.put(RdfConstants.RDF_SCHEMA.toString(), "rdf"); prefixes.put(RdfConstants.RDF_SYNTAX.toString(), "rdfs"); prefixes.put("http://www.w3.org/2001/XMLSchema#", "type"); for (String key : prefixes.keySet()) { this.writer.append("@prefix ").append(prefixes.get(key)) .append(": <").append(key).append(">.\n"); } this.writer.append("@keywords a, is, of, has.\n"); } @Override public void endGraph() throws IOException { this.writer.write(".\n"); this.writer.flush(); } @Override public void link(Graph source, Reference typeRef, Literal target) { try { this.writer.write("{"); write(source); this.writer.write("} "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); write(target); this.precSource = null; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } @Override public void link(Graph source, Reference typeRef, Reference target) { try { this.writer.write("{"); write(source); this.writer.write("} "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); write(target, this.context.getPrefixes()); this.precSource = null; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } @Override public void link(Reference source, Reference typeRef, Literal target) { try { if (source.equals(this.precSource)) { if (typeRef.equals(this.precPredicate)) { this.writer.write(", "); } else { this.writer.write("; "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } } else { if (this.writingExtraDot) { this.writer.write(".\n"); } write(source, this.context.getPrefixes()); this.writer.write(" "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } write(target); this.precSource = source; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } @Override public void link(Reference source, Reference typeRef, Reference target) { try { if (source.equals(this.precSource)) { if (typeRef.equals(this.precPredicate)) { this.writer.write(", "); } else { this.writer.write("; "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } } else { if (this.writingExtraDot) { this.writer.write(".\n"); } write(source, this.context.getPrefixes()); this.writer.write(" "); write(typeRef, this.context.getPrefixes()); this.writer.write(" "); } write(target, this.context.getPrefixes()); this.precSource = source; this.precPredicate = typeRef; this.writingExtraDot = true; } catch (IOException e) { org.restlet.Context.getCurrentLogger().warning( "Cannot write the representation of a statement due to " + e.getMessage()); } } /** * Write the representation of the given graph of links. * * @param linkset * the given graph of links. * @throws IOException */ private void write(Graph linkset) throws IOException { for (Link link : linkset) { if (link.hasReferenceSource()) { if (link.hasReferenceTarget()) { link(link.getSourceAsReference(), link.getTypeRef(), link.getTargetAsReference()); } else if (link.hasLiteralTarget()) { link(link.getSourceAsReference(), link.getTypeRef(), link.getTargetAsLiteral()); } else if (link.hasLinkTarget()) { // TODO Handle source as link. } else { org.restlet.Context .getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } } else if (link.hasGraphSource()) { this.writingExtraDot = false; if (link.hasReferenceTarget()) { link(link.getSourceAsGraph(), link.getTypeRef(), link.getTargetAsReference()); } else if (link.hasLiteralTarget()) { link(link.getSourceAsGraph(), link.getTypeRef(), link.getTargetAsLiteral()); } else if (link.hasLinkTarget()) { // TODO Handlle source as link. } else { org.restlet.Context .getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } this.writer.write(".\n"); } this.precSource = link.getSourceAsReference(); this.precPredicate = link.getTypeRef(); } } /** * Writes the representation of a literal. * * @param literal * The literal to write. * @throws IOException */ private void write(Literal literal) throws IOException { // Write it as a string this.writer.write("\""); if (literal.getValue().contains("\n")) { this.writer.write("\""); this.writer.write("\""); this.writer.write(literal.getValue()); this.writer.write("\""); this.writer.write("\""); } else { this.writer.write(literal.getValue()); } this.writer.write("\""); if (literal.getDatatypeRef() != null) { this.writer.write("^^"); write(literal.getDatatypeRef(), context.getPrefixes()); } if (literal.getLanguage() != null) { this.writer.write("@"); this.writer.write(literal.getLanguage().toString()); } } /** * Writes the representation of a given reference. * * @param reference * The reference to write. * @param prefixes * The map of known namespaces. * @throws IOException */ private void write(Reference reference, Map prefixes) throws IOException { String uri = reference.toString(); if (Link.isBlankRef(reference)) { this.writer.write(uri); } else { boolean found = false; for (String key : prefixes.keySet()) { if (uri.startsWith(key)) { found = true; this.writer.append(prefixes.get(key)); this.writer.append(":"); this.writer.append(uri.substring(key.length())); break; } } if (!found) { this.writer.append("<"); this.writer.append(uri); this.writer.append(">"); } } } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3Reader.java0000664000175000017500000005155611757206350031250 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.n3; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.data.Reference; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.GraphHandler; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.internal.RdfConstants; import org.restlet.ext.rdf.internal.turtle.BlankNodeToken; import org.restlet.ext.rdf.internal.turtle.Context; import org.restlet.ext.rdf.internal.turtle.LexicalUnit; import org.restlet.ext.rdf.internal.turtle.ListToken; import org.restlet.ext.rdf.internal.turtle.RdfTurtleReader; import org.restlet.ext.rdf.internal.turtle.StringToken; import org.restlet.ext.rdf.internal.turtle.Token; import org.restlet.ext.rdf.internal.turtle.UriToken; import org.restlet.representation.Representation; /** * Handler of RDF content according to the N3 notation. * * @author Thierry Boileau */ public class RdfN3Reader extends RdfTurtleReader { /** * Constructor. * * @param rdfRepresentation * The representation to read. * @param graphHandler * The graph handler invoked during the parsing. * @throws IOException */ public RdfN3Reader(Representation rdfN3Representation, GraphHandler graphHandler) throws IOException { super(rdfN3Representation, graphHandler); } @Override protected void generateLinks(List lexicalUnits) { Object currentSubject = null; Reference currentPredicate = null; Object currentObject = null; int nbTokens = 0; boolean swapSubjectObject = false; // Stores the list of parsed subjects. List subjects = new ArrayList(); for (int i = 0; i < lexicalUnits.size(); i++) { LexicalUnit lexicalUnit = lexicalUnits.get(i); nbTokens++; switch (nbTokens) { case 1: if (",".equals(lexicalUnit.getValue())) { nbTokens++; } else if (";".equals(lexicalUnit.getValue())) { if (!subjects.isEmpty()) { currentSubject = subjects.get(subjects.size() - 1); } } else { if ("!".equalsIgnoreCase(lexicalUnit.getValue())) { currentObject = new BlankNodeToken(newBlankNodeId()) .resolve(); currentPredicate = getPredicate(lexicalUnits.get(++i)); this.link(currentSubject, currentPredicate, currentObject); currentSubject = currentObject; nbTokens = 1; } else if ("^".equalsIgnoreCase(lexicalUnit.getValue())) { currentObject = currentSubject; currentPredicate = getPredicate(lexicalUnits.get(++i)); currentSubject = new BlankNodeToken(newBlankNodeId()) .resolve(); this.link(currentSubject, currentPredicate, currentObject); nbTokens = 1; } else { currentSubject = lexicalUnit.resolve(); subjects.add(currentSubject); } } break; case 2: if ("is".equalsIgnoreCase(lexicalUnit.getValue())) { nbTokens--; swapSubjectObject = true; } else if ("has".equalsIgnoreCase(lexicalUnit.getValue())) { nbTokens--; } else if ("=".equalsIgnoreCase(lexicalUnit.getValue())) { currentPredicate = RdfConstants.PREDICATE_SAME; } else if ("=>".equalsIgnoreCase(lexicalUnit.getValue())) { currentPredicate = RdfConstants.PREDICATE_IMPLIES; } else if ("<=".equalsIgnoreCase(lexicalUnit.getValue())) { swapSubjectObject = true; currentPredicate = RdfConstants.PREDICATE_IMPLIES; } else if ("a".equalsIgnoreCase(lexicalUnit.getValue())) { currentPredicate = RdfConstants.PREDICATE_TYPE; } else if ("!".equalsIgnoreCase(lexicalUnit.getValue())) { currentObject = new BlankNodeToken(newBlankNodeId()) .resolve(); currentPredicate = getPredicate(lexicalUnits.get(++i)); this.link(currentSubject, currentPredicate, currentObject); currentSubject = currentObject; nbTokens = 1; } else if ("^".equalsIgnoreCase(lexicalUnit.getValue())) { currentObject = currentSubject; currentPredicate = getPredicate(lexicalUnits.get(++i)); currentSubject = new BlankNodeToken(newBlankNodeId()) .resolve(); this.link(currentSubject, currentPredicate, currentObject); nbTokens = 1; } else { currentPredicate = getPredicate(lexicalUnit); } break; case 3: if ("of".equalsIgnoreCase(lexicalUnit.getValue())) { nbTokens--; } else { // take care of the "path" shorthands. int j = i + 1; if (j < lexicalUnits.size() && isPath(lexicalUnits.get(j))) { if ("!" .equalsIgnoreCase(lexicalUnits.get(j) .getValue())) { // Create a new BlankNode which is the object of the // current link. currentObject = new BlankNodeToken(newBlankNodeId()) .resolve(); this.link(currentSubject, currentPredicate, currentObject); // Interpret the "!" path currentPredicate = getPredicate(lexicalUnits .get(j + 1)); this.link(lexicalUnit.resolve(), currentPredicate, currentObject); currentSubject = currentObject; nbTokens = 0; i += 2; } else if ("^".equalsIgnoreCase(lexicalUnits.get(j) .getValue())) { // Create a new BlankNode which is the object of the // current link. currentObject = new BlankNodeToken(newBlankNodeId()) .resolve(); this.link(currentSubject, currentPredicate, currentObject); // Interpret the "^" path currentSubject = currentObject; currentPredicate = getPredicate(lexicalUnits .get(j + 1)); currentObject = lexicalUnit.resolve(); this.link(currentSubject, currentPredicate, currentObject); nbTokens = 0; i += 2; } } else { if (swapSubjectObject) { currentObject = currentSubject; currentSubject = lexicalUnit.resolve(); this.link(currentSubject, currentPredicate, currentObject); currentSubject = currentObject; } else { currentObject = lexicalUnit.resolve(); this.link(currentSubject, currentPredicate, currentObject); } nbTokens = 0; swapSubjectObject = false; } } break; default: break; } } } /** * Returns the given lexical unit as a predicate. * * @param lexicalUnit * The lexical unit to get as a predicate. * @return A RDF URI reference of the predicate. */ private Reference getPredicate(LexicalUnit lexicalUnit) { Reference result = null; Object p = lexicalUnit.resolve(); if (p instanceof Reference) { result = (Reference) p; } else if (p instanceof String) { result = new Reference((String) p); } return result; } @Override protected boolean isDelimiter(int c) { return isWhiteSpace(c) || c == '^' || c == '!' || c == '=' || c == '<' || c == '"' || c == '{' || c == '}' || c == '[' || c == ']' || c == '(' || c == ')' || c == '.' || c == ';' || c == ',' || c == '@'; } /** * Returns true if the given lexical unit is a "path" shorthand. * * @param lexicalUnit * The lexical unit to analyse. * @return True if the given lexical unit is a "path" shorthand. */ protected boolean isPath(LexicalUnit lexicalUnit) { return "!".equals(lexicalUnit.getValue()) || "^".equals(lexicalUnit.getValue()); } /** * Callback method used when a link is parsed or written. * * @param source * The source or subject of the link. * @param typeRef * The type reference of the link. * @param target * The target or object of the link. */ @Override protected void link(Object source, Reference typeRef, Object target) { if (source instanceof Reference) { if (target instanceof Reference) { getGraphHandler().link((Reference) source, typeRef, (Reference) target); } else if (target instanceof Literal) { getGraphHandler().link((Reference) source, typeRef, (Literal) target); } else { org.restlet.Context .getCurrentLogger() .warning( "The N3 document contains an object which is neither a Reference nor a literal: " + target); org.restlet.Context.getCurrentLogger().warning( getParsingMessage()); } } else if (source instanceof Graph) { if (target instanceof Reference) { getGraphHandler().link((Graph) source, typeRef, (Reference) target); } else if (target instanceof Literal) { getGraphHandler().link((Graph) source, typeRef, (Literal) target); } else { org.restlet.Context .getCurrentLogger() .warning( "The N3 document contains an object which is neither a Reference nor a literal: " + target); org.restlet.Context.getCurrentLogger().warning( getParsingMessage()); } } } @Override protected void parseBlankNode(BlankNodeToken blankNode) throws IOException { step(); do { consumeWhiteSpaces(); switch (getChar()) { case '(': blankNode.getLexicalUnits().add( new ListToken(this, getContext())); break; case '<': if (step() == '=') { blankNode.getLexicalUnits().add(new Token("<=")); step(); discard(); } else { stepBack(); blankNode.getLexicalUnits().add( new UriToken(this, getContext())); } break; case '_': blankNode.getLexicalUnits().add( new BlankNodeToken(parseToken())); break; case '"': blankNode.getLexicalUnits().add( new StringToken(this, getContext())); break; case '[': blankNode.getLexicalUnits().add( new BlankNodeToken(this, getContext())); break; case '!': blankNode.getLexicalUnits().add(new Token("!")); step(); discard(); break; case '^': blankNode.getLexicalUnits().add(new Token("^")); step(); discard(); break; case '=': if (step() == '>') { blankNode.getLexicalUnits().add(new Token("=>")); step(); discard(); } else { blankNode.getLexicalUnits().add(new Token("=")); discard(); } break; case '@': // Remove the leading '@' character. step(); discard(); blankNode.getLexicalUnits().add(new Token(this, getContext())); discard(); break; case ';': step(); discard(); blankNode.getLexicalUnits().add(new Token(";")); break; case ',': step(); discard(); blankNode.getLexicalUnits().add(new Token(",")); break; case '#': parseComment(); break; case '{': blankNode.getLexicalUnits().add( new FormulaToken(this, getContext())); break; case ']': break; default: if (!isEndOfFile(getChar())) { blankNode.getLexicalUnits().add( new Token(this, getContext())); } break; } } while (!isEndOfFile(getChar()) && getChar() != ']'); if (getChar() == ']') { // Set the cursor at the right of the list token. step(); } } /** * Parses the given formula token. * * @param formulaToken * The formula token to parse. * @throws IOException */ protected void parseFormula(FormulaToken formulaToken) throws IOException { step(); do { parseStatement(new Context()); } while (!isEndOfFile(getChar()) && getChar() != '}'); if (getChar() == '}') { // Set the cursor at the right of the formula token. step(); } } @Override protected void parseList(ListToken listToken) throws IOException { step(); do { consumeWhiteSpaces(); switch (getChar()) { case '(': listToken.getLexicalUnits().add( new ListToken(this, getContext())); break; case '<': if (step() == '=') { listToken.getLexicalUnits().add(new Token("<=")); step(); discard(); } else { stepBack(); listToken.getLexicalUnits().add( new UriToken(this, getContext())); } break; case '_': listToken.getLexicalUnits().add( new BlankNodeToken(this.parseToken())); break; case '"': listToken.getLexicalUnits().add( new StringToken(this, getContext())); break; case '[': listToken.getLexicalUnits().add( new BlankNodeToken(this, getContext())); break; case '{': listToken.getLexicalUnits().add( new FormulaToken(this, getContext())); break; case ')': break; default: if (!isEndOfFile(getChar())) { listToken.getLexicalUnits().add( new Token(this, getContext())); } break; } } while (!isEndOfFile(getChar()) && getChar() != ')'); if (getChar() == ')') { // Set the cursor at the right of the list token. step(); } } @Override protected void parseStatement(Context context) throws IOException { List lexicalUnits = new ArrayList(); do { consumeWhiteSpaces(); switch (getChar()) { case '(': lexicalUnits.add(new ListToken(this, context)); break; case '<': if (step() == '=') { lexicalUnits.add(new Token("<=")); step(); discard(); } else { stepBack(); lexicalUnits.add(new UriToken(this, context)); } break; case '_': lexicalUnits.add(new BlankNodeToken(parseToken())); break; case '"': lexicalUnits.add(new StringToken(this, context)); break; case '[': lexicalUnits.add(new BlankNodeToken(this, context)); break; case '!': lexicalUnits.add(new Token("!")); step(); discard(); break; case '^': lexicalUnits.add(new Token("^")); step(); discard(); break; case '=': if (step() == '>') { lexicalUnits.add(new Token("=>")); step(); discard(); } else { lexicalUnits.add(new Token("=")); discard(); } break; case '@': // Remove the leading '@' character. step(); discard(); lexicalUnits.add(new Token(this, context)); discard(); break; case ';': step(); discard(); lexicalUnits.add(new Token(";")); break; case ',': step(); discard(); lexicalUnits.add(new Token(",")); break; case '{': lexicalUnits.add(new FormulaToken(this, context)); break; case '#': parseComment(); break; case '.': break; default: if (!isEndOfFile(getChar())) { lexicalUnits.add(new Token(this, context)); } break; } } while (!isEndOfFile(getChar()) && getChar() != '.' && getChar() != '}'); // Generate the links generateLinks(lexicalUnits); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/FormulaToken.java0000664000175000017500000000406711757206350031612 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf.internal.n3; import java.io.IOException; import org.restlet.ext.rdf.internal.turtle.Context; import org.restlet.ext.rdf.internal.turtle.LexicalUnit; /** * Allows to parse a formula in RDF N3 notation. Please note that this kind of * feature is not supported yet. * * @author Thierry Boileau */ public class FormulaToken extends LexicalUnit { @Override public Object resolve() { org.restlet.Context.getCurrentLogger().warning( "Formulae are not supported yet."); return null; } public FormulaToken(RdfN3Reader contentHandler, Context context) throws IOException { super(contentHandler, context); this.parse(); } @Override public void parse() throws IOException { ((RdfN3Reader) getContentReader()).parseFormula(this); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfClientResource.java0000664000175000017500000002667311757206350030441 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ClientInfo; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Reference; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.util.Couple; /** * Linked client resource. In addition to regular client resources, this class * offers additional method aware of links exposed by RDF, making it natural to * navigate the Web of data. * * @author Jerome Louvel */ public class RdfClientResource extends ClientResource { /** The links cache. */ private Graph links; /** * Constructor. * * @param context * The context. * @param method * The method to call. * @param reference * The target reference. */ public RdfClientResource(Context context, Method method, Reference reference) { super(context, method, reference); } /** * Constructor. * * @param context * The context. * @param method * The method to call. * @param uri * The target URI. */ public RdfClientResource(Context context, Method method, String uri) { super(context, method, uri); } /** * Constructor. * * @param context * The context. * @param method * The method to call. * @param uri * The target URI. */ public RdfClientResource(Context context, Method method, URI uri) { super(context, method, uri); } /** * Constructor. * * @param context * The context. * @param reference * The target reference. */ public RdfClientResource(Context context, Reference reference) { super(context, reference); } /** * Constructor. * * @param context * The current context. * @param request * The handled request. * @param response * The handled response. */ public RdfClientResource(Context context, Request request, Response response) { super(context, request, response); } /** * Constructor. * * @param context * The context. * @param uri * The target URI. */ public RdfClientResource(Context context, String uri) { super(context, uri); } /** * Constructor. * * @param context * The context. * @param uri * The target URI. */ public RdfClientResource(Context context, URI uri) { super(context, uri); } /** * Constructor. * * @param method * The method to call. * @param reference * The target reference. */ public RdfClientResource(Method method, Reference reference) { super(method, reference); } /** * Constructor. * * @param method * The method to call. * @param uri * The target URI. */ public RdfClientResource(Method method, String uri) { super(method, uri); } /** * Constructor. * * @param method * The method to call. * @param uri * The target URI. */ public RdfClientResource(Method method, URI uri) { super(method, uri); } /** * Constructor. * * @param reference * The target reference. */ public RdfClientResource(Reference reference) { super(reference); } /** * Constructor. * * @param request * The handled request. * @param response * The handled response. */ public RdfClientResource(Request request, Response response) { super(request, response); } /** * Constructor. * * @param uri * The target URI. */ public RdfClientResource(String uri) { super(uri); } /** * Constructor. * * @param uri * The target URI. */ public RdfClientResource(URI uri) { super(uri); } /** * Returns all the linked resources, based on the RDF representation * exposed. * * @return All the linked resources. * @see #getLinks() */ public Set getLinked() { return getLinked((Collection) null); } /** * Returns the linked resources, based on the RDF representation exposed. * The type of links to follow can be restricted. * * @param typeRefs * The set of types references of the links to select or null. * @return All the linked resources. * @see #getLinks() */ public Set getLinked(Collection typeRefs) { Set result = null; Graph links = getLinks(); if (links != null) { result = new HashSet(); for (Link link : links) { if (link.hasReferenceTarget()) { if ((typeRefs == null) || typeRefs.contains(link.getTypeRef())) { result.add(new RdfClientResource(getContext(), link .getTargetAsReference())); } } } } return result; } /** * Returns the linked resources, based on the RDF representation exposed. * The type of links to follow can be restricted. * * @param typeRef * The type reference of the links to select or null. * @return All the linked resources. * @see #getLinks() */ public Set getLinked(Reference typeRef) { return getLinked(Collections.singleton(typeRef)); } /** * Returns the links exposed by this resource. * * @return The links exposed by this resource. */ public Graph getLinks() { Graph result = this.links; if (result == null) { ClientInfo currentInfo = getClientInfo(); // Customize the preferences to maximize the chance of getting RDF ClientInfo newInfo = new ClientInfo(); newInfo.getAcceptedMediaTypes().add( new Preference(MediaType.APPLICATION_RDF_XML)); newInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_RDF_N3)); newInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_RDF_NTRIPLES)); newInfo.getAcceptedMediaTypes() .add( new Preference( MediaType.APPLICATION_RDF_TURTLE)); newInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_XML, 0.5F)); newInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN, 0.4F)); newInfo.getAcceptedMediaTypes().add( new Preference(MediaType.APPLICATION_ALL_XML, 0.3F)); // Attempt to retrieve the RDF representation try { Representation rep = get(); if (rep != null) { RdfRepresentation rdfRep = new RdfRepresentation(rep); this.links = rdfRep.getGraph(); result = this.links; } else { getLogger().log( Level.WARNING, "Unable to retrieve an RDF representation of this resource: " + getReference()); } } catch (Throwable e) { getLogger().log( Level.WARNING, "Unable to retrieve an RDF representation of this resource: " + getReference(), e); } // Restore previous preferences setClientInfo(currentInfo); } return result; } /** * Returns all the linked literals, based on the RDF representation exposed. * * @return All the linked literals. * @see #getLinks() */ public Set> getLiterals() { Set> result = null; Graph links = getLinks(); if (links != null) { for (Link link : links) { if (link.hasLiteralTarget()) { if (result == null) { result = new HashSet>(); } result.add(new Couple( link.getTypeRef(), link.getTargetAsLiteral())); } } } return result; } /** * Returns the linked literals, based on the RDF representation exposed. The * type of links to follow can be restricted. * * @param typeRef * The type reference of the links to select or null. * @return All the linked literals. * @see #getLiterals() */ public Set getLiterals(Reference typeRef) { Set result = null; Graph links = getLinks(); if (links != null) { result = new HashSet(); for (Link link : links) { if (link.hasLiteralTarget()) { if ((typeRef == null) || typeRef.equals(link.getTypeRef())) { result.add(link.getTargetAsLiteral()); } } } } return result; } /** * Refreshes the links cache. */ public void refresh() { this.links = null; getLinks(); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/GraphHandler.java0000664000175000017500000001000211757206350027371 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import java.io.IOException; import org.restlet.data.Reference; /** * Handler for the content of a Graph. List of callbacks used when parsing or * writing a representation of a RDF graph. */ public abstract class GraphHandler { /** * Callback method used after the graph is parsed or written. Does nothing * by default. * * @throws IOException */ public void endGraph() throws IOException { } /** * Callback method used at the end of a Namespace mapping. Does nothing by * default. * * @param prefix * The Namespace prefix. */ public void endPrefixMapping(String prefix) { } /** * Callback method used when a link is parsed or written. * * @param source * The source or subject of the link. * @param typeRef * The type reference of the link. * @param target * The target or object of the link. */ public abstract void link(Graph source, Reference typeRef, Literal target); /** * Callback method used when a link is parsed or written. * * @param source * The source or subject of the link. * @param typeRef * The type reference of the link. * @param target * The target or object of the link. */ public abstract void link(Graph source, Reference typeRef, Reference target); /** * Callback method used when a link is parsed or written. * * @param source * The source or subject of the link. * @param typeRef * The type reference of the link. * @param target * The target or object of the link. */ public abstract void link(Reference source, Reference typeRef, Literal target); /** * Callback method used when a link is parsed or written. * * @param source * The source or subject of the link. * @param typeRef * The type reference of the link. * @param target * The target or object of the link. */ public abstract void link(Reference source, Reference typeRef, Reference target); /** * Callback method used before the graph is parsed or written. Does nothing * by default. * * @throws IOException */ public void startGraph() throws IOException { } /** * Callback method used at the start of a Namespace mapping. Does nothing by * default. * * @param prefix * The Namespace prefix being declared. * @param reference * The Namespace URI mapped to the prefix. */ public void startPrefixMapping(String prefix, Reference reference) { } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/package.html0000664000175000017500000000040011757206350026451 0ustar jamespagejamespage Support for the RDF parsing and generation. It supports major RDF serialization formats: n3, Turtle, N-Triples and RDF/XML. @since Restlet 2.0 @see Resource Description Framework restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/Graph.java0000664000175000017500000002162211757206350026105 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import java.util.concurrent.CopyOnWriteArraySet; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.representation.Representation; /** * Graph composed of links. This also called a set of RDF statements or a RDF * model. * * @author Jerome Louvel */ public class Graph extends CopyOnWriteArraySet { /** The serialization unique identifier. */ private static final long serialVersionUID = 1L; /** The default link that is used to complete new links. */ private Link defaultLink; /** * Default constructor. */ public Graph() { this((Link) null); } /** * Constructor with a default link. * * @param defaultLink * The link to use when adding links with missing properties. */ public Graph(Link defaultLink) { this.defaultLink = defaultLink; } /** * Creates then adds a link. If one of the parameter is null, the value from * {@link #getDefaultLink()} is used instead if possible. * * @param sourceGraph * The source graph. * @param typeRef * The type reference. * @param targetLit * The target literal. * @return The created link. */ public Link add(Graph sourceGraph, Reference typeRef, Literal targetLit) { Link result = new Link(getSourceAsGraph(sourceGraph), getTypeRef(typeRef), getTargetAsLiteral(targetLit)); add(result); return result; } /** * Creates then adds a link. If one of the parameter is null, the value from * {@link #getDefaultLink()} is used instead if possible. * * @param sourceGraph * The source graph. * @param typeRef * The type reference. * @param targetRef * The target reference. * @return The created link. */ public Link add(Graph sourceGraph, Reference typeRef, Reference targetRef) { Link result = new Link(getSourceAsGraph(sourceGraph), getTypeRef(typeRef), getTargetAsReference(targetRef)); add(result); return result; } /** * Creates then adds a link. If one of the parameter is null, the value from * {@link #getDefaultLink()} is used instead if possible. * * @param sourceRef * The source resource reference. * @param typeRef * The type reference. * @param targetLit * The target literal. * @return The created link. */ public Link add(Reference sourceRef, Reference typeRef, Literal targetLit) { Link result = new Link(getSourceAsReference(sourceRef), getTypeRef(typeRef), getTargetAsLiteral(targetLit)); add(result); return result; } /** * Creates then adds a link. If one of the parameter is null, the value from * {@link #getDefaultLink()} is used instead if possible. * * @param sourceRef * The source resource reference. * @param typeRef * The type reference. * @param targetRef * The target resource reference. * @return The created link. */ public Link add(Reference sourceRef, Reference typeRef, Reference targetRef) { Link result = new Link(getSourceAsReference(sourceRef), getTypeRef(typeRef), getTargetAsReference(targetRef)); add(result); return result; } /** * Returns the default link that is used to complete new links. * * @return The default link that is used to complete new links. */ public Link getDefaultLink() { return defaultLink; } /** * Returns a representation in the RDF/n3 format. * * @return A representation in the RDF/n3 format. */ public Representation getRdfN3Representation() { return new RdfRepresentation(this, MediaType.TEXT_RDF_N3); } /** * Returns a representation in the RDF/N-Triples format. * * @return A representation in the RDF/N-Triples format. */ public Representation getRdfNTriplesRepresentation() { return new RdfRepresentation(this, MediaType.TEXT_PLAIN); } /** * Returns a representation in the RDF/Turtle format. * * @return A representation in the RDF/Turtle format. */ public Representation getRdfTurtleRepresentation() { return new RdfRepresentation(this, MediaType.APPLICATION_RDF_TURTLE); } /** * Returns a representation in the RDF/XML format. * * @return A representation in the RDF/XML format. */ public Representation getRdfXmlRepresentation() { return new RdfRepresentation(this, MediaType.TEXT_XML); } /** * Returns the source reference, either the one given in the sourceRef * parameter or if it is null, the source reference of the default link. * * @param sourceRef * The source reference to check. * @return The source reference. */ private Graph getSourceAsGraph(Graph sourceGraph) { Graph result = sourceGraph; if ((result == null) && (getDefaultLink() != null)) { result = getDefaultLink().getSourceAsGraph(); } return result; } /** * Returns the source reference, either the one given in the sourceRef * parameter or if it is null, the source reference of the default link. * * @param sourceRef * The source reference to check. * @return The source reference. */ private Reference getSourceAsReference(Reference sourceRef) { Reference result = sourceRef; if ((result == null) && (getDefaultLink() != null)) { result = getDefaultLink().getSourceAsReference(); } return result; } /** * Returns the target literal, either the one given in the targetLit * parameter or if it is null, the target literal of the default link. * * @param targetLit * The target literal to check. * @return The target literal. */ private Literal getTargetAsLiteral(Literal targetLit) { Literal result = targetLit; if ((result == null) && (getDefaultLink() != null)) { result = getDefaultLink().getTargetAsLiteral(); } return result; } /** * Returns the target reference, either the one given in the targetRef * parameter or if it is null, the target reference of the default link. * * @param targetRef * The target reference to check. * @return The target reference. */ private Reference getTargetAsReference(Reference targetRef) { Reference result = targetRef; if ((result == null) && (getDefaultLink() != null)) { result = getDefaultLink().getTargetAsReference(); } return result; } /** * Returns the type reference, either the one given in the typeRef parameter * or if it is null, the type reference of the default link. * * @param typeRef * The type reference to check. * @return The type reference. */ private Reference getTypeRef(Reference typeRef) { Reference result = typeRef; if ((result == null) && (getDefaultLink() != null)) { result = getDefaultLink().getTypeRef(); } return result; } /** * Sets the default link that is used to complete new links. * * @param defaultLink * The default link that is used to complete new links. */ public void setDefaultLink(Link defaultLink) { this.defaultLink = defaultLink; } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfRepresentation.java0000664000175000017500000003065211757206350030505 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import java.io.IOException; import java.io.Writer; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.rdf.internal.n3.RdfN3Reader; import org.restlet.ext.rdf.internal.n3.RdfN3Writer; import org.restlet.ext.rdf.internal.ntriples.RdfNTriplesReader; import org.restlet.ext.rdf.internal.ntriples.RdfNTriplesWriter; import org.restlet.ext.rdf.internal.turtle.RdfTurtleReader; import org.restlet.ext.rdf.internal.turtle.RdfTurtleWriter; import org.restlet.ext.rdf.internal.xml.RdfXmlReader; import org.restlet.ext.rdf.internal.xml.RdfXmlWriter; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; /** * Generic RDF representation. Provides support for the Resource Description * Framework (RDF) Semantic Web standard. It supports major RDF serialization * formats (n3, Turtle, N-Triples and RDF/XML) and is able to both serialize and * deserialize a {@link Graph}. * * @author Jerome Louvel */ public class RdfRepresentation extends WriterRepresentation { /** The inner graph of links. */ private Graph graph; /** The inner RDF representation. */ private Representation rdfRepresentation; /** * Constructor. */ public RdfRepresentation() { super(MediaType.TEXT_XML); } /** * Constructor with argument. * * @param linkSet * The graph of links. * @param mediaType * The representation's mediaType. */ public RdfRepresentation(Graph linkSet, MediaType mediaType) { super(mediaType); this.graph = linkSet; } /** * Constructor with argument. * * @param mediaType * The representation's mediaType. */ public RdfRepresentation(MediaType mediaType) { super(mediaType); } /** * Constructor that parsed a given RDF representation into a link set. * * @param rdfRepresentation * The RDF representation to parse. * @throws IOException */ public RdfRepresentation(Representation rdfRepresentation) throws IOException { super(rdfRepresentation.getMediaType()); this.rdfRepresentation = rdfRepresentation; } /** * Returns an instance of a graph handler used when parsing the inner RDF * representation. * * @param graph * The graph to build. * @return An instance of a graph handler used when parsing the inner RDF * representation. */ public GraphHandler createBuilder(Graph graph) { return new GraphBuilder(this.graph); } /** * Returns an instance of a graph handler used when writing the inner set of * links. * * @param mediaType * The given media type of the parsed RDF representation. * @param writer * The character writer to write to. * @return An instance of a graph handler used when writing the inner set of * links. * @throws IOException */ public GraphHandler createWriter(MediaType mediaType, Writer writer) throws IOException { if (MediaType.TEXT_RDF_N3.equals(getMediaType())) { return new RdfN3Writer(writer); } else if (MediaType.TEXT_XML.equals(getMediaType())) { return new RdfXmlWriter(writer); } else if (MediaType.APPLICATION_ALL_XML.includes(getMediaType())) { return new RdfXmlWriter(writer); } else if (MediaType.TEXT_PLAIN.equals(getMediaType())) { return new RdfNTriplesWriter(writer); } else if (MediaType.TEXT_RDF_NTRIPLES.equals(getMediaType())) { return new RdfNTriplesWriter(writer); } else if (MediaType.APPLICATION_RDF_TURTLE.equals(getMediaType())) { return new RdfTurtleWriter(writer); } // Writing for other media types goes here. return null; } /** * Updates the list of known namespaces for the given graph of links. * * @param linkset * The given graph of links. * @param GraphHandler * the graph handler. */ private void discoverNamespaces(Graph linkset, GraphHandler graphHandler) { for (Link link : linkset) { discoverNamespaces(link, graphHandler); } } /** * Updates the list of known namespaces of the XML writer for the given * link. * * @param link * The given link. * @param GraphHandler * the graph handler. */ private void discoverNamespaces(Link link, GraphHandler graphHandler) { // The subject of the link is not discovered, it is generated as the // value of an "about" attribute. if (link.hasLinkSource()) { discoverNamespaces(link.getSourceAsLink(), graphHandler); } else if (link.hasGraphSource()) { discoverNamespaces(link.getSourceAsGraph(), graphHandler); } discoverNamespaces(link.getTypeRef(), graphHandler); if (link.hasLinkTarget()) { discoverNamespaces(link.getTargetAsLink(), graphHandler); } else if (link.hasGraphSource()) { discoverNamespaces(link.getSourceAsGraph(), graphHandler); } } /** * Updates the list of known namespaces of the XML writer for the given * reference. * * @param reference * The given reference. * @param xmlWriter * the XML writer. */ private void discoverNamespaces(Reference reference, GraphHandler graphHandler) { if (!Link.isBlankRef(reference)) { graphHandler.startPrefixMapping(null, reference); } } /** * Returns the graph of links. * * @return The graph of links. * @throws Exception */ public Graph getGraph() throws Exception { if (this.graph == null) { this.graph = new Graph(); parse(createBuilder(this.graph)); } return this.graph; } /** * Parses the inner RDF representation. The given graph handler is invoked * each time a link is detected. * * @param graphHandler * The graph handler. * @throws Exception */ public void parse(GraphHandler graphHandler) throws Exception { if (rdfRepresentation != null) { if (MediaType.TEXT_RDF_N3.equals(rdfRepresentation.getMediaType())) { new RdfN3Reader(rdfRepresentation, graphHandler).parse(); } else if (MediaType.TEXT_XML.equals(rdfRepresentation .getMediaType())) { new RdfXmlReader(rdfRepresentation, graphHandler).parse(); } else if (MediaType.APPLICATION_ALL_XML.includes(rdfRepresentation .getMediaType())) { new RdfXmlReader(rdfRepresentation, graphHandler).parse(); } else if (MediaType.TEXT_PLAIN.equals(rdfRepresentation .getMediaType())) { new RdfNTriplesReader(rdfRepresentation, graphHandler).parse(); } else if (MediaType.TEXT_RDF_NTRIPLES.equals(rdfRepresentation .getMediaType())) { new RdfNTriplesReader(rdfRepresentation, graphHandler).parse(); } else if (MediaType.APPLICATION_RDF_TURTLE .equals(rdfRepresentation.getMediaType())) { new RdfTurtleReader(rdfRepresentation, graphHandler).parse(); } else if (MediaType.valueOf("text/rdf+n3").equals( rdfRepresentation.getMediaType())) { // Deprecated media type still in usage new RdfN3Reader(rdfRepresentation, graphHandler).parse(); } // Parsing for other media types goes here. } } /** * Sets the graph of links. * * @param linkSet * The graph of links. */ public void setGraph(Graph linkSet) { this.graph = linkSet; } /** * Writes the * * @param graphHandler * @throws IOException */ public void write(GraphHandler graphHandler) throws IOException { try { if (graph != null) { discoverNamespaces(graph, graphHandler); graphHandler.startGraph(); for (Link link : graph) { if (link.hasReferenceSource()) { if (link.hasReferenceTarget()) { graphHandler.link(link.getSourceAsReference(), link.getTypeRef(), link.getTargetAsReference()); } else if (link.hasLiteralTarget()) { graphHandler.link(link.getSourceAsReference(), link.getTypeRef(), link.getTargetAsLiteral()); } else if (link.hasLinkTarget()) { Context.getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } else { Context.getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } } else if (link.hasGraphSource()) { if (link.hasReferenceTarget()) { graphHandler.link(link.getSourceAsGraph(), link.getTypeRef(), link.getTargetAsReference()); } else if (link.hasLiteralTarget()) { graphHandler.link(link.getSourceAsGraph(), link.getTypeRef(), link.getTargetAsLiteral()); } else if (link.hasLinkTarget()) { Context.getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } else { Context.getCurrentLogger() .warning( "Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal."); } } } graphHandler.endGraph(); } } catch (Exception e) { Context.getCurrentLogger() .log(Level.WARNING, "Cannot write the RDF graph due to an unexpected exception", e); } } @Override public void write(Writer writer) throws IOException { write(createWriter(getMediaType(), writer)); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/Literal.java0000664000175000017500000001047311757206350026442 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import org.restlet.data.Language; import org.restlet.data.Reference; /** * Literal as defined by RDF. Composed of the literal value, optional datatype * reference and language properties. * * @author Jerome Louvel * @see RDF * literals */ public class Literal { /** The optional datatype reference. */ private Reference datatypeRef; /** The optional language. */ private Language language; /** The value. */ private String value; /** * Constructor. * * @param value * The value. */ public Literal(String value) { this(value, null, null); } /** * Constructor. * * @param value * The value. * @param datatypeRef * The optional datatype reference. */ public Literal(String value, Reference datatypeRef) { this(value, datatypeRef, null); } /** * Constructor. * * @param value * The value. * @param datatypeRef * The optional datatype reference. * @param language * The optional language. */ public Literal(String value, Reference datatypeRef, Language language) { this.value = value; this.datatypeRef = datatypeRef; this.language = language; } /** * Returns the optional datatype reference. * * @return The datatype reference or null. */ public Reference getDatatypeRef() { return datatypeRef; } /** * Returns the optional language. * * @return The language or null. */ public Language getLanguage() { return language; } /** * Returns the value. * * @return The value. */ public String getValue() { return value; } /** * Indicates if the literal is plain. Plain literals have a value and an * optional language tag. * * @return True if the literal is plain. */ public boolean isPlain() { return (getValue() != null) && (getDatatypeRef() == null); } /** * Indicates if the literal is types. Typed literals have a value and a * datatype reference. * * @return True if the literal is typed. */ public boolean isTyped() { return (getValue() != null) && (getDatatypeRef() != null); } /** * Sets the datatype reference. * * @param datatypeRef * The datatype reference. */ public void setDatatypeRef(Reference datatypeRef) { this.datatypeRef = datatypeRef; } /** * Sets the language. * * @param language * The language. */ public void setLanguage(Language language) { this.language = language; } /** * Sets the value. * * @param value * The value. */ public void setValue(String value) { this.value = value; } @Override public String toString() { return getValue(); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/Link.java0000664000175000017500000002772711757206350025755 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import org.restlet.data.Reference; import org.restlet.util.Triple; /** * Link between a source resource and a target resource or literal. This exactly * maps with the concepts of statement, triple or relationship defined by RDF, * the core specification of the Semantic Web. A link is composed of a source * node (or subject in RDF terminology), a type URI reference (or predicate in * RDF terminology) and a target node (or object in RDF terminology). * * We use this class in Restlet to enhance resources and make them part of the * Web of data (also know as Linked Data and Hyperdata). * * @author Jerome Louvel * @see RDF concepts */ public class Link extends Triple { /** * Creates a reference to a blank node. In this API, we support RDF blank * nodes using the "_" namespace and local identifiers, in a way similar to * the RDF n3 serialization format. * * @param identifier * The blank node identifier. * @return A reference to a blank node. */ public static Reference createBlankRef(String identifier) { return new Reference("_:" + identifier); } /** * Indicates if a reference is identifying a blank node. * * @param reference * The reference to test. * @return True if a reference is identifying a blank node. * @see #createBlankRef(String) */ public static boolean isBlankRef(Reference reference) { return ((reference != null) && ("_".equals(reference.getScheme()))); } /** * Constructor. Leverages n3 reification feature where a graph itself can be * the source node of a link. * * @param sourceGraph * The source graph or subject in RDF terminology. * @param typeRef * The type reference or predicate in RDF terminology. * @param targetLit * The target literal or object in RDF terminology. */ public Link(Graph sourceGraph, Reference typeRef, Literal targetLit) { this((Object) sourceGraph, typeRef, (Object) targetLit); } /** * Constructor. Leverages n3 reification feature where a graph itself can be * the source node of a link. * * @param sourceGraph * The source graph or subject in RDF terminology. * @param typeRef * The type reference or predicate in RDF terminology. * @param target * The target node or object in RDF terminology. */ public Link(Graph sourceGraph, Reference typeRef, Object target) { this((Object) sourceGraph, typeRef, target); } /** * Constructor. Leverages n3 reification feature where a graph itself can be * the source node of a link. * * @param sourceGraph * The source graph or subject in RDF terminology. * @param typeRef * The type reference or predicate in RDF terminology. * @param targetRef * The target reference or object in RDF terminology. */ public Link(Graph sourceGraph, Reference typeRef, Reference targetRef) { this(sourceGraph, typeRef, (Object) targetRef); } /** * Constructor by copy. * * @param from * The link to copy from. */ public Link(Link from) { this(from.getSource(), from.getTypeRef(), from.getTarget()); } /** * Constructor. * * @param source * The source node or subject in RDF terminology. * @param typeRef * The type reference or predicate in RDF terminology. * @param target * The target node or object in RDF terminology. */ private Link(Object source, Reference typeRef, Object target) { super(source, typeRef, target); } /** * Constructor. * * @param sourceRef * The source resource reference or subject in RDF terminology. * @param typeRef * The type reference or predicate in RDF terminology. * @param targetLit * The target literal node or object in RDF terminology. */ public Link(Reference sourceRef, Reference typeRef, Literal targetLit) { this(sourceRef, typeRef, (Object) targetLit); } /** * Constructor. * * @param sourceRef * The source resource reference or subject in RDF terminology. * @param typeRef * The type reference or predicate in RDF terminology. * @param targetRef * The target resource reference or object in RDF terminology. */ public Link(Reference sourceRef, Reference typeRef, Reference targetRef) { this(sourceRef, typeRef, (Object) targetRef); } /** * Returns the source which can be either a reference or a link or a graph * or null. This maps with the concept of subject in RDF terminology. * * @return The source. */ public Object getSource() { return getFirst(); } /** * Returns the source graph. Supports RDF reification or N3 formulae. * * @return The source graph. * @see #getSource() */ public Graph getSourceAsGraph() { return hasGraphSource() ? (Graph) getSource() : null; } /** * Returns the source link. Supports RDF reification. * * @return The source link. * @see #getSource() */ public Link getSourceAsLink() { return hasLinkSource() ? (Link) getSource() : null; } /** * Returns the source resource reference. * * @return The source resource reference. * @see #getSource() */ public Reference getSourceAsReference() { return hasReferenceSource() ? (Reference) getSource() : null; } /** * Returns the target which can be either a literal or a reference or is * null. This maps with the concept of object in RDF terminology. * * @return The target. */ public Object getTarget() { return getThird(); } /** * Returns the target graph. * * @return The target graph. * @see #getTarget() */ public Graph getTargetAsGraph() { return hasGraphTarget() ? (Graph) getTarget() : null; } /** * Returns the target link. * * @return The target link. * @see #getTarget() */ public Link getTargetAsLink() { return hasLinkTarget() ? (Link) getTarget() : null; } /** * Returns the target literal. * * @return The target literal. * @see #getTarget() */ public Literal getTargetAsLiteral() { return hasLiteralTarget() ? (Literal) getTarget() : null; } /** * Returns the target resource reference. * * @return The target resource reference. * @see #getTarget() */ public Reference getTargetAsReference() { return hasReferenceTarget() ? (Reference) getTarget() : null; } /** * Returns the type reference. This maps with the concept of predicate in * RDF terminology. * * @return The type reference. */ public Reference getTypeRef() { return getSecond(); } /** * Indicates if the source is a graph. * * @return True if the source is a graph. */ public boolean hasGraphSource() { return getSource() instanceof Graph; } /** * Indicates if the target is a graph. * * @return True if the target is a graph. */ public boolean hasGraphTarget() { return getTarget() instanceof Graph; } /** * Indicates if the source is a link. * * @return True if the source is a link. */ public boolean hasLinkSource() { return getSource() instanceof Link; } /** * Indicates if the target is a link. * * @return True if the target is a link. */ public boolean hasLinkTarget() { return getTarget() instanceof Link; } /** * Indicates if the target is a literal. * * @return True if the target is a literal. */ public boolean hasLiteralTarget() { return getTarget() instanceof Literal; } /** * Indicates if the source is a reference. * * @return True if the source is a reference. */ public boolean hasReferenceSource() { return getSource() instanceof Reference; } /** * Indicates if the target is a reference. * * @return True if the target is a reference. */ public boolean hasReferenceTarget() { return getTarget() instanceof Reference; } /** * Sets the source as a graph. This maps with the concept of subject in RDF * terminology. * * @param sourceGraph * The source graph. */ public void setSource(Graph sourceGraph) { setFirst(sourceGraph); } /** * Sets the source as a link. This maps with the concept of subject in RDF * terminology. * * @param sourceLink * The source link. */ public void setSource(Link sourceLink) { setFirst(sourceLink); } /** * Sets the source resource reference. This maps with the concept of subject * in RDF terminology. * * @param sourceRef * The source resource reference. */ public void setSource(Reference sourceRef) { setFirst(sourceRef); } /** * Sets the target as a graph. This maps with the concept of object in RDF * terminology. * * @param targetGraph * The target graph. */ public void setTarget(Graph targetGraph) { setThird(targetGraph); } /** * Sets the target as a link. This maps with the concept of object in RDF * terminology. * * @param targetLink * The target link. */ public void setTarget(Link targetLink) { setThird(targetLink); } /** * Sets the target literal. This maps with the concept of object in RDF * terminology. * * @param targetLit * The target literal. */ public void setTarget(Literal targetLit) { setThird(targetLit); } /** * Sets the target as a resource reference. This maps with the concept of * object in RDF terminology. * * @param targetRef * The target resource reference. */ public void setTarget(Reference targetRef) { setThird(targetRef); } /** * Sets the type reference. This maps with the concept of predicate in RDF * terminology. * * @param typeRef * The type reference. */ public void setTypeRef(Reference typeRef) { setSecond(typeRef); } } restlet-2.0.14/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfConverter.java0000664000175000017500000001277711757206350027462 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rdf; import java.io.IOException; import java.util.List; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between the Graph and RDF Representation classes. * * @author Thierry Boileau */ public class RdfConverter extends ConverterHelper { private static final VariantInfo VARIANT_RDF_N3 = new VariantInfo( MediaType.TEXT_RDF_N3); private static final VariantInfo VARIANT_RDF_NTRIPLES = new VariantInfo( MediaType.TEXT_RDF_NTRIPLES); private static final VariantInfo VARIANT_RDF_TURTLE = new VariantInfo( MediaType.APPLICATION_RDF_TURTLE); private static final VariantInfo VARIANT_RDF_XML = new VariantInfo( MediaType.APPLICATION_ALL_XML); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_RDF_N3.isCompatible(source) || VARIANT_RDF_NTRIPLES.isCompatible(source) || VARIANT_RDF_TURTLE.isCompatible(source) || VARIANT_RDF_XML.isCompatible(source)) { result = addObjectClass(result, Graph.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (source != null && Graph.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_RDF_N3); result = addVariant(result, VARIANT_RDF_NTRIPLES); result = addVariant(result, VARIANT_RDF_NTRIPLES); result = addVariant(result, VARIANT_RDF_XML); } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0f; if (target != null) { if (Graph.class.isAssignableFrom(target)) { result = 1.0f; } } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source instanceof Graph) { if (target == null) { result = 0.5F; } else if (VARIANT_RDF_N3.isCompatible(target) || VARIANT_RDF_NTRIPLES.isCompatible(target) || VARIANT_RDF_TURTLE.isCompatible(target) || VARIANT_RDF_XML.isCompatible(target)) { result = 1.0F; } else { result = 0.5F; } } return result; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; try { if (source instanceof RdfRepresentation) { result = ((RdfRepresentation) source).getGraph(); } else { result = (new RdfRepresentation(source)).getGraph(); } } catch (Exception e) { Context.getCurrentLogger() .warning( "Cannot convert a source representation into a Graph object."); } return target.cast(result); } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { if (source instanceof Graph) { return new RdfRepresentation((Graph) source, target.getMediaType()); } return null; } @Override public void updatePreferences(List> preferences, Class entity) { if (Graph.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.TEXT_RDF_N3, 1.0F); updatePreferences(preferences, MediaType.TEXT_RDF_NTRIPLES, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_RDF_TURTLE, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_RDF_XML, 1.0F); } } } restlet-2.0.14/org.restlet.ext.fileupload/0000775000175000017500000000000012001473136021123 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.fileupload/pom.xml0000600000175000017500000000206112001473136022425 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.fileupload Restlet Extension - FileUpload Integration with Apache FileUpload. javax.servlet servlet-api 2.5 provided commons-fileupload commons-fileupload 1.2.1 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.fileupload/src/0000775000175000017500000000000012001473136021712 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.fileupload/src/META-INF/0000775000175000017500000000000011757206450023064 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.fileupload/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446024524 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.fileupload/src/org/0000775000175000017500000000000011757206346022517 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.fileupload/src/org/restlet/0000775000175000017500000000000011757206346024201 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.fileupload/src/org/restlet/ext/0000775000175000017500000000000011757206346025001 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.fileupload/src/org/restlet/ext/fileupload/0000775000175000017500000000000011757206346027125 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.fileupload/src/org/restlet/ext/fileupload/RestletFileUpload.java0000664000175000017500000001306711757206346033366 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.fileupload; import java.io.IOException; import java.util.List; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadException; import org.restlet.Request; import org.restlet.representation.Representation; /** * High level API for processing file uploads. This class handles multiple files * per single HTML widget, sent using the "multipart/mixed" encoding type, as * specified by RFC 1867. Use {@link #parseRequest(Request)} method to acquire a * list of FileItems associated with a given HTML widget.
*
* How the data for individual parts is stored is determined by the factory used * to create them; a given part may be in memory, on disk, or somewhere else.
*
* In addition, it is possible to use RFC 1867 * compliant multipart/form-data input representation. Note * that this will not result in the writing of the parts on the disk but * will instead allow you to use stream access. * * @param multipartForm * The input representation. * @return An iterator to instances of FileItemStream parsed from the * request. * @throws FileUploadException * @throws IOException * @see FileUpload * Streaming API */ public FileItemIterator getItemIterator(Representation multipartForm) throws FileUploadException, IOException { return getItemIterator(new RepresentationContext(multipartForm)); } /** * Processes an RFC 1867 * compliant multipart/form-data input representation. Note * that this will result in the writing of the parts on the disk. * * @param multipartForm * The multipart representation to be parsed. * @return A list of FileItem instances parsed, in the order * that they were transmitted. * @throws FileUploadException * if there are problems reading/parsing the request or storing * files. */ @SuppressWarnings("unchecked") public List parseRepresentation(Representation multipartForm) throws FileUploadException { return parseRequest(new RepresentationContext(multipartForm)); } /** * Processes an RFC 1867 * compliant multipart/form-data input representation. Note * that this will result in the writing of the parts on the disk. * * @param request * The request containing the entity to be parsed. * @return A list of FileItem instances parsed, in the order * that they were transmitted. * @throws FileUploadException * if there are problems reading/parsing the request or storing * files. */ @SuppressWarnings("unchecked") public List parseRequest(Request request) throws FileUploadException { return parseRequest(new RepresentationContext(request.getEntity())); } } restlet-2.0.14/org.restlet.ext.fileupload/src/org/restlet/ext/fileupload/package.html0000664000175000017500000000046211757206346031410 0ustar jamespagejamespage Integration with Apache FileUpload 1.2. The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your web applications. @since Restlet 1.0 @see Apache Commons FileUpload restlet-2.0.14/org.restlet.ext.fileupload/src/org/restlet/ext/fileupload/RepresentationContext.java0000664000175000017500000000572311757206346034346 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.fileupload; import java.io.IOException; import java.io.InputStream; import org.apache.commons.fileupload.RequestContext; import org.restlet.representation.Representation; /** * Provides access to the representation information needed by the FileUpload * processor. * * @author Jerome Louvel */ public class RepresentationContext implements RequestContext { /** The representation to adapt. */ private volatile Representation multipartForm; /** * Constructor. * * @param multipartForm * The multipart form to parse. */ public RepresentationContext(Representation multipartForm) { this.multipartForm = multipartForm; } /** * Returns the character encoding for the form. * * @return The character encoding for the form. */ public String getCharacterEncoding() { if (this.multipartForm.getCharacterSet() != null) { return this.multipartForm.getCharacterSet().getName(); } return null; } /** * Returns the content length of the form. * * @return The content length of the form. */ public int getContentLength() { return (int) this.multipartForm.getSize(); } /** * Returns the content type of the form. * * @return The content type of the form. */ public String getContentType() { if (this.multipartForm.getMediaType() != null) { return this.multipartForm.getMediaType().toString(); } return null; } /** * Returns the input stream. * * @return The input stream. */ public InputStream getInputStream() throws IOException { return this.multipartForm.getStream(); } } restlet-2.0.14/org.restlet.test/0000775000175000017500000000000012001473213017153 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/pom.xml0000600000175000017500000001051712001473213020462 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.test Restlet Unit Tests All Restlet unit tests. ${basedir}/src junit junit 4.8.1 org.restlet.jse org.restlet.ext.atom 2.0.14 org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.crypto 2.0.14 org.restlet.jse org.restlet.example 2.0.14 org.restlet.jse org.restlet.ext.freemarker 2.0.14 org.restlet.jse org.restlet.ext.grizzly 2.0.14 org.restlet.jse org.restlet.ext.gwt 2.0.14 org.restlet.jse org.restlet.ext.httpclient 2.0.14 org.restlet.jse org.restlet.ext.jackson 2.0.14 org.restlet.jse org.restlet.ext.jaxb 2.0.14 org.restlet.jse org.restlet.ext.jaxrs 2.0.14 org.restlet.jse org.restlet.ext.jetty 2.0.14 org.restlet.jse org.restlet.ext.json 2.0.14 org.restlet.jse org.restlet.ext.lucene 2.0.14 org.restlet.jse org.restlet.ext.net 2.0.14 org.restlet.jse org.restlet.ext.netty 2.0.14 org.restlet.jse org.restlet.ext.odata 2.0.14 org.restlet.jse org.restlet.ext.rdf 2.0.14 org.restlet.jse org.restlet.ext.simple 2.0.14 org.restlet.jse org.restlet.ext.spring 2.0.14 org.restlet.jse org.restlet.ext.velocity 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 org.restlet.jse org.restlet.ext.xstream 2.0.14 org.restlet.jse org.restlet.ext.wadl 2.0.14 restlet-2.0.14/org.restlet.test/src/0000775000175000017500000000000012001473212017741 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/META-INF/0000775000175000017500000000000011757206450021120 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446022560 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.test/src/org/0000775000175000017500000000000011757206352020550 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/0000775000175000017500000000000011757206352022232 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/0000775000175000017500000000000011757206354023213 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/component/0000775000175000017500000000000011757206354025215 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/component/ComponentXmlConfigTestCase.java0000664000175000017500000005634111757206352033274 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.component; import java.util.List; import org.restlet.Client; import org.restlet.Component; import org.restlet.Context; import org.restlet.Server; import org.restlet.data.Parameter; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.routing.TemplateRoute; import org.restlet.routing.VirtualHost; import org.restlet.service.LogService; import org.restlet.test.RestletTestCase; import org.restlet.util.ClientList; import org.restlet.util.ServerList; /** * JUnit test case for the newly added (Component.xsd version 2.0) parameter * elements in a restlet.xml configuration file. *

* Note that the XML data validation IS active but DOES NOT affect the outcome * of the configuration. In other words you can write non Schema compliant XML * data without risking an exception being thrown. Note also that although this * is possible, it is strongly discouraged. The schema validation error message * which is printed in the logs will look like the following --line breaks were * added for clarity: * *

 * Jan 23, 2009 6:11:48 PM org.restlet.util.SaxDefaultHandler error
 * CONFIG: [ERROR] - Unexpected exception while parsing an instance of PUBLIC \
 *     [null], SYSTEM [null] - line #7, column #75: cvc-complex-type.2.4.a: \
 *     Invalid content was found starting with element 'illegal-element'. \
 *     One of '{"http://www.restlet.org/schemas/2.0/Component":client, \
 *     "http://www.restlet.org/schemas/2.0/Component":server, \
 *     "http://www.restlet.org/schemas/2.0/Component":parameter, \
 *     "http://www.restlet.org/schemas/2.0/Component":defaultHost, \
 *     "http://www.restlet.org/schemas/2.0/Component":host, \
 *     "http://www.restlet.org/schemas/2.0/Component":internalRouter, \
 *     "http://www.restlet.org/schemas/2.0/Component":logService, \
 *     "http://www.restlet.org/schemas/2.0/Component":statusService}' is expected.
 * 
*/ public class ComponentXmlConfigTestCase extends RestletTestCase { private static final String A_PARAM_NAME = "attachParamName"; private static final String A_PARAM_VALUE = "attachParamValue"; private static final String ATTACH = "ATTACH"; private static final String C_NAME = "componentParamName"; private static final String C_VALUE = "componentParamValue"; private static final String CLIENT = "CLIENT"; // strings used in output to better identify the context of the check private static final String COMPONENT = "COMPONENT"; private static final String CON_PARAM_NAME = "connectorParamName"; private static final String CON_PARAM_VALUE = "connectorParamValue"; private static final String HOST = "HOST"; private static final boolean LOG_ENABLED = false; private static final String LOG_FORMAT = "logFormat"; private static final boolean LOG_IDENTITY_CHECKED = true; private static final String LOGGER_NAME = "loggerName"; private static final int PORT1 = TEST_PORT; private static final int PORT2 = PORT1 + 1; private static final String R_NAME = "routerParamName"; private static final String R_VALUE = "routerParamValue"; private static final String RESTLET_DESCRIPTION = "restletDescription"; private static final String RESTLET_NAME = "restletName"; /** Correct restlet.xml test instances. */ private static final String RESTLET_XML = "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + ""; private static final String SERVER = "SERVER"; private Component c; /** * Check if a designated {@code init-param} element does not exist within a * given {@link Context}. * * @param msg * contextual message to better describe the output. * @param ctx * the {@link Context} within which the check is performed. * @param n * the name of the {@code init-param} to check for. */ private void checkNegativeParam(String msg, Context ctx, String n) { Parameter p = ctx.getParameters().getFirst(n); assertNull(msg + " Parameter '" + n + "' MUST be null", p); } // default 0-arguments constructor /** * Check if a designated {@code init-param} element exist within a given * {@link Context} with the expected name and value. * * @param msg * contextual message to better describe the output. * @param ctx * the {@link Context} within which the check is performed. * @param n * the name of the {@code context-param} to check for. * @param v * the expected value of the named {@code init-param}. */ private void checkPositiveParam(String msg, Context ctx, String n, String v) { assertNotNull(msg + "Context MUST NOT be null", ctx); Parameter p = ctx.getParameters().getFirst(n); assertNotNull(msg + "Parameter '" + n + "' MUST NOT be null", p); String pValue = p.getValue(); assertNotNull(msg + "Parameter '" + n + "' MUST NOT have a null value", pValue); assertEquals(msg + "Parameter '" + n + "' has unexpected value", v, pValue); } /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); Representation xml = new StringRepresentation(RESTLET_XML); c = new Component(xml); assertNotNull("Component (parsed) MUST NOT be null", c); } @Override protected void tearDown() throws Exception { c.stop(); c = null; super.tearDown(); } public void testAttachParams1a() throws Exception { System.out.println("-- testAttachParams1a()"); TemplateRoute route = c.getDefaultHost().getRoutes().get(0); assertNotNull( "The first Attach element of the Default Host MUST NOT be null", route); String msg = "[" + ATTACH + " #1] "; Context ctx = route.getNext().getContext(); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, C_NAME + "1"); checkNegativeParam(msg, ctx, C_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "1"); checkNegativeParam(msg, ctx, R_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "3"); checkNegativeParam(msg, ctx, R_NAME + "4"); checkPositiveParam(msg, ctx, A_PARAM_NAME + "1", A_PARAM_VALUE + "1"); checkPositiveParam(msg, ctx, A_PARAM_NAME + "2", A_PARAM_VALUE + "2"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "5"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "6"); } public void testAttachParams1b() throws Exception { System.out.println("-- testAttachParams1b()"); TemplateRoute route = c.getDefaultHost().getRoutes().get(1); assertNotNull( "The second Attach element of the Default Host MUST NOT be null", route); String msg = "[" + ATTACH + " #2] "; Context ctx = route.getNext().getContext(); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, C_NAME + "1"); checkNegativeParam(msg, ctx, C_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "1"); checkNegativeParam(msg, ctx, R_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "3"); checkNegativeParam(msg, ctx, R_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "2"); checkPositiveParam(msg, ctx, A_PARAM_NAME + "3", A_PARAM_VALUE + "3"); checkPositiveParam(msg, ctx, A_PARAM_NAME + "4", A_PARAM_VALUE + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "5"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "6"); } public void testAttachParams2() throws Exception { System.out.println("-- testAttachParams2()"); TemplateRoute route = c.getHosts().get(0).getRoutes().get(0); assertNotNull( "The single Attach element of the Single Host MUST NOT be null", route); String msg = "[" + ATTACH + "] "; Context ctx = route.getNext().getContext(); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, C_NAME + "1"); checkNegativeParam(msg, ctx, C_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "1"); checkNegativeParam(msg, ctx, R_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "3"); checkNegativeParam(msg, ctx, R_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "4"); checkPositiveParam(msg, ctx, A_PARAM_NAME + "5", A_PARAM_VALUE + "5"); checkPositiveParam(msg, ctx, A_PARAM_NAME + "6", A_PARAM_VALUE + "6"); } public void testClient() throws Exception { System.out.println("-- testClient()"); ClientList clients = c.getClients(); assertNotNull("Client list MUST NOT be null", clients); assertEquals("Client list MUST contain 1 item", 1, clients.size()); Client client = clients.get(0); assertNotNull("The single Client MUST NOT be null", client); assertEquals(client.getName(), RESTLET_NAME); assertEquals(client.getDescription(), RESTLET_DESCRIPTION); } public void testClientParams() throws Exception { System.out.println("-- testClientParams()"); ClientList clients = c.getClients(); assertNotNull("Client list MUST NOT be null", clients); assertEquals("Client list MUST contain 1 item", 1, clients.size()); Client client = clients.get(0); assertNotNull("The single Client MUST NOT be null", client); String msg = "[" + CLIENT + "] "; Context ctx = client.getContext(); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "2"); checkPositiveParam(msg, ctx, CON_PARAM_NAME + "3", CON_PARAM_VALUE + "3"); checkPositiveParam(msg, ctx, CON_PARAM_NAME + "4", CON_PARAM_VALUE + "4"); checkNegativeParam(msg, ctx, C_NAME + "1"); checkNegativeParam(msg, ctx, C_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "1"); checkNegativeParam(msg, ctx, R_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "3"); checkNegativeParam(msg, ctx, R_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "5"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "6"); } public void testComponentParams() throws Exception { System.out.println("-- testComponentParams()"); String msg = "[" + COMPONENT + "] "; Context ctx = c.getContext(); checkPositiveParam(msg, ctx, C_NAME + "1", C_VALUE + "1"); checkPositiveParam(msg, ctx, C_NAME + "2", C_VALUE + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, R_NAME + "1"); checkNegativeParam(msg, ctx, R_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "3"); checkNegativeParam(msg, ctx, R_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "5"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "6"); } public void testDefaultHost() throws Exception { System.out.println("-- testDefaultHost()"); final VirtualHost dh = c.getDefaultHost(); assertNotNull("Default Host MUST NOT be null", dh); assertEquals(dh.getName(), RESTLET_NAME); assertEquals(dh.getDescription(), RESTLET_DESCRIPTION); } public void testDefaultHostParams() throws Exception { System.out.println("-- testDefaultHostParams()"); VirtualHost dh = c.getDefaultHost(); assertNotNull("Default Host MUST NOT be null", dh); String msg = "[" + HOST + ":" + dh.getHostPort() + "] "; Context ctx = dh.getContext(); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, C_NAME + "1"); checkNegativeParam(msg, ctx, C_NAME + "2"); checkPositiveParam(msg, ctx, R_NAME + "1", R_VALUE + "1"); checkPositiveParam(msg, ctx, R_NAME + "2", R_VALUE + "2"); checkNegativeParam(msg, ctx, R_NAME + "3"); checkNegativeParam(msg, ctx, R_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "5"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "6"); } public void testHostParams() throws Exception { System.out.println("-- testHostParams()"); List hosts = c.getHosts(); assertNotNull("Host List MUST NOT be null", hosts); assertEquals("Server list MUST contain 1 item", 1, hosts.size()); VirtualHost host = hosts.get(0); assertNotNull("The single Host MUST NOT be null", host); String msg = "[" + HOST + ":" + host.getHostPort() + "] "; Context ctx = host.getContext(); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, C_NAME + "1"); checkNegativeParam(msg, ctx, C_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "1"); checkNegativeParam(msg, ctx, R_NAME + "2"); checkPositiveParam(msg, ctx, R_NAME + "3", R_VALUE + "3"); checkPositiveParam(msg, ctx, R_NAME + "4", R_VALUE + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "5"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "6"); } public void testLogService() throws Exception { System.out.println("-- testLogService()"); LogService ls = c.getLogService(); assertNotNull("Log service MUST NOT be null", ls); assertEquals(LOG_ENABLED, ls.isEnabled()); assertEquals(LOG_IDENTITY_CHECKED, ls.isIdentityCheck()); assertEquals(LOG_FORMAT, ls.getLogFormat()); assertEquals(LOGGER_NAME, ls.getLoggerName()); } public void testServer() throws Exception { System.out.println("-- testServerParams()"); ServerList servers = c.getServers(); assertNotNull("Server list MUST NOT be null", servers); assertEquals("Server list MUST contain 1 item", 1, servers.size()); Server server = servers.get(0); assertNotNull("The single Server MUST NOT be null", server); assertEquals(server.getName(), RESTLET_NAME); assertEquals(server.getDescription(), RESTLET_DESCRIPTION); } public void testServerParams() throws Exception { System.out.println("-- testServerParams()"); ServerList servers = c.getServers(); assertNotNull("Server list MUST NOT be null", servers); assertEquals("Server list MUST contain 1 item", 1, servers.size()); Server server = servers.get(0); assertNotNull("The single Server MUST NOT be null", server); String msg = "[" + SERVER + "] "; Context ctx = server.getContext(); checkPositiveParam(msg, ctx, CON_PARAM_NAME + "1", CON_PARAM_VALUE + "1"); checkPositiveParam(msg, ctx, CON_PARAM_NAME + "2", CON_PARAM_VALUE + "2"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, CON_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, C_NAME + "1"); checkNegativeParam(msg, ctx, C_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "1"); checkNegativeParam(msg, ctx, R_NAME + "2"); checkNegativeParam(msg, ctx, R_NAME + "3"); checkNegativeParam(msg, ctx, R_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "1"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "2"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "3"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "4"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "5"); checkNegativeParam(msg, ctx, A_PARAM_NAME + "6"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/component/Component.xml0000664000175000017500000000115511757206354027703 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/component/HelloWorldApplication.java0000664000175000017500000000275211757206352032323 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.component; import org.restlet.Application; import org.restlet.Restlet; public class HelloWorldApplication extends Application { @Override public synchronized Restlet createInboundRoot() { return new HelloWorldRestlet(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/component/ComponentXmlTestCase.java0000664000175000017500000000733511757206352032145 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.component; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.representation.AppendableRepresentation; import org.restlet.test.RestletTestCase; /** * Unit test case for the configuration of a component with an XML file. * * @author Thierry Boileau */ public class ComponentXmlTestCase extends RestletTestCase { private final int port = TEST_PORT; private final int port2 = port + 1; public void testComponentXMLConfig() throws Exception { AppendableRepresentation config = new AppendableRepresentation(); config.append(""); config.append(""); config .append(""); config.append(""); config.append(""); config .append(" "); config.append(""); config.append(""); config .append(" "); config.append(""); config.append(""); final Component component = new Component(config); component.start(); final Client client = new Client(Protocol.HTTP); Response response = client.handle(new Request(Method.GET, "http://localhost:" + this.port + "/efgh")); assertTrue(response.getStatus().isSuccess()); assertTrue(response.isEntityAvailable()); response = client.handle(new Request(Method.GET, "http://localhost:" + this.port + "/abcd")); assertTrue(response.getStatus().isClientError()); response = client.handle(new Request(Method.GET, "http://localhost:" + this.port2 + "/abcd")); assertTrue(response.getStatus().isSuccess()); assertTrue(response.isEntityAvailable()); response = client.handle(new Request(Method.GET, "http://localhost:" + this.port2 + "/efgh")); assertTrue(response.getStatus().isClientError()); component.stop(); client.stop(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/component/HelloWorldRestlet.java0000664000175000017500000000320611757206352031475 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; /** * Reusable hello world Restlet. * * @author Jerome Louvel */ public class HelloWorldRestlet extends Restlet { @Override public void handle(Request request, Response response) { response.setEntity("hello, world", MediaType.TEXT_PLAIN); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/MockRestlet.java0000664000175000017500000000364711757206352026322 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; /** * Thin layer around an AbstractRestlet. Takes care about being started when it * should handle a call. * * @author Lars Heuer (heuer[at]semagia.com) Semagia */ public class MockRestlet extends Restlet { public MockRestlet(Context context) { super(context); } @Override public void handle(Request request, Response response) { super.handle(request, response); if (!super.isStarted()) { throw new IllegalStateException("Restlet was not started"); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/0000775000175000017500000000000011757206354024342 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/0000775000175000017500000000000011757206352026163 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/car/0000775000175000017500000000000011757206352026730 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/car/CarListResource.java0000664000175000017500000001215311757206352032646 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.car; import java.net.URI; import java.net.URISyntaxException; import javax.ws.rs.Encoded; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; /** * @author Stephan Koops * @see CarResource */ @Path(CarListResource.PATH) public class CarListResource { public static final String DUMMY_CAR_LIST = "[1, 2, 5]"; public static final String OFFERS = "This are test offers"; public static final String PATH = "cars"; public static final String OFFERS_PATH = "offers"; /** * Konstruktoren von Root-Resourcen werden von der JAX-RS-Laufzeitumgebung * aufgerufen. Bei mind. 1 der vorhandenen Konstruktoren mussen alle * Parameter mit @HttpContext, @HeaderParam, @MatrixParam, * @QueryParam oder @UriParam annotiert sein. Ein Konstruktor ohne * Parameter ist auch erlaubt. */ public CarListResource() { } /** * Diese Methode ist ein sub-resource-locator, weil sie nicht mit * einer Http-Methoden annotiert ist. Anfragen werden von der * zurueckgegebenen Resource behandelt. * * @param id * @return */ @Path("{id}") @Encoded public CarResource findCar(@javax.ws.rs.PathParam("id") int id) { return new CarResource(id); } /** * * @return */ @GET @Produces("text/plain") public String getCarList() { // NICE test: use URIs in response entity. return DUMMY_CAR_LIST; } /** *

* Diese Methode ist ein sub-resource-method, weil sie mit einer * Http-Methoden annotiert ist. Sie behandelt die Anfrage selber. *

*

* Alle Parameter bis auf einen von Resource-Methods mussen @ * {@link MatrixParam}, @{@link QueryParam}, @{@link UriParam}, * @{@link HttpContext} oder @{@link HeaderParam} annotiert sein. * Ein ggf. nicht annotierte Parameter bekommt die Entity ubergeben. Alle * Parameterklassen auber @{@link HttpContext} mussen Strings verstehen * konnen (Konstruktor oder static valueOf(String) mit genau einem * String-Parameter).
* Wenn @HttpContext: Klasse muss {@link UriInfo}, PrecoditionEvaluator * (inzwischen umbenannt, zu Provider?) oder {@link HttpHeaders} *

*

* Ruckgabetypen: *

    *
  • void: leerer Entity-Body
  • *
  • instanceof {@link Response}
  • * verwendet. Dafur kann bspw. der {@link Response.Builder} verwendet * werden *
  • sonst: gemappt von ? (fruher EntityProvider, Abschnitt 3.1 der Spec)
  • *
*

* * @return * * @throws WebApplicationException * Muss gefangen werden. Sie kann einen Request enthalten. */ @GET @Path(OFFERS_PATH) @Produces("text/plain") public String getOffers() throws WebApplicationException { return OFFERS; } /** * This method do so, if it adds a new car to the car list. */ @POST public Response newCar(@Context UriInfo uriInfo) { final int newId = 47; // from business logic. final URI newUri = uriInfo.getAbsolutePathBuilder().path("{id}").build( newId); return Response.created(newUri).build(); } /** * This method is available for OPTIONS-test. */ @POST @Path(OFFERS_PATH) public Response newCarOffer() { try { return Response.created(new URI("../5")).build(); } catch (URISyntaxException e) { throw new WebApplicationException(e); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/car/package-info.java0000664000175000017500000000302711757206352032121 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* some resources for a test service *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops * @see CarTest */ package org.restlet.test.jaxrs.services.car; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/car/EngineResource.java0000664000175000017500000000356111757206352032515 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.car; import javax.ws.rs.GET; import javax.ws.rs.Produces; /** * @author Stephan Koops * @see CarResource */ public class EngineResource { /** * @param carId * @return */ public static String getPlainRepr(int carId) { return "This is the engine of car with id " + carId + "."; } /** Car, the engine elongs to */ private final CarResource car; public EngineResource(CarResource car) { this.car = car; } @GET @Produces("text/plain") public String getText() { final int carId = this.car.getId(); return getPlainRepr(carId); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/car/CarResource.java0000664000175000017500000000434511757206352032016 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.car; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * This class will be returned of {@link CarListResource#findCar(int)}. * * @author Stephan Koops * @see CarListResource * @see EngineResource */ public class CarResource { /** * * @param carNumber * @return */ public static String createTextRepr(Object carNumber) { return "This is the car with id " + carNumber + "."; } private final int id; /** * * @param id */ public CarResource(int id) { this.id = id; } /** * @param id * @return */ @Path("engine") public EngineResource findEngine() { return new EngineResource(this); } /** * * @return */ public int getId() { return this.id; } /** * * @return */ @GET @Produces("text/plain") public String getText() { return createTextRepr(this.id); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/0000775000175000017500000000000011757206354030177 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ListParamService.java0000664000175000017500000000572411757206352034265 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.SortedSet; import javax.ws.rs.CookieParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.PathSegment; import org.restlet.test.jaxrs.services.tests.ListParamTest; /** * @author Stephan Koops * @see ListParamTest */ @Path("/listParams") public class ListParamService { @GET @Path("cookie") @Produces("text/plain") public String getCookie(@CookieParam("c") String c, @CookieParam("cc") List cc) { return "c=" + c + "\ncc=" + cc; } @GET @Path("header") @Produces("text/plain") public String getHeader(@HeaderParam("h") String h, @HeaderParam("hh") Set hh) { return "h=" + h + "\nhh=" + hh; } @GET @Path("matrix") @Produces("text/plain") public String getMatrix(@MatrixParam("m") String m, @MatrixParam("mm") Collection mm) { return "m=" + m + "\nmm=" + mm; } // @Path("{other}") public ListParamService getOther() { return new ListParamService(); } @GET @Path("path/{p}/{p}/{pp}/{pp}") @Produces("text/plain") public String getPath(@PathParam("p") PathSegment p, @PathParam("pp") SortedSet pp) { return "p=" + p + "\npp=" + pp; } @GET @Path("query") @Produces("text/plain") public String getQuery(@QueryParam("q") String q, @QueryParam("qq") List qq) { return "q=" + q + "\nqq=" + qq; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatrixParamTestService2.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatrixParamTestService0000664000175000017500000000563311757206354034537 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.List; import javax.ws.rs.DefaultValue; import javax.ws.rs.Encoded; import javax.ws.rs.GET; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.restlet.test.jaxrs.services.tests.MatrixParamTest2; /** * @author Stephan Koops * @see MatrixParamTest2 * @see MatrixParam * @see UriInfo */ @Path("") public class MatrixParamTestService2 { @GET @Produces(MediaType.TEXT_PLAIN) @Path("encodedWithDefault") public String encodedList( @Encoded @DefaultValue("default") @MatrixParam("m") List cc) { return cc.toString(); } @GET @Produces("text/plain") public String get(@MatrixParam("firstname") String firstname, @MatrixParam("lastname") String lastname, @Context UriInfo uriInfo) { final List pathSegents = uriInfo.getPathSegments(); final PathSegment lastPathSegm = pathSegents.get(0); final MultivaluedMap mp = lastPathSegm .getMatrixParameters(); if (mp.isEmpty()) { final ResponseBuilder rb = Response.status(Status.NOT_FOUND); rb.entity("matrix parameters are empty"); throw new WebApplicationException(rb.build()); } return firstname + " " + lastname; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PathParamTestService2.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PathParamTestService2.0000664000175000017500000000633211757206352034322 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.math.BigDecimal; import javax.ws.rs.Encoded; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.restlet.data.MediaType; import org.restlet.test.jaxrs.services.tests.PathParamTest2; /** * @author Stephan Koops * @see PathParamTest2 * @see PathParam */ @Path("pathParamTest2/") public class PathParamTestService2 { @GET @Produces("text/plain") @Path("decoded/{string}") public String decoded(@PathParam("string") String string) { return string; } @Encoded @GET @Produces("text/plain") @Path("encoded/{string}") public String encoded(@PathParam("string") String string) { return string; } @GET @Path("BigDecimal/{id}") @Produces("text/plain") public String getBigDecimal(@PathParam("id") BigDecimal id) { return String.valueOf(id); } @GET @Path("int/{id}") @Produces("text/plain") public String getInt(@PathParam("id") int id) { return String.valueOf(id); } @GET @Path("Integer/{id}") @Produces("text/plain") public String getInteger(@PathParam("id") Integer id) { return String.valueOf(id); } @GET @Path("MediaType/{id}") @Produces("text/plain") public String getMediaType(@PathParam("id") MediaType id) { return String.valueOf(id); } @GET @Path("mn{id}") @Produces("text/plain") public String getMn(@PathParam("id") int id) { return String.valueOf(id); } @GET @Path("multSegm/{string:.*}") @Produces("text/plain") public String getMultSegment(@PathParam("string") String string) { return string; } @GET @Path("abc{def}") public String getX(@PathParam("def") String def) { return def; } @GET @Path("a{bcd}ef/{12}34") public String getX2(@PathParam("bcd") String bcd, @PathParam("12") String tt) { return bcd + "\n" + tt; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PersonsResource.java0000664000175000017500000000510311757206352034200 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.net.URI; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.others.PersonList; /** * @author Stephan Koops * @ee PersonsTest */ @Path("persons") public class PersonsResource { @Context UriInfo uris; @POST @Produces( { "application/xml", "text/xml" }) public Response addPerson(Person person) { final int id = createPerson(person); final URI location = this.uris.getBaseUriBuilder().path( PersonResource.class).build(String.valueOf(id)); return Response.created(location).build(); } /** * @param person * @return */ private int createPerson(Person person) { // create person in database person.toString(); return 5; } @GET @Produces( { "application/xml", "text/xml" }) public PersonList getPersons() { final PersonList list = new PersonList(); list.add(new Person("Angela", "Merkel")); list.add(new Person("Ehud", "Olmert")); list.add(new Person("George U.", "Bush")); return list; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ExtendedUriBuilderTestResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ExtendedUriBuilderTest0000664000175000017500000000423411757206352034512 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.restlet.ext.jaxrs.ExtendedUriInfo; import org.restlet.test.jaxrs.services.tests.UriBuilderByServiceTest; /** * @author Stephan Koops * @see UriBuilderByServiceTest */ @Path("UriBuilder") public class ExtendedUriBuilderTestResource { @Context ExtendedUriInfo uriInfo; @GET @Path("absolute") @Produces( { MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public String getAbsoluteUriBuilder() { return this.uriInfo.getAbsolutePathBuilder().build().toString(); } @GET @Path("base") @Produces( { MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public String getBaseUriBuilder() { return this.uriInfo.getBaseUriBuilder().build().toString(); } // LATER test also with uri of sub resource } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/GenericTypeResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/GenericTypeResource.ja0000664000175000017500000000412711757206352034443 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.Response; import org.restlet.test.jaxrs.services.providers.GenericTypeMBW; import org.restlet.test.jaxrs.services.tests.GenericTypeTestCase; /** * @author Stephan Koops * @see GenericTypeMBW * @see GenericTypeTestCase */ @Path("GenericType") public class GenericTypeResource { @GET @Produces("text/plain") public Response getStrings() { final List strings = new ArrayList(); strings.add("abc"); strings.add("def"); final GenericEntity> entity = new GenericEntity>( strings) { }; return Response.ok(entity).build(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InjectionTestService2.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InjectionTestService2.0000664000175000017500000000555711757206352034377 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.InjectionTest; /** * @author Stephan Koops * @see InjectionTest * @see Context */ @Path("/InjectionTestService/two/{idf}") public class InjectionTestService2 { @Context private SecurityContext securityContext; @Context private UriInfo uriInfo; @Context private Request request; @Context private HttpHeaders httpHeaders; @PathParam("idf") private Integer idf; @HeaderParam("host") private String hostHost; @GET @Produces("text/plain") public Response get() { String msg = ""; if (this.securityContext == null) { msg += "\n* securityContext"; } if (this.uriInfo == null) { msg += "\n* uriInfo"; } if (this.request == null) { msg += "\n* request"; } if (this.httpHeaders == null) { msg += "\n* httpHeaders"; } if (this.idf == null) { msg += "\n* id"; } if (this.hostHost == null) { msg += "\n* host"; } if (msg.length() > 0) { return Response.serverError().entity("missing:" + msg).build(); } return Response.ok(String.valueOf(this.idf)).build(); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InheritAnnotationTestServiceInterface.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InheritAnnotationTestS0000664000175000017500000000325211757206352034542 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * Interface to test the inheritaion and non inheritation of annotations. * * @author Stephan Koops * @see InheritAnnotationTestService1 * @see InheritAnnotationTestService2 */ public interface InheritAnnotationTestServiceInterface { @GET @Produces("text/plain") @Path("getText") public Object getText(); } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ContextResolverTestResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ContextResolverTestRes0000664000175000017500000000344111757206352034602 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.tests.ContextResolverTest; /** * this test is not used yet !! * * @author Stephan Koops * @see ContextResolverTest */ @Path("workers") public class ContextResolverTestResource { /** @see ContextResolverTest#test1() */ @GET @Produces("text/html") public Person getHomeUri() { return new Person("Helmut", "Kohl"); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PathParamTestResource3.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PathParamTestResource30000664000175000017500000000316211757206352034432 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; /** * @author Stephan Koops */ @Path("supplemental/{doctype}/{entryid}") public class PathParamTestResource3 { @GET public String get(@PathParam("doctype") String doctype, @PathParam("entryid") String entryid) { return doctype+"\n"+entryid+"\n"; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PrimitiveWrapperEntityResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PrimitiveWrapperEntity0000664000175000017500000000454311757206352034634 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.tests.PrimitiveWrapperEntityTest; /** * This resource is to test, what happens, if a primitive and a primitive * wrapper is required, also if nothing is given * * @author Stephan Koops * @see PrimitiveWrapperEntityTest */ @Path("PrimitiveWrapperEntity") @Produces("text/plain") public class PrimitiveWrapperEntityResource { @PUT @Path("BooleanReturnboolean") public boolean BooleanReturnboolean(Boolean b) { if (b == null) { return false; } return b; } @PUT @Path("charReturnCharacter") public Character charReturnCharacter(char c) { return c; } @PUT @Path("integerReturnInteger") public Integer integerReturnInteger(Integer i) { return i; } @PUT @Path("intReturnInt") public int intReturnInt(int i) { return i; } @PUT @Path("byteArrayReturnByteArray") public byte[] byteArrayReturnByteArray(byte[] array) { return array; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/Issue971Resource.java0000664000175000017500000000322611757206352034104 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.others.Issue971Object; /** * @author Martin Krasser */ @Path("test") public class Issue971Resource { @GET @Path("971") @Produces("text/plain") public Issue971Object getIssue971() { return new Issue971Object("issue 971 description"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/SimpleHouse.java0000664000175000017500000000413311757206352033276 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.tests.SimpleHouseTest; /** * This class contains only data for one media type. * * @author Stephan Koops * @see SimpleHouseTest */ @Path("/ho%20use") public class SimpleHouse { /** Text of the Plain-Text-Representation. */ public static final String RERP_PLAIN_TEXT = " /\\ \n / \\ \n | | \n +--+ \n \n This is a simple text house"; @GET @Path("null") public Object getNull() { return null; } @GET @Path("nullWithMediaType") @Produces("text/plain") public Object getNullWithMediaType() { return null; } /** * * @return */ @GET @Produces("text/plain") public String getPlainText() { return RERP_PLAIN_TEXT; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/JsonTestService.java0000664000175000017500000000541711757206354034143 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.TEXT_PLAIN; import static javax.ws.rs.core.MediaType.TEXT_XML; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import org.json.JSONObject; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.tests.JsonTest; /** * @author Stephan Koops * @see JsonTest */ @Path("jsonTest") public class JsonTestService { @GET @Path("JSONObject") @Produces(APPLICATION_JSON) public JSONObject getJsonObject() throws Exception { final JSONObject jsonObject = new JSONObject(); jsonObject.put("name1", "value1"); jsonObject.put("name2", "value2"); return jsonObject; } @GET @Path("person") @Produces( { TEXT_XML, APPLICATION_XML, APPLICATION_JSON }) public Person getPerson(@QueryParam("firstname") String firstname, @QueryParam("lastname") String lastname) { return new Person(firstname, lastname); } @GET @Path("String") @Produces(APPLICATION_JSON) public String getString() { return "{name:value}"; } @POST @Path("JSONObject") @Consumes(APPLICATION_JSON) @Produces(TEXT_PLAIN) public String post(JSONObject jsonObject) throws Exception { return jsonObject.getString("name"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/Issue593Resource.java0000664000175000017500000000342311757206352034103 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.Issue593Test; /** * @author Stephan Koops * @see Issue593Test */ @Path("test") public class Issue593Resource { /** * @return {@link UriInfo#getPath()} */ @GET @Path("example") @Produces("text/plain") public String getPath(@Context UriInfo uriInfo) { return uriInfo.getPath(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/RequestService.java0000664000175000017500000001143111757206352034011 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.test.jaxrs.services.others.OPTIONS; import org.restlet.test.jaxrs.services.tests.RequestTest; /** * @author Stephan Koops * @see RequestTest * @see Request * @see CallContext */ @Path("/requestTestService") public class RequestService { public static final String GERMAN_TEXT = "Text auf deutsch"; public static final String ENGLISH_TEXT = "Text in english"; public static EntityTag getEntityTagFromDatastore() { return new EntityTag("validEntityTag"); } public static Date getLastModificationDateFromDatastore() { return new Date(1199790000000l); // 2009-01-08, 12h } @GET @Path("date") @Produces("text/plain") public Response get(@Context Request request) { final Date modificDate = getLastModificationDateFromDatastore(); final EntityTag entityTag = getEntityTagFromDatastore(); final ResponseBuilder resp = request.evaluatePreconditions(modificDate, entityTag); if (resp != null) { return resp.build(); } // Build new Response final ResponseBuilder responseBuilder = Response.status(200); responseBuilder.entity("This is the Entity from " + modificDate); responseBuilder.lastModified(modificDate); responseBuilder.tag(entityTag); return responseBuilder.build(); } @GET @Path("selectVariants") public Response getSelectVariants(@Context Request request) { // TEST VariantListBuilder final List variants = new ArrayList(); variants .add(new Variant(MediaType.TEXT_HTML_TYPE, Locale.ENGLISH, null)); variants.add(new Variant(MediaType.TEXT_PLAIN_TYPE, Locale.ENGLISH, null)); variants .add(new Variant(MediaType.TEXT_HTML_TYPE, Locale.GERMAN, null)); variants .add(new Variant(MediaType.TEXT_PLAIN_TYPE, Locale.GERMAN, null)); final Variant variant = request.selectVariant(variants); if (variant == null) { return Response.notAcceptable(variants).build(); } String entity; if (variant.getLanguage().equals("en")) { entity = ENGLISH_TEXT; } else { entity = GERMAN_TEXT; } return Response.ok(entity).variant(variant).build(); } @OPTIONS public Response options() { return Response.ok().header("Allow", "ABC, DEF").header("Allow", "GHI") .build(); } @PUT @Path("date") public Response put(@Context Request request) { final Date modificDate = getLastModificationDateFromDatastore(); final EntityTag entityTag = getEntityTagFromDatastore(); final ResponseBuilder resp = request.evaluatePreconditions(modificDate, entityTag); if (resp != null) { return resp.build(); } // Build new Response final ResponseBuilder responseBuilder = Response.status(200); return responseBuilder.build(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InheritAnnotationTestService2.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InheritAnnotationTestS0000664000175000017500000000525611757206352034550 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.tests.InheritAnnotationTest; /** * @author Stephan Koops * @see InheritAnnotationTest * @see InheritAnnotationTestServiceInterface */ @Path("1234") public class InheritAnnotationTestService2 implements InheritAnnotationTestServiceInterface { public class GetTextResource { @GET @Produces("text/plain") public String get() { return RETURN_STRING; } } public class SubClassResource extends GetTextResource { @Override public String get() { return RETURN_STRING_SUB; } @Path("sub") public SubClassResource2 getSub() { return new SubClassResource2(); } } public class SubClassResource2 { @GET @Produces("text/plain") public String get() { return RETURN_STRING_SUB2; } } public static final String RETURN_STRING = "fromGetTextResource"; public static final String RETURN_STRING_SUB = "fromGetTextExtResource"; public static final String RETURN_STRING_SUB2 = "fromGetTextExt2Resource"; @Path("getSubClassText") public SubClassResource getSubClass() { return new SubClassResource(); } @Path("getText") public GetTextResource getText() { return new GetTextResource(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/HeadOptionsTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/HeadOptionsTestService0000664000175000017500000000511011757206352034513 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.others.OPTIONS; import org.restlet.test.jaxrs.services.tests.HeadOptionsTest; /** * This class contains only data for one media type * * @author Stephan Koops * @see HeadOptionsTest * @see HEAD * @see OPTIONS */ @Path("/headOptionsTest") public class HeadOptionsTestService { @GET public void get() { // do nothing } @GET @Path("headTest1") @Produces("text/html") public String getTest1() { return "4711"; } @GET @Path("headTest1") @Produces("text/plain") public String getTest1a() { return "4711"; } @GET @Path("headTest2") @Produces("text/html") public String getTest2() { return "4711"; } @GET @Path("headTest2") @Produces("text/plain") public String getTest2plain() { return "4711"; } @HEAD @Path("headTest1") @Produces("text/html") public String headTest1() { return null; } @HEAD @Path("headTest2") @Produces("text/html") public String headTest2() { return "4711"; } @POST @Path("headTest1") public void post() { // do nothing yet } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/HttpHeaderTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/HttpHeaderTestService.0000664000175000017500000001253411757206352034414 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.List; import java.util.Map; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.restlet.test.jaxrs.services.tests.HttpHeaderTest; /** * Service to test, if the headers are read correct. * * @author Stephan Koops * @see HttpHeaderTest */ @Path("/skjflsfh") public class HttpHeaderTestService { public static final String TEST_HEADER_NAME = "testHeader"; @GET @Path("accMediaTypes") @Produces("text/plain") public String getAccMediaTypes(@Context HttpHeaders headers) { final List mediaTypes = headers.getAcceptableMediaTypes(); return mediaTypes.toString(); } @GET @Path("cookies/{cookieName}") @Produces("text/plain") public String getCookies(@Context HttpHeaders headers, @PathParam("cookieName") String cookieName) { final Map cookies = headers.getCookies(); try { cookies.put("notAllowed", new Cookie("notAllowed", "value")); throw new WebApplicationException(Response.serverError().entity( "could add cookie notAllowed").build()); } catch (UnsupportedOperationException uoe) { // not allowed } try { cookies.put("xyz", new Cookie("notAllowed", "value")); throw new WebApplicationException(Response.serverError().entity( "could add xyz").build()); } catch (UnsupportedOperationException uoe) { // not allowed } final Cookie cookie = cookies.get(cookieName); if (cookie == null) { return null; } return cookie.toString(); } @GET @Path("header/{headername}") @Produces("text/plain") public String getHeader(@Context HttpHeaders headers, @PathParam("headername") String headername) { final MultivaluedMap requestHeaders = headers .getRequestHeaders(); final String headerValue = requestHeaders.getFirst(headername); return headerValue; } /** * @param hostLower * @param hostUpper * @param hostMixed * @return returns internal server error if the host variables does not have * all the same value. */ @GET @Path("header2") @Produces("text/plain") public Object getHeader2(@HeaderParam("host") String hostLower, @HeaderParam("HOST") String hostUpper, @HeaderParam("Host") String hostMixed) { if (hostLower.equals(hostUpper) && hostLower.equals(hostMixed)) { return hostMixed; } final String hosts = "mixed: " + hostMixed + "\nupper: " + hostUpper + "\n lower: " + hostLower; return Response.serverError().entity(hosts).build(); } @GET @Path("HeaderParam") @Produces("text/plain") public String getHeaderParam( @HeaderParam(TEST_HEADER_NAME) String testHeaderValue) { return testHeaderValue; } @GET @Path("headerWithDefault") @Produces("text/plain") public String getHeaderWithDefault( @HeaderParam(TEST_HEADER_NAME) @DefaultValue("default") String testHeader) { return testHeader; } @POST @Path("language") @Produces( { "text/plain", "text/html" }) public String getLanguage(@Context HttpHeaders headers) { return headers.getLanguage().toString(); } @GET @Produces("text/plain") public String getPlain() { return "media type text/plain is supported\n"; } @GET @Produces( { "text/xml", MediaType.APPLICATION_XML }) public String getXML() { return "the media types text/xml and application/xml are supported\n"; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MessageBodyWriterTestResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MessageBodyWriterTestR0000664000175000017500000000366311757206352034511 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.providers.AppCrazyPersonProvider; import org.restlet.test.jaxrs.services.tests.MessageBodyWritersTest; /** * @author Stephan Koops * @see MessageBodyWritersTest * @see AppCrazyPersonProvider */ @Path("mbw") public class MessageBodyWriterTestResource { @GET @Produces("application/crazy-person") public Response get() { final Person person = new Person("Angela", "Merkel"); return Response.ok(person).header("h1", "h1v").build(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ContextsTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ContextsTestService.ja0000664000175000017500000000655211757206352034511 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Providers; import org.restlet.test.jaxrs.services.tests.ContextsTest; /** * @author Stephan Koops * @see ContextsTest */ @Path("contextTest") public class ContextsTestService { @Context Providers providers; void setProviders(Providers providers) { this.contextResolver = providers.getContextResolver(Integer.class, MediaType.WILDCARD_TYPE); } ContextResolver contextResolver; @Context UriInfo uriInfo; @GET @Produces("text/plain") @Path("fields") public String fieldsAvailable() { final StringBuilder stb = new StringBuilder(); if (this.providers != null) { stb.append("providers\n"); } if (this.contextResolver != null) { stb.append("contextResolver\n"); } if (this.uriInfo != null) { stb.append("uriInfo\n"); } return stb.toString(); } @GET @Produces("text/plain") @Path("lastPathSegm") public String getPathSegm(@Context PathSegment lastPathSegment) { final StringBuilder stb = new StringBuilder(); for (String key : lastPathSegment.getMatrixParameters().keySet()) { stb.append(key + " : " + lastPathSegment.getMatrixParameters().get(key) + "\n"); } return stb.toString(); } @GET @Produces("text/plain") @Path("params") public String getResources(@Context UriInfo uriInfo, @Context Providers providers) { final StringBuilder stb = new StringBuilder(); if (providers != null) { stb.append("providers\n"); } if (contextResolver != null) { stb.append("contextResolver\n"); } if (uriInfo != null) { stb.append("uriInfo\n"); } return stb.toString(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/AppPlusXmlResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/AppPlusXmlResource.jav0000664000175000017500000000340111757206354034454 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.TEXT_XML; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.others.Person; /** * @author Stephan Koops */ @Path("appPlusXml") public class AppPlusXmlResource { @GET @Produces( { "application/Person+xml", APPLICATION_XML, TEXT_XML }) public Person getPerson() { return new Person("Angela", "Merkel"); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ProviderTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ProviderTestService.ja0000664000175000017500000002511611757206352034471 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import javax.mail.BodyPart; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.MatrixParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import org.restlet.data.Form; import org.restlet.engine.io.IoUtils; import org.restlet.ext.jaxrs.internal.core.MultivaluedMapImpl; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.tests.ProviderTest; import org.restlet.test.jaxrs.util.TestUtils; import org.xml.sax.InputSource; /** * @author Stephan Koops * @see ProviderTest * @see JsonTestService */ @SuppressWarnings("all") @Path("/providerTest") public class ProviderTestService { /** * */ public static final String STRING2 = "Rom" + '\u00E4' + "n"; // avoid UTF-8 // bugs public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final int CS_LAST_CHAR = 126; /** * @return */ public static String createCS() { final StringBuilder stb = new StringBuilder(); for (char c = 32; c <= CS_LAST_CHAR; c++) { stb.append(c); } return stb.toString(); } @GET @Path("BufferedReader") @Produces("application/octet-stream") public BufferedReader bufferedReaderGet() { return new BufferedReader(readerGet(), IoUtils.getBufferSize()); } @POST @Path("BufferedReader") @Produces("text/plain") public String bufferedReaderPost(BufferedReader reader) throws IOException { final StringBuilder stb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stb.append(line); stb.append('\n'); } stb.deleteCharAt(stb.length() - 1); return stb.toString(); } @GET @Path("byteArray") @Produces("application/octet-stream") public byte[] byteArrayGet() { return ALPHABET.getBytes(); } @POST @Path("byteArray") @Produces("text/plain") public String byteArrayPost(byte[] byteArray) { return new String(byteArray); } /** * Returns a {@link CharSequence}, which class is equals to no default. * * @return a {@link CharSequence}, which class is equals to no default. */ @GET @Path("CharSequence") @Produces("text/plain") public CharSequence charSequenceGet() { return new CharSequence() { public char charAt(int index) { return (char) (index + 32); } public int length() { return CS_LAST_CHAR - 32 + 1; } public CharSequence subSequence(int start, int end) { return toString().subSequence(start, end); } @Override public String toString() { return createCS(); } }; } @POST @Path("CharSequence") @Produces("text/plain") @Consumes("text/plain") public String charSequencePost(CharSequence form) { return form.toString(); } @GET @Path("file") @Produces("application/octet-stream") public File fileGet() { return new File(this.getClass().getResource("alphabet.txt").getPath()); } @POST @Path("file") @Consumes("application/octet-stream") @Produces("text/plain") public String filePost(File file) throws IOException { final InputStream inputStream = new FileInputStream(file); return inputStreamPost(inputStream); } @GET @Path("form") @Produces("application/x-www-form-urlencoded") public Form formGet() { final Form form = new Form(); form.add("firstname", "Angela"); form.add("lastname", "Merkel"); return form; } @POST @Path("form") @Produces("text/plain") @Consumes("application/x-www-form-urlencoded") public String formPost(Form form) { return form.toString(); } @GET @Path("InputStream") @Produces("application/octet-stream") public InputStream inputStreamGet() { return new ByteArrayInputStream(ALPHABET.getBytes()); } @POST @Path("InputStream") @Produces("text/plain") public String inputStreamPost(InputStream inputStream) throws IOException { final StringBuilder stb = new StringBuilder(); int b; while ((b = inputStream.read()) >= 0) { stb.append((char) b); } return stb.toString(); } @GET @Path("jaxbElement") @Produces("text/xml") public JAXBElement jaxbElementGet() { return new JAXBElement(new QName("qName"), Person.class, jaxbGet()); } @GET @Path("jaxb") @Produces("text/xml") public Person jaxbGet() { return new Person("Angela", "Merkel"); } @POST @Path("jaxbElement") @Consumes( { "text/xml", "application/xml" }) @Produces("text/plain") public String jaxbPost(JAXBElement person) { if (person == null) { throw new WebApplicationException(Response.serverError().entity( "the JAXBElement is null").build()); } if (person.getValue() == null) { return null; } return person.getValue().toString(); } @POST @Path("jaxbElement/rootElement") @Consumes( { "text/xml", "application/xml" }) @Produces("text/plain") public String jaxbPostRootElement(JAXBElement person) { if (person == null) { throw new WebApplicationException(Response.serverError().entity( "the JAXBElement is null").build()); } if (person.getValue() == null) { return null; } return person.getName().toString(); } @POST @Path("jaxb") @Consumes( { "text/xml", "application/xml" }) @Produces("text/plain") public String jaxbPost(Person person) { return person.toString(); } @GET @Path("MultivaluedMap") @Produces("application/x-www-form-urlencoded") public MultivaluedMap mMapGet() { final MultivaluedMap mmap = new MultivaluedMapImpl(); mmap.add("firstname", "Angela"); mmap.add("lastname", "Merkel"); return mmap; } @POST @Path("MultivaluedMap") @Consumes("application/x-www-form-urlencoded") @Produces("text/plain") public String mMapPost(MultivaluedMap mmap) { return Converter.toForm(mmap).toString(); } @POST @Path("multipart/form-data") @Consumes("multipart/form-data") public Object multipartPost(@QueryParam("attrNo") int attrNo, Multipart multipart) throws MessagingException, IOException { final BodyPart bodyPart = multipart.getBodyPart(attrNo); return bodyPart.getInputStream(); } @GET @Path("Reader") @Produces("application/octet-stream") public Reader readerGet() { return new StringReader(ALPHABET); } @POST @Path("Reader") @Produces("text/plain") public String readerPost(Reader reader) throws IOException { final StringBuilder stb = new StringBuilder(); int c; while ((c = reader.read()) >= 0) { stb.append((char) c); } return stb.toString(); } @GET @Path("StringBuilder") @Produces("text/plain") public StringBuilder stringBuilderGet() { return new StringBuilder(ALPHABET); } @GET @Path("String") @Produces("text/plain") public String stringGet() { return ALPHABET; } @GET @Path("String2") @Produces("text/plain") public String string2Get() { return STRING2; } @POST @Path("String") @Produces("text/plain") @Consumes("text/plain") public String stringPost(String entity) { return entity; } @GET @Path("String/substring") @Produces("text/plain") public String subStringGet(@MatrixParam("start") int start, @MatrixParam("end") int end) { if (end >= ALPHABET.length()) { return ALPHABET.substring(start); } return ALPHABET.substring(start, end); } @GET @Path("source") @Produces("text/xml") public Source xsltGet() { return new StreamSource(new ByteArrayInputStream("".getBytes())); } @POST @Path("source") @Consumes("text/xml") @Produces("text/plain") public byte[] xsltPost(Source source) throws IOException { final InputSource inputSource = SAXSource.sourceToInputSource(source); return TestUtils.getByteArray(inputSource.getByteStream()); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ResponseBuilderService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ResponseBuilderService0000664000175000017500000000635411757206352034556 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.test.jaxrs.util.TestUtils; /** * Test what happens when two methods should be use for the same request. * * @author Stephan Koops * @see ResponseBuilder * @see Response.ResponseBuilder */ @Path("/responseBuilder") public class ResponseBuilderService { @DELETE public Response delete() { return Response.ok().build(); } @GET @Path("1") public Response get1() { final List variants = new ArrayList(); variants.add(new Variant(TestUtils.createMediaType("text", "sjk"), Locale.ENGLISH, "encoding")); variants.add(new Variant(TestUtils.createMediaType("text", "sfgs"), Locale.ENGLISH, "encoding2")); variants.add(new Variant(TestUtils.createMediaType("text", "ydgdsfg"), Locale.ENGLISH, "encoding")); variants.add(new Variant(TestUtils.createMediaType("text", "sjk"), Locale.ENGLISH, "encoding2")); return Response.notAcceptable(variants).build(); } @GET @Path("2") public Response get2() { final List variants = new ArrayList(); variants.add(new Variant(TestUtils.createMediaType("text", "sjk"), Locale.ENGLISH, "encoding")); variants.add(new Variant(TestUtils.createMediaType("text", "sjk", "charset", "enc"), Locale.ENGLISH, "encoding")); variants.add(new Variant(TestUtils.createMediaType("text", "sjk", "charset", "skl"), Locale.ENGLISH, "encoding")); variants.add(new Variant(TestUtils.createMediaType("text", "sjk"), Locale.GERMAN, "encoding")); return Response.notAcceptable(variants).build(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/RecursiveTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/RecursiveTestService.j0000664000175000017500000000424311757206354034505 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.tests.RecursiveTest; /** * Test, if there are problems if a resource is a child of itself. * * @author Stephan Koops * @see RecursiveTest */ @Path("/recursiveTest") @Produces("text/plain") public class RecursiveTestService { private final RecursiveTestService parent; public RecursiveTestService() { this.parent = null; } public RecursiveTestService(RecursiveTestService parent) { this.parent = parent; } public int depth() { if (this.parent == null) { return 0; } return this.parent.depth() + 1; } @GET public String get() { return String.valueOf(depth()); } @Path("a") public RecursiveTestService getSubResource2() { return new RecursiveTestService(this); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatrixParamTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatrixParamTestService0000664000175000017500000001254011757206352034530 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.List; import javax.ws.rs.DefaultValue; import javax.ws.rs.Encoded; import javax.ws.rs.GET; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.MatrixParamTest; import org.restlet.test.jaxrs.util.TestUtils; /** * @author Stephan Koops * @see MatrixParamTest * @see MatrixParam */ @Path("matrixParamTest") public class MatrixParamTestService { private String encoded; private String decoded; @GET @Produces("text/plain") @Path("checkUnmodifiable") public Object checkUnmodifiable(@MatrixParam("mp") List mps) { try { mps.clear(); throw new WebApplicationException(Response.serverError().entity( "the List must be unmodifiable").build()); } catch (UnsupportedOperationException use) { return null; } } @GET @Produces("text/plain") @Path("encoded") @Encoded public String encoded(@MatrixParam("firstname") String firstname, @MatrixParam("lastname") String lastname) { return firstname + " " + lastname; } @GET @Produces("text/plain") public String get(@MatrixParam("firstname") String firstname, @MatrixParam("lastname") String lastname) { return firstname + " " + lastname; } @GET @Produces("text/plain") @Path("a") public String getA(@MatrixParam("firstname") String firstname, @MatrixParam("lastname") String lastname) { return firstname + " " + lastname; } @GET @Produces("text/plain") @Path("allNames") public String getAllNames(@MatrixParam("name") List name) { return name.toString(); } @GET @Produces("text/plain") @Path("b") public String getB(@Context UriInfo uriInfo) { final PathSegment pSeg = TestUtils.getLastElement(uriInfo .getPathSegments()); final String vorname = pSeg.getMatrixParameters().getFirst("firstname"); final String nachname = pSeg.getMatrixParameters().getFirst("lastname"); return vorname + " " + nachname; } @GET @Produces("text/plain") @Path("one") public String getOne(@MatrixParam("name") String name) { if (name == null) { return "[null]"; } if (name.equals("")) { return "[empty]"; } return name; } @GET @Produces("text/plain") @Path("setterDecoded") public String getSetterDecoded() { return this.decoded; } @GET @Produces("text/plain") @Path("setterEncoded") public String getSetterEncoded() { return this.encoded; } @Path("sub") public MatrixParamTestService getSub() { return new MatrixParamTestService(); } @MatrixParam("decoded") public void setDecoded(String decoded) { this.decoded = decoded; } @Encoded @MatrixParam("encoded") public void setEncoded(String encoded) { this.encoded = encoded; } @GET @Produces("text/plain") @Path("withDefault") @Encoded public String withDefault( @MatrixParam("mp") @DefaultValue("default") String mp) { return withoutDefault(mp); } @GET @Produces("text/plain") @Path("withoutDefault") @Encoded public String withoutDefault(@MatrixParam("mp") String mp) { if (mp == null) { return "[null]"; } if (mp.equals("")) { return "[empty]"; } return mp; } @GET @Produces("text/plain") @Path("semicolon;mpA=") public Response withSemicolon(@MatrixParam("mpA") String mpA, @MatrixParam("mpB") String mpB) { final String entity = "this method must not be called\nmpA param is " + mpA + "\nmpB param is " + mpB; return Response.serverError().entity(entity).build(); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalThingsTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalThingsTestServi0000664000175000017500000000425111757206352034521 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.restlet.test.jaxrs.services.tests.IllegalThingsTest; /** * This class contains only data for one media type * * @author Stephan Koops * @see IllegalThingsTest */ @Path("/illegalThingsInternal") public class IllegalThingsTestService { @GET @Path("package") String getPackageVisible() { return "this method is package visible. Is there a warning?"; } /** * This sub resource locator returns null; that is not allowed * * @return */ @Path("nullSubResource") public Object getPlainText() { return null; } @GET @Path("private") String getPrivateVisible() { return "this method is private visible. Is there a warning?"; } @GET @Path("protected") protected String getProtected() { return "this method is protected. Is there a warning?"; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/RepresentationTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/RepresentationTestServ0000664000175000017500000000704611757206352034631 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.io.IOException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.restlet.engine.application.DecodeRepresentation; import org.restlet.ext.jaxb.JaxbRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.tests.RepresentationTest; /** * This tests ensures, that it is also working with a Restlet * {@link Representation} and subclasses. * * @author Stephan Koops * @see RepresentationTest * @see Representation */ @Path("representationTest") public class RepresentationTestService { /**@return*/ @GET @Path("repr") @Produces("text/plain") public Representation get() { return getString(); } /**@return*/ @GET @Path("reprString") @Produces("text/plain") public StringRepresentation getString() { return new StringRepresentation("jgkghkg"); } /**@return * @param representation * @throws IOException */ @POST @Path("repr") public Response post(Representation representation) throws IOException { final String type = representation.getMediaType().toString(); final String entity = representation.getText(); return Response.ok(entity).type(type).build(); } /**@return * @param representation * @throws IOException */ @POST @Path("reprDecode") public Response postDecode(DecodeRepresentation representation) throws IOException { final String type = representation.getMediaType().toString(); final String entity = representation.getText(); return Response.ok(entity).type(type).build(); } /**@return * @param personRepr * @throws IOException */ @POST @Path("jaxb") @Consumes({MediaType.APPLICATION_XML, MediaType.TEXT_XML}) public String postJaxb(JaxbRepresentation personRepr) throws IOException { if (personRepr == null) { return null; } personRepr.getObject(); return personRepr.getContextPath(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MethodAheadLocatorTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MethodAheadLocatorTest0000664000175000017500000000446211757206352034455 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.tests.MethodAheadLocatorTest; /** * This service is used to test, if sub resourcemethods are preferd to sub * resource locators. It test also with methods ordered both directions (first * method, than locator; also vice versa). * * @author Stephan Koops * @see MethodAheadLocatorTest */ @Path("/methodsAheadLocatorsTest") public class MethodAheadLocatorTestService { class SubResource { @GET @Produces("text/plain") public String get() { return "locator"; } } @GET @Path("p1") @Produces("text/plain") public String get1() { return "method"; // do nothing } @GET @Path("p2") @Produces("text/plain") public String get2() { return "method"; // do nothing } @Path("p1") public String locator1() { return null; } @Path("p2") public String locator2() { return null; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/package-info.java0000664000175000017500000000312211757206352033362 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Resources to test. You find the test cases in package * {@link org.restlet.test.jaxrs.services.tests}. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops */ package org.restlet.test.jaxrs.services.resources; ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InjectionTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InjectionTestService.j0000664000175000017500000000574511757206354034470 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.InjectionTest; /** * @author Stephan Koops * @see InjectionTest * @see Context */ @Path("/InjectionTestService") public class InjectionTestService { @Context private SecurityContext securityContext; @Context private UriInfo uriInfo; @Context private Request request; private HttpHeaders httpHeaders; @HeaderParam("host") private String host; private String qp1; @GET @Produces("text/plain") public Response get() { String msg = ""; if (this.securityContext == null) { msg += "\n* securityContext"; } if (this.uriInfo == null) { msg += "\n* uriInfo"; } if (this.request == null) { msg += "\n* request"; } if (this.httpHeaders == null) { msg += "\n* httpHeaders"; } if (this.host == null) { msg += "\n* host"; } if (this.qp1 == null) { msg += "\n* qp1"; } if (msg.length() > 0) { return Response.serverError().entity("missing:" + msg).build(); } return Response.ok("ok").build(); } @Context void setHeaders(HttpHeaders httpHeaders) { this.httpHeaders = httpHeaders; } @QueryParam("qp1") void setQp1(String qp1) { this.qp1 = qp1; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/QueryParamTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/QueryParamTestService.0000664000175000017500000001261411757206352034451 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.Arrays; import java.util.List; import javax.ws.rs.DefaultValue; import javax.ws.rs.Encoded; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.QueryParamTest; /** * @author Stephan Koops * @see QueryParamTest * @see QueryParam */ @Path("queryParamTest") public class QueryParamTestService { @QueryParam("decoded") private String decoded; @Encoded @QueryParam("encoded") private String encoded; @GET @Produces("text/plain") @Path("checkUnmodifiable") public Object checkUnmodifiable(@QueryParam("a") List as) { try { as.clear(); throw new WebApplicationException(Response.serverError().entity( "the List must be unmodifiable").build()); } catch (UnsupportedOperationException uoe) { return null; } } @GET @Produces("text/plain") @Path("encodedA") @Encoded public String encodedA(@QueryParam("firstname") String firstname, @QueryParam("lastname") String lastname) { return firstname + " " + lastname; } @GET @Produces("text/plain") @Path("a") public String getA(@QueryParam("firstname") String firstname, @QueryParam("lastname") String lastname) { return firstname + " " + lastname; } @GET @Produces("text/plain") @Path("array") public String getArrayQp(@QueryParam("qp") String[] qp) { return Arrays.toString(qp); } @GET @Produces("text/plain") @Path("arrayWithDefault") public String getArrayQpDef( @QueryParam("qp") @DefaultValue("qv") String[] qp) { return Arrays.toString(qp); } @GET @Produces("text/plain") @Path("decoded") public String getFieldDecoded() { return this.decoded; } @GET @Produces("text/plain") @Path("encoded") public String getFieldEncoded() { return this.encoded; } @GET @Produces(MediaType.TEXT_PLAIN) @Path("int") public String getInt(@QueryParam("n1") int n1, @QueryParam("n2") @DefaultValue("xx") int n2, @QueryParam("n3") @DefaultValue("99") int n3) { return n1 + " " + n2 + " " + n3; } @GET @Produces(MediaType.TEXT_PLAIN) @Path("Integer") public String getInteger(@QueryParam("n1") Integer n1, @QueryParam("n2") @DefaultValue("xx") Integer n2, @QueryParam("n3") @DefaultValue("99") Integer n3) { return n1 + " " + n2 + " " + n3; } @GET @Produces("text/plain") @Path("list") public String getListQp(@QueryParam("qp") List qp) { return qp.toString(); } @GET @Produces("text/plain") @Path("listWithDefault") public String getListQpDef( @QueryParam("qp") @DefaultValue("qv") List qp) { return qp.toString(); } @GET @Produces("text/plain") @Path("one") public String getOne(@QueryParam("name") String name) { if (name == null) { return "[null]"; } if (name.equals("")) { return "[empty]"; } return name; } @GET @Produces("text/plain") @Path("qpDecoded") public String getQueryParamsDecoded(@Context UriInfo uriInfo) { final String firstname = uriInfo.getQueryParameters().getFirst( "firstname"); final String lastname = uriInfo.getQueryParameters().getFirst( "lastname"); return firstname + " " + lastname; } @GET @Produces("text/plain") @Path("qpEncoded") public String getQueryParamsEncoded(@Context UriInfo uriInfo) { final String firstn = uriInfo.getQueryParameters(false).getFirst( "firstname"); final String lastn = uriInfo.getQueryParameters(false).getFirst( "lastname"); return firstn + " " + lastn; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/SimpleResource.java0000664000175000017500000000340011757206354034000 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.tests.ThrowWebAppExcProviderTest; /** * @author Stephan Koops * @see ThrowWebAppExcProviderTest */ @Path("simple") public class SimpleResource { @GET @Produces("text/plain") public String get() { return "fxgsgdg"; } @POST @Produces("text/plain") public String post(String entity) { return entity; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/SimpleTrain.java0000664000175000017500000001036511757206352033274 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.SimpleTrainTest; /** * One of the first test services. * * @author Stephan Koops * @see SimpleTrainTest */ @Path(SimpleTrain.PATH) public class SimpleTrain { /** * The path is here available to check it from the tests. It is not required * for JAX-RS */ public static final String PATH = "/train"; public static boolean checkForValidConstructor = true; /** Text der ausgegebenen Plain-Text-Representation. */ public static final String RERP_PLAIN_TEXT = "This is a simple text train"; /** Text der ausgegebenen HTML-Text-Representation. */ public static final String RERP_HTML_TEXT = "This is a simple html train"; public SimpleTrain() { if (checkForValidConstructor) { throw new RuntimeException( "This Constructor is not allowed, because another constructors has more elements"); } } public SimpleTrain(Integer x) { "".equals(x); if (checkForValidConstructor) { throw new RuntimeException( "This Constructor is not allowed, because the paramters are not correct annotated"); } } public SimpleTrain(@HeaderParam("p") String p) { "".equals(p); // this is a valid constructor } public SimpleTrain(String x, @HeaderParam("p") String p) { "".equals(p); "".equals(x); if (checkForValidConstructor) { throw new RuntimeException( "This Constructor is not allowed, because one of the parameters are not correct annotated"); } } /** * * @return */ @GET @Produces("text/html") public String getHtmlText() { return RERP_HTML_TEXT; } /** * * @return */ @GET @Produces("text/plain") public String getPlainText() { return RERP_PLAIN_TEXT; } @GET @Path("decode/{string}") @Produces("text/plain") public String getTemplParamDecoded(@Context UriInfo uriInfo) { try { uriInfo.getPathParameters(true).add("jkghjk", "khlokh"); return "The Template Parameter MultivaluedMap must be unmodifiable."; } catch (UnsupportedOperationException e) { // ok } return uriInfo.getPathParameters(true).getFirst("string"); } @GET @Path("encode/{string}") @Produces("text/plain") public String getTemplParamEncoded(@Context UriInfo uriInfo) { try { uriInfo.getPathParameters(false).add("jkghjk", "khlokh"); return "The Template Parameter MultivaluedMap must be unmodifiable."; } catch (UnsupportedOperationException e) { // ok } return uriInfo.getPathParameters(false).getFirst("string"); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ThrowExceptionResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ThrowExceptionResource0000664000175000017500000000446611757206352034624 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.io.IOException; import java.sql.SQLException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import org.restlet.test.jaxrs.services.tests.ThrowExceptionTest; /** * @author Stephan Koops * @see ThrowExceptionTest */ @Path("throwExc") public class ThrowExceptionResource { public static final int WEB_APP_EXC_STATUS = 583; @GET @Path("IOException") public String getIoe() throws IOException { throw new IOException("This exception is planned for testing !"); } @GET @Path("sqlExc") public Object getSqlExc() throws SQLException { throw new SQLException(); } @GET @Path("WebAppExc") public String getWebAppExc() throws WebApplicationException { throw new WebApplicationException(WEB_APP_EXC_STATUS); } @GET @Path("WebAppExcNullStatus") public String getWebAppExcNullStatus() throws WebApplicationException { throw new WebApplicationException((Response) null); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/CookieParamTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/CookieParamTestService0000664000175000017500000000556511757206352034506 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.Set; import java.util.SortedSet; import javax.ws.rs.CookieParam; import javax.ws.rs.DefaultValue; import javax.ws.rs.Encoded; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import org.restlet.test.jaxrs.services.tests.CookieParamTest; /** * @author Stephan Koops * @see CookieParamTest * @see CookieParam */ @Path("cookieParamTest") public class CookieParamTestService { @GET @Produces(MediaType.TEXT_PLAIN) @Path("array") public String array(@CookieParam("c") Cookie[] cc) { String result = "["; for (final Cookie c : cc) { result += c.getValue() + ", "; } return result.substring(0, result.length() - 2) + "]"; } @GET @Produces("text/plain") public String get(@CookieParam("c") String cookieValue) { return cookieValue; } @GET @Produces(MediaType.TEXT_PLAIN) @Path("Set") public String set(@CookieParam("c") Set cc) { String result = "{"; for (final Cookie c : cc) { result += c.getValue() + ", "; } return result.substring(0, result.length() - 2) + "}"; } @GET @Produces(MediaType.TEXT_PLAIN) @Path("SortedSet") public String sortedSet(@CookieParam("c") SortedSet cc) { return cc.toString(); } @GET @Produces("text/plain") @Path("withDefault") @Encoded public String withDefault( @CookieParam("c") @DefaultValue("default") String cookieValue) { return cookieValue; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/DeterminingMediaTypeTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/DeterminingMediaTypeTe0000664000175000017500000000352611757206352034466 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.restlet.test.jaxrs.services.tests.DeterminingMediaTypeTest; /** * @author Stephan Koops * @see DeterminingMediaTypeTest */ @Path("/providertest") public class DeterminingMediaTypeTestService { @GET @Path("htmlPlainGif") @Produces( { "text/html", "text/plain", "image/gif" }) public byte[] getHtmlPlainGif() { return "gkjlgk".getBytes(); } @GET @Path("textStar") @Produces("text/*") public String getTextStar() { return "isfhl"; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/OwnProviderTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/OwnProviderTestService0000664000175000017500000000370011757206352034557 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.providers.TextCrazyPersonProvider; import org.restlet.test.jaxrs.services.tests.OwnProviderTest; /** * @author Stephan Koops * @see TextCrazyPersonProvider * @see OwnProviderTest */ @Path("ownProviderTest") public class OwnProviderTestService { @GET @Produces( { "text/crazy-person", "application/crazy-person" }) public Response get() { final Person person = new Person("abc", "def"); return Response.ok(person).header("h1", "h1v").build(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PersonResource.java0000664000175000017500000000326311757206354034024 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.tests.PersonsTest; /** * @author Stephan Koops * @see PersonsTest */ @Path("persons/{id}") public class PersonResource { @GET public Person get(@PathParam("id") int id) { return new Person("firstname" + id, "lastname"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/FormTestResource.java0000664000175000017500000001246711757206352034325 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.TreeSet; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.UriInfo; /** * @author Stephan Koops * @see org.restlet.test.jaxrs.services.tests.MatchedTest * @see UriInfo#getMatchedResources() * @see UriInfo#getMatchedURIs() */ @Path("formTest") public class FormTestResource { @Path("formOnly") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public Object formOnly(final MultivaluedMap form) { return new StreamingOutput() { public void write(OutputStream out) throws IOException { for (final String key : new TreeSet(form.keySet())) { for (final String value : form.get(key)) { out.write(key.getBytes()); out.write(" -> ".getBytes()); out.write(value.getBytes()); out.write('\n'); } } } }; } @Path("paramOnly") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public Object paramOnly(@FormParam("a") String a, @FormParam("c") String c) { String result = "a -> " + a + "\n"; if (c != null) { result += "c -> " + c + "\n"; } return result; } @Path("formAndParam") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public Object formAndParam(final MultivaluedMap form, @FormParam("a") final String a) { return new StreamingOutput() { public void write(OutputStream out) throws IOException { out.write("a -> ".getBytes()); out.write(a.getBytes()); out.write('\n'); for (final String key : new TreeSet(form.keySet())) { if (!key.equals("a")) { for (final String value : form.get(key)) { out.write(key.getBytes()); out.write(" -> ".getBytes()); out.write(value.getBytes()); out.write('\n'); } } } } }; } @Path("paramAndForm") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public Object paramAndForm(@FormParam("a") final String a, final MultivaluedMap form) { return new StreamingOutput() { public void write(OutputStream out) throws IOException { out.write("a -> ".getBytes()); out.write(a.getBytes()); out.write('\n'); for (final String key : new TreeSet(form.keySet())) { if (!key.equals("a")) { for (final String value : form.get(key)) { out.write(key.getBytes()); out.write(" -> ".getBytes()); out.write(value.getBytes()); out.write('\n'); } } } } }; } @Path("checkUnmodifiable") @POST @Produces("text/plain") public Object checkUnmodifiable(@FormParam("a") List as) { try { as.clear(); throw new WebApplicationException(Response.serverError().entity( "the List must be unmodifiable").build()); } catch (UnsupportedOperationException uoe) { return null; } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/alphabet.txt0000664000175000017500000000003211757206354032513 0ustar jamespagejamespageABCDEFGHIJKLMNOPQRSTUVWXYZ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatchedUriTestResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatchedUriTestResource0000664000175000017500000000473111757206352034522 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; /** * @author Stephan Koops * @see org.restlet.test.jaxrs.services.tests.MatchedTest * @see UriInfo#getMatchedResources() * @see UriInfo#getMatchedURIs() */ @Path("ancestorTest") public class MatchedUriTestResource { @SuppressWarnings("unused") // will be used later @Context private UriInfo mainUriInfo; @GET @Produces("text/plain") public String get(@Context UriInfo uriInfo) { final int uriSize = uriInfo.getMatchedURIs().size(); final int resourcesSize = uriInfo.getMatchedResources().size(); return uriSize + "\n" + resourcesSize; } @GET @Produces("text/plain") @Path("sub") public String getResources(@Context UriInfo uriInfo) { final StringBuilder stb = new StringBuilder(); final List resources = uriInfo.getMatchedResources(); stb.append(resources.size()); for (final Object resource : resources) { stb.append('\n'); stb.append(resource.getClass().getName()); } return stb.toString(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PathParamTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PathParamTestService.j0000664000175000017500000000634311757206352034414 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Response; import org.restlet.test.jaxrs.services.tests.PathParamTest; /** * @author Stephan Koops * @see PathParamTest * @see PathParam */ @Path("pathParamTest/{var1}") public class PathParamTestService { @Path("checkUnmodifiable/{var1}") @GET @Produces("text/plain") public Object checkUnmodifiable(@PathParam("var1") List var1s) { try { var1s.clear(); throw new WebApplicationException(Response.serverError().entity( "the List must be unmodifiable").build()); } catch (UnsupportedOperationException uoe) { return null; } } @GET @Produces("text/plain") public String get(@PathParam("var1") String var1) { return var1; } @Path("abc/{var2}/def") @GET @Produces("text/plain") public String get(@PathParam("var1") String var1, @PathParam("var2") String var2) { return var1 + "\n" + var2; } @GET @Path("regExp/{buchstabe:[a-zA-Z]}") @Produces(MediaType.TEXT_PLAIN) public String getRegExpEinBuchstabe(@PathParam("buchstabe") String buchstabe) { return "ein Buchstabe: "+buchstabe; } @GET @Path("regExp/{string}") @Produces(MediaType.TEXT_PLAIN) public String getRegExpSonstwas(@PathParam("string") String string) { return "anderes: "+string; } @GET @Path("regExp/{zahl:[-]?[0-9]+}") @Produces(MediaType.TEXT_PLAIN) public String getRegExpZahl(@PathParam("zahl") int zahl) { return "Zahl: "+zahl; } @Path("st/{var1}") @GET @Produces(MediaType.TEXT_PLAIN) public String getVar1(@PathParam("var1") String var1) { return var1; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/SecurityContextService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/SecurityContextService0000664000175000017500000000747711757206354034636 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.net.URI; import java.security.Principal; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.restlet.test.jaxrs.services.tests.SecurityContextTest; /** * @author Stephan Koops * @see SecurityContextTest * @see SecurityContext */ @Path("/SecurityContextTestService") public class SecurityContextService { @Context private SecurityContext securityContext; @GET @Produces("text/plain") public String get() { if (!this.securityContext.isUserInRole("bad")) { throw new WebApplicationException(403); } return "das darfst Du"; } @GET @Path("authenticationScheme") @Produces("text/plain") public String getAuthenticationScheme() { return this.securityContext.getAuthenticationScheme(); } @GET @Path("userPrincipal") @Produces("text/plain") public String getUserPrincipal() { final Principal principal = this.securityContext.getUserPrincipal(); if (principal == null) { return "no principal found"; } return principal.getName(); } @GET @Path("secure") @Produces("text/plain") public String isSecure(@Context UriInfo uriInfo) { if (!this.securityContext.isSecure()) { final ResponseBuilder rb = Response .status(Status.MOVED_PERMANENTLY); rb.entity("You must use a secure connection"); rb.location(uriInfo.getRequestUriBuilder().scheme("https").build()); throw new WebApplicationException(rb.build()); } return "wonderful! It's a secure request."; } @POST public Response post(MultivaluedMap entity, @Context UriInfo uriInfo) { if (!this.securityContext.isUserInRole("bat")) { throw new WebApplicationException(403); } entity.toString(); // typically the entity will be stored in the DB. final String id = "4711"; final URI collectionUri = uriInfo.getRequestUri(); final URI location = UriBuilder.fromUri(collectionUri).path("{id}") .build(id); return Response.created(location).build(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/UriBuilderTestResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/UriBuilderTestResource0000664000175000017500000000510411757206354034540 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.UriBuilderByServiceTest; /** * @author Stephan Koops * @see UriBuilderByServiceTest */ @Path("UriBuilder") public class UriBuilderTestResource { @Context UriInfo uriInfo; @GET @Path("absolute") @Produces( { MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public String getAbsoluteUriBuilder() { return this.uriInfo.getAbsolutePathBuilder().build().toString(); } @GET @Path("base") @Produces( { MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public String getBaseUriBuilder() { return this.uriInfo.getBaseUriBuilder().build().toString(); } @POST @Path("absolute") @Produces( { MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public String postAbsoluteUriBuilder() { // LATER test also with uri of sub resource return this.uriInfo.getAbsolutePathBuilder().build().toString(); } @POST @Path("base") @Produces( { MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public String postBaseUriBuilder() { return this.uriInfo.getBaseUriBuilder().build().toString(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/NoProviderResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/NoProviderResource.jav0000664000175000017500000000327411757206352034504 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * @author Stephan Koops */ @Path("GenericType") public class NoProviderResource { @GET @Path("no-mbw") @Produces("4711/0815") public Object getNoMediaType() { return new Object(); } @GET @Path("text-plain") @Produces("text/plain") public Object getTextPlain() { return new Object(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalConstructorResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalConstructorReso0000664000175000017500000000407611757206352034577 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.CookieParam; import javax.ws.rs.Path; import org.restlet.test.jaxrs.services.tests.IllegalConstructorTest; /** * This resource is used to test, if a constructor with a requirement to the * entity is ignored, and also a constructor which is not public. * * @author Stephan Koops * @see IllegalConstructorTest */ @Path("IllegalConstructorResource") @SuppressWarnings("all") public class IllegalConstructorResource { /** * not to call, because it requires the entity * * @param entity */ public IllegalConstructorResource(String entity) { } /** * not to call because it is not public * * @param c1 * @param c2 */ IllegalConstructorResource(@CookieParam("c1") String c1, @CookieParam("c2") String c2) { } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/Issue594Resources.java0000664000175000017500000000560211757206354034272 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import org.restlet.test.jaxrs.services.tests.Issue594Test; /** * @author Roman Geus * @author Stephan Koops * @see Issue594Test */ @Path("admin") public class Issue594Resources { /** * Provides both static and dynamic, per-request information, about the * components of a request URI. */ @Context UriInfo uriInfo; @GET @Produces("text/plain") public String root() { return "root"; } @GET @Path("{project}") @Produces("text/plain") public String project(@PathParam("project") String project) { return "project="+project; } @GET @Path("{project}/{repository}") @Produces("text/plain") public String repository(@PathParam("project") String project, @PathParam("repository") String repository) { return "project="+project+"\nrepository="+repository; } @GET @Path("{project}/{repository}/schema") @Produces("text/plain") public String schemaDir(@PathParam("project") String project, @PathParam("repository") String repository) { return "project="+project+"\nrepository="+repository+"\nschema"; } @GET @Path("{project}/{repository}/schema/{schema}") @Produces("text/plain") public String schema(@PathParam("project") String project, @PathParam("repository") String repository, @PathParam("schema") String schema) { return "project="+project+"\nrepository="+repository+"\nschema\nschema="+schema; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatchedTestService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/MatchedTestService.jav0000664000175000017500000001165311757206352034433 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Response.Status; /** * @author Stephan Koops * @see org.restlet.test.jaxrs.services.tests.MatchedTest * @see UriInfo#getMatchedResources() * @see UriInfo#getMatchedURIs() */ @Path("matchedTest") public class MatchedTestService { /** * @param uriInfo * @param attribute * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ private static Object getAttribute(UriInfo uriInfo, String attribute) { final String getterName = "get" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1); Method subMethod; try { subMethod = uriInfo.getClass().getMethod(getterName); } catch (SecurityException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (NoSuchMethodException e) { throw new WebApplicationException(Status.NOT_FOUND); } try { return subMethod.invoke(uriInfo); } catch (IllegalArgumentException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IllegalAccessException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (InvocationTargetException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } } @Context private UriInfo mainUriInfo; @GET @Produces("text/plain") public String get(@Context UriInfo uriInfo) { final int uriSize = uriInfo.getMatchedURIs().size(); final int resourcesSize = uriInfo.getMatchedResources().size(); return uriSize + "\n" + resourcesSize; } @GET @Produces("text/plain") @Path("resourceClassNames") public String getResources(@Context UriInfo uriInfo) { final StringBuilder stb = new StringBuilder(); final List resources = uriInfo.getMatchedResources(); stb.append(resources.size()); for (final Object resource : resources) { stb.append('\n'); stb.append(resource.getClass().getName()); } return stb.toString(); } @Path("sameSub") public MatchedTestService getSameSub() { return getSub(); } @Path("sub") public MatchedTestService getSub() { final MatchedTestService sub = new MatchedTestService(); sub.mainUriInfo = this.mainUriInfo; return sub; } @GET @Produces("text/plain") @Path("uriInfo/{attribute}") public String getUriInfoAttribute(@Context UriInfo subUriInfo, @PathParam("attribute") String attribute) { final Object mainAttrValue = getAttribute(this.mainUriInfo, attribute); final Object subAttrValue = getAttribute(subUriInfo, attribute); return mainAttrValue + "\n" + subAttrValue; } @GET @Produces("text/plain") @Path("uris") public String getUris(@Context UriInfo uriInfo) { final StringBuilder stb = new StringBuilder(); final List uris = uriInfo.getMatchedURIs(); stb.append(uris.size()); for (final String uri : uris) { stb.append('\n'); stb.append(uri); } return stb.toString(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ExcMapperTestResource.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/ExcMapperTestResource.0000664000175000017500000000331011757206354034431 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.restlet.test.jaxrs.services.providers.IllegalArgExcMapper; import org.restlet.test.jaxrs.services.tests.ExcMapperTest; /** * @author Stephan Koops * @see IllegalArgExcMapper * @see ExcMapperTest */ @Path("excMapper") public class ExcMapperTestResource { @GET public Object get() throws IllegalArgumentException { throw new IllegalArgumentException(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InheritAnnotationTestService1.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/InheritAnnotationTestS0000664000175000017500000000334011757206352034540 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.resources; import javax.ws.rs.Path; import org.restlet.test.jaxrs.services.tests.InheritAnnotationTest; /** * @author Stephan Koops * @see InheritAnnotationTestServiceInterface * @see InheritAnnotationTest */ @Path("abcd") public class InheritAnnotationTestService1 implements InheritAnnotationTestServiceInterface { public static final String RETURN_STRING = "getTextWithoutSubResource"; public String getText() { return RETURN_STRING; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/0000775000175000017500000000000011757206354027327 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/PathParamTest.java0000664000175000017500000001115311757206352032706 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.PathParam; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.PathParamTestService; /** * @author Stephan Koops * @see PathParamTestService * @see PathParam */ public class PathParamTest extends JaxRsTestCase { /** * @param subPath * without beginning '/' * @return */ private Reference createReference2(String subPath) { final String baseRef = createBaseRef() + "/pathParamTest/" + subPath; return new Reference(createBaseRef(), baseRef); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(PathParamTestService.class); } }; } /** @see PathParamTestService#checkUnmodifiable(java.util.List) */ public void htestCheckUnmodifiable() { final Response response = get(createReference2("4711/checkUnmodifiable/1667")); assertTrue( "The List annotated with @PathParam must not be modifiable. Status is " + response.getStatus(), response.getStatus() .isSuccess()); } public void testGet1() throws IOException { final Response response = get(createReference2("4711")); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("4711", response.getEntity().getText()); } public void testGet2() throws IOException { final Response response = get(createReference2("4711/abc/677/def")); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("4711\n677", response.getEntity().getText()); } public void testGet4() throws IOException { final Response response = get(createReference2("12/st/34")); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("34", response.getEntity().getText()); } public void testGetRegExpPathEinBuchstabe() throws IOException { Response response = get("regExp/a"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("ein Buchstabe: a", response.getEntity().getText()); } public void testGetRegExpPathLangerString() throws IOException { Response response = get("regExp/aa"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("anderes: aa", response.getEntity().getText()); } public void testGetRegExpPathZahl() throws IOException { Response response = get("regExp/1"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Zahl: 1", response.getEntity().getText()); response = get("regExp/112"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Zahl: 112", response.getEntity().getText()); } public void testGetRegExpPathZahlMinus() throws IOException { Response response = get("regExp/-1"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Zahl: -1", response.getEntity().getText()); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/IllegalConstructorTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/IllegalConstructorTest.jav0000664000175000017500000000465211757206352034515 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.test.jaxrs.services.providers.EntityConstructorProvider; import org.restlet.test.jaxrs.services.providers.ParamConstructorProvider; import org.restlet.test.jaxrs.services.resources.IllegalConstructorResource; /** * Checks, if illegal things are forbidden. * * @author Stephan Koops * @see IllegalConstructorResource */ public class IllegalConstructorTest extends JaxRsTestCase { /** * @return */ @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings("unchecked") public Set> getClasses() { return Util.createSet( IllegalConstructorResource.class, ParamConstructorProvider.class, EntityConstructorProvider.class); } }; } public void testNullSubResource() throws Exception { final Response response = get(); assertTrue(response.getStatus().isError()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/InjectionTest.java0000664000175000017500000000546011757206352032757 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.InjectionTestService; import org.restlet.test.jaxrs.services.resources.InjectionTestService2; import org.restlet.test.jaxrs.util.OrderedReadonlySet; /** * @author Stephan Koops * @see InjectionTestService * @see InjectionTestService2 */ public class InjectionTest extends JaxRsTestCase { @Override protected Application getApplication() { final Application appConfig = new Application() { @Override public Set> getClasses() { return new OrderedReadonlySet>( InjectionTestService.class, InjectionTestService2.class); } }; return appConfig; } public void testGet() { final Response response = get("?qp1=56"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); } /** @see InjectionTestService2#get() */ public void testGetWithIndex() throws IOException { Response response = get("two/56"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("56", response.getEntity().getText()); response = get("two/97"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("97", response.getEntity().getText()); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/DeterminingMediaTypeTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/DeterminingMediaTypeTest.j0000664000175000017500000001000011757206352034376 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.DeterminingMediaTypeTestService; /** * This test class checks if the * {@link javax.ws.rs.core.Request#evaluatePreconditions(java.util.Date, javax.ws.rs.core.EntityTag)} * methods works fine. * * @author Stephan Koops */ public class DeterminingMediaTypeTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections .singleton(DeterminingMediaTypeTestService.class); } }; } public void testHtmlPlainGif1() { final Response response = get("htmlPlainGif", MediaType.TEXT_ALL); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_HTML, response); } public void testHtmlPlainGif2() { final Response response = get("htmlPlainGif", MediaType.ALL); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_HTML, response); } public void testHtmlPlainGif3() { final Response response = get("htmlPlainGif", MediaType.IMAGE_GIF); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.IMAGE_GIF, response); } public void testHtmlPlainGif4() { final Response response = get("htmlPlainGif", MediaType.TEXT_PLAIN); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, response); } public void testTextStar1() { Response response = get("textStar", MediaType.TEXT_ALL); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); response = get("textStar", MediaType.ALL); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); response = get("textStar", MediaType.IMAGE_GIF); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } public void testTextStar2() { final Response response = get("textStar", MediaType.TEXT_HTML); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_HTML, response); } public void testTextStar3() { final Response response = get("textStar", MediaType.TEXT_PLAIN); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, response); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/Issue971Test.java0000664000175000017500000000514511757206354032370 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.providers.Issue971WriterSub; import org.restlet.test.jaxrs.services.resources.Issue971Resource; /** * @author Martin Krasser * * @see Issue971Resource * @see Issue971WriterSub */ public class Issue971Test extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override public Set> getClasses() { Set> classes = new HashSet>(); classes.add(Issue971Resource.class); classes.add(Issue971WriterSub.class); return classes; } }; } /** * @see Issue971Resource#getIssue971() */ public void testGet() throws Exception { final Response response = get("971"); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("issue 971 description", entity.getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/Issue593Test.java0000664000175000017500000000472011757206352032364 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.Issue593Resource; /** * @author Stephan Koops * @see Issue593Resource */ public class Issue593Test extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(Issue593Resource.class); } }; } /** * @see Issue593Resource#getPath(javax.ws.rs.core.UriInfo) */ public void testGet() throws Exception { final Response response = get("example"); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("/test/example", entity.getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/NoProviderTest.java0000664000175000017500000000453411757206354033127 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.MatchedTestService; import org.restlet.test.jaxrs.services.resources.NoProviderResource; /** * @author Stephan Koops * @see MatchedTestService */ public class NoProviderTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(NoProviderResource.class); } }; } public void testNoMediaType() throws Exception { final Response response = get("no-mbw"); assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); } public void testTextPlain() throws Exception { final Response response = get("text-plain"); assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/HeadOptionsTest.java0000664000175000017500000001422011757206352033244 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.HEAD; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.others.OPTIONS; import org.restlet.test.jaxrs.services.resources.HeadOptionsTestService; /** * Test to check if HTTP methods HEAD and OPTIONS work fine. * * @author Stephan Koops * @see HeadOptionsTestService * @see HEAD * @see OPTIONS */ public class HeadOptionsTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(HeadOptionsTestService.class); } }; } public void testHead1() throws Exception { final Response responseGett = get("headTest1", MediaType.TEXT_HTML); final Response responseHead = head("headTest1", MediaType.TEXT_HTML); if (responseGett.getStatus().isError()) { System.out.println(responseGett.getEntity().getText()); } assertEquals(Status.SUCCESS_OK, responseGett.getStatus()); if (responseHead.getStatus().isError()) { System.out.println(responseHead.getEntity().getText()); } assertEquals(Status.SUCCESS_OK, responseHead.getStatus()); final Representation entityGett = responseGett.getEntity(); final Representation entityHead = responseHead.getEntity(); assertNotNull(entityGett); assertNotNull("Must not be null to read the entity headers", entityHead); assertEqualMediaType(MediaType.TEXT_HTML, entityGett.getMediaType()); assertEqualMediaType(MediaType.TEXT_HTML, entityHead.getMediaType()); assertEquals("4711", entityGett.getText()); assertEquals("The entity text of the head request must be null", null, entityHead.getText()); } public void testHead2() throws Exception { final Response responseGett = get("headTest2", MediaType.TEXT_HTML); final Response responseHead = head("headTest2", MediaType.TEXT_HTML); if (responseGett.getStatus().isError()) { System.out.println(responseGett.getEntity().getText()); } assertEquals(Status.SUCCESS_OK, responseGett.getStatus()); if (responseHead.getStatus().isError()) { System.out.println(responseHead.getEntity().getText()); } assertEquals(Status.SUCCESS_OK, responseHead.getStatus()); final Representation entityGett = responseGett.getEntity(); final Representation entityHead = responseHead.getEntity(); assertNotNull(entityGett); assertNotNull("Must not be null to read the entity headers", entityHead); assertEqualMediaType(MediaType.TEXT_HTML, entityGett.getMediaType()); assertEqualMediaType(MediaType.TEXT_HTML, entityHead.getMediaType()); assertEquals("4711", entityGett.getText()); assertEquals("The entity text of the head request must be null", null, entityHead.getText()); } public void testHead2plain() throws Exception { final Response responseGett = get("headTest2", MediaType.TEXT_PLAIN); final Response responseHead = head("headTest2", MediaType.TEXT_PLAIN); if (responseGett.getStatus().isError()) { System.out.println(responseGett.getEntity().getText()); } assertEquals(Status.SUCCESS_OK, responseGett.getStatus()); if (responseHead.getStatus().isError()) { System.out.println(responseHead.getEntity().getText()); } assertEquals(Status.SUCCESS_OK, responseHead.getStatus()); final Representation entityGett = responseGett.getEntity(); final Representation entityHead = responseHead.getEntity(); assertNotNull(entityGett); assertNotNull("Must not be null to read the entity headers", entityHead); assertEqualMediaType(MediaType.TEXT_PLAIN, entityGett.getMediaType()); assertEqualMediaType(MediaType.TEXT_PLAIN, entityHead.getMediaType()); assertEquals("4711", entityGett.getText()); assertEquals("The entity text of the head request must be null", null, entityHead.getText()); } public void testOptions() throws Exception { Response response = options(); assertAllowedMethod(response, Method.GET); response = options("headTest1"); assertAllowedMethod(response, Method.GET, Method.HEAD, Method.POST); response = options("headTest2"); assertAllowedMethod(response, Method.GET, Method.HEAD); response = options("xyz"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ThrowExceptionTest.java0000664000175000017500000000642111757206352034015 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.test.jaxrs.services.providers.SqlExceptionMapper; import org.restlet.test.jaxrs.services.resources.ThrowExceptionResource; /** * @author Stephan Koops * @see ThrowExceptionResource */ public class ThrowExceptionTest extends JaxRsTestCase { @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(ThrowExceptionResource.class); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set getSingletons() { return (Set) Util.createSet(new SqlExceptionMapper()); } }; return appConfig; } /** * @throws Exception * @see ThrowExceptionResource */ public void testIoe() { final Response response = get("IOException"); assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); } public void testSqlExc() throws Exception { final Response response = get("sqlExc"); assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); assertEquals(SqlExceptionMapper.MESSAGE, response.getEntity().getText()); } /** * @see ThrowExceptionResource#getWebAppExc() */ public void testWebAppExc() { final Response response = get("WebAppExc"); final int actStatus = response.getStatus().getCode(); assertEquals(ThrowExceptionResource.WEB_APP_EXC_STATUS, actStatus); } public void testWebAppExcNullStatus() { final Response response = get("WebAppExcNullStatus"); assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ThrowWebAppExcProviderTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ThrowWebAppExcProviderTest0000664000175000017500000000521211757206352034465 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.representation.StringRepresentation; import org.restlet.test.jaxrs.services.providers.ThrowWebAppExcProvider; import org.restlet.test.jaxrs.services.resources.SimpleResource; import org.restlet.test.jaxrs.util.TestUtils; /** * @author Stephan Koops * @see ThrowWebAppExcProvider * @see SimpleResource */ public class ThrowWebAppExcProviderTest extends JaxRsTestCase { @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set getSingletons() { return (Set) TestUtils.createSet(new ThrowWebAppExcProvider()); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(SimpleResource.class); } }; return appConfig; } public void testPost() { final Response response = post(new StringRepresentation("jgjhsdhbf")); sysOutEntityIfError(response); final int statusCode = response.getStatus().getCode(); assertEquals(ThrowWebAppExcProvider.STATUS_READ, statusCode); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/CarTest.java0000664000175000017500000001172611757206354031546 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.car.CarListResource; import org.restlet.test.jaxrs.services.car.CarResource; import org.restlet.test.jaxrs.services.car.EngineResource; /** * @author Stephan Koops * @see CarListResource * @see CarResource * @see EngineResource */ public class CarTest extends JaxRsTestCase { public static void main(String[] args) throws Exception { new CarTest().runServerUntilKeyPressed(); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(CarListResource.class); } }; } public void testDelete() throws Exception { final Response response = accessServer(Method.DELETE, CarListResource.class, null, null); assertTrue( "The status should be a client error, but was " + response.getStatus(), response.getStatus() .isClientError()); assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, response.getStatus()); } /** * This tests, if a sub resource class of a sub resource class of a root * resource class is accessable. * * @throws Exception */ public void testEngine() throws Exception { final Response response = get("4711/engine"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals(EngineResource.getPlainRepr(4711), entity.getText()); } public void testGetCar() throws Exception { final String carNumber = "57"; final Response response = get(carNumber); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(CarResource.createTextRepr(carNumber), entity.getText()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); } public void testGetHtmlText() throws Exception { final Response response = get(MediaType.TEXT_HTML); assertTrue( "The status should be a client error, but was " + response.getStatus(), response.getStatus() .isClientError()); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } public void testGetOffers() throws Exception { final Response response = get("offers"); final Representation representation = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(CarListResource.OFFERS, representation.getText()); final MediaType actualMediaType = representation.getMediaType(); assertEqualMediaType(MediaType.TEXT_PLAIN, actualMediaType); } public void testGetPlainText() throws Exception { final Response response = get(MediaType.TEXT_PLAIN); final Status status = response.getStatus(); assertTrue("Status should be 2xx, but is " + status, status.isSuccess()); final Representation representation = response.getEntity(); assertEquals(CarListResource.DUMMY_CAR_LIST, representation.getText()); assertEqualMediaType(MediaType.TEXT_PLAIN, representation.getMediaType()); } public void testOptions() throws Exception { Response response = options(); assertAllowedMethod(response, Method.GET, Method.POST); response = options("offers"); assertAllowedMethod(response, Method.GET, Method.POST); response = options("53"); assertAllowedMethod(response, Method.GET); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/PathParamTest3.java0000664000175000017500000000602011757206354032770 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.PathParam; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.PathParamTestResource3; /** * @author Stephan Koops * @see PathParamTestResource3 * @see PathParam */ public class PathParamTest3 extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections .singleton(PathParamTestResource3.class); } }; } public void test() throws Exception { doTest("AAAABBBB", "eeeee", "AAAABBBB", "eeeee"); doTest("AAA%2FBB", "eeeee", "AAA/BB", "eeeee"); doTest("AAA%2FBB", "e%2Fe", "AAA/BB", "e/e"); doTest("AAAABBBB", "e%2Fe", "AAAABBBB", "e/e"); } /** * @param doctypeEncoded * @param entryidEncoded * @param doctypeDecoded * @param entryidDecoded * @throws IOException */ private void doTest(String doctypeEncoded, String entryidEncoded, String doctypeDecoded, String entryidDecoded) throws IOException { Reference reference = createBaseRef(); reference = new Reference(reference + "/supplemental/" + doctypeEncoded + "/" + entryidEncoded); Response response = get(reference); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(doctypeDecoded + "\n" + entryidDecoded + "\n", response .getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/PersonsTest.java0000664000175000017500000001061311757206354032464 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.List; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.jaxb.JaxbRepresentation; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.others.PersonList; import org.restlet.test.jaxrs.services.resources.PersonResource; import org.restlet.test.jaxrs.services.resources.PersonsResource; import org.restlet.test.jaxrs.util.OrderedReadonlySet; /** * @author Stephan Koops * @see PersonsResource * @see PersonResource */ public class PersonsTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override public Set> getClasses() { return new OrderedReadonlySet>(PersonsResource.class, PersonResource.class); } }; } /** * @throws Exception * @see PersonsResource#addPerson(Person) * @see PersonResource#get(int) */ public void testCreate() throws Exception { if (usesTcp()) { return; } final Person newPerson = new Person("Kurt", "Beck"); final Response response1 = post(new JaxbRepresentation( newPerson)); sysOutEntityIfError(response1); assertEquals(Status.SUCCESS_CREATED, response1.getStatus()); final Reference newLocation = response1.getLocationRef(); final Response response2 = get(newLocation, MediaType.APPLICATION_JAVASCRIPT, MediaType.TEXT_XML); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); final JaxbRepresentation repr = new JaxbRepresentation( response2.getEntity(), Person.class); final Person person = repr.getObject(); assertTrue(person.getFirstname().startsWith("firstname")); assertEquals("lastname", person.getLastname()); final Response response3 = get(newLocation, MediaType.ALL); sysOutEntityIfError(response3); assertEquals(Status.SUCCESS_OK, response3.getStatus()); final JaxbRepresentation repr3 = new JaxbRepresentation( response3.getEntity(), Person.class); final Person person3 = repr3.getObject(); assertTrue(person3.getFirstname().startsWith("firstname")); assertEquals("lastname", person3.getLastname()); } public void testGetList() throws Exception { final Response response = get(); sysOutEntityIfError(response); final JaxbRepresentation personListRepr = new JaxbRepresentation( response.getEntity(), PersonList.class); final List persons = personListRepr.getObject().getPersons(); assertEquals(3, persons.size()); assertEquals("Angela", persons.get(0).getFirstname()); assertEquals("Olmert", persons.get(1).getLastname()); assertEquals("George U.", persons.get(2).getFirstname()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/InheritAnnotationTest.java0000664000175000017500000001126211757206354034471 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.InheritAnnotationTestService1; import org.restlet.test.jaxrs.services.resources.InheritAnnotationTestService2; import org.restlet.test.jaxrs.services.resources.InheritAnnotationTestServiceInterface; /** * Check, if the inheritation of method annotations works corerct. * * @author Stephan Koops * @see InheritAnnotationTestService1 * @see InheritAnnotationTestService2 * @see InheritAnnotationTestServiceInterface */ public class InheritAnnotationTest extends JaxRsTestCase { private static final Class SERVICE_1 = InheritAnnotationTestService1.class; private static final Class SERVICE_2 = InheritAnnotationTestService2.class; @Override protected Application getApplication() { return new Application() { @Override public Set> getClasses() { final Set> rrcs = new HashSet>(2); rrcs.add(SERVICE_1); rrcs.add(SERVICE_2); return rrcs; } }; } public void test1() throws Exception { final Reference reference = createReference(SERVICE_1, "getText"); final Response response = accessServer(Method.GET, reference); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, response); final String entityText = response.getEntity().getText(); assertEquals(InheritAnnotationTestService1.RETURN_STRING, entityText); } public void test2a() throws Exception { final Reference reference = createReference(SERVICE_2, "getText"); final Response response = accessServer(Method.GET, reference); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, response); final String entityText = response.getEntity().getText(); assertEquals(InheritAnnotationTestService2.RETURN_STRING, entityText); } public void test2b() throws Exception { final Reference reference = createReference(SERVICE_2, "getSubClassText"); final Response response = accessServer(Method.GET, reference); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, response); final String entityText = response.getEntity().getText(); assertEquals(InheritAnnotationTestService2.RETURN_STRING_SUB, entityText); } public void x_test2c() throws Exception { final Reference reference = createReference(SERVICE_2, "getSubClassText/sub"); final Response response = accessServer(Method.GET, reference); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, response); final String entityText = response.getEntity().getText(); assertEquals(InheritAnnotationTestService2.RETURN_STRING_SUB2, entityText); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/SimpleTrainTest.java0000664000175000017500000002110511757206352033256 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.SimpleTrain; import org.restlet.test.jaxrs.util.TestUtils; /** * one of the first test case classes. * * @author Stephan Koops * @see SimpleTrain */ public class SimpleTrainTest extends JaxRsTestCase { private static final boolean ONLY_M2 = false; private static final boolean ONLY_TEXT_ALL = false; private static final Preference PREF_TEXTPLAIN_QUAL05 = new Preference( MediaType.TEXT_PLAIN, 0.5f); @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(SimpleTrain.class); } }; } public void testGetHtmlText() throws Exception { if (!ONLY_M2 && !ONLY_TEXT_ALL) { final Response response = get(MediaType.TEXT_HTML); sysOutEntityIfError(response); assertTrue(response.getStatus().isSuccess()); final Representation entity = response.getEntity(); assertEquals(SimpleTrain.RERP_HTML_TEXT, entity.getText()); assertEqualMediaType(MediaType.TEXT_HTML, entity.getMediaType()); } } public void testGetPlainText() throws Exception { if (!ONLY_M2 && !ONLY_TEXT_ALL) { final Response response = get(MediaType.TEXT_PLAIN); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals(SimpleTrain.RERP_PLAIN_TEXT, entity.getText()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); } } public void testGetTextAll() throws Exception { if (ONLY_M2) { return; } Response response = get(MediaType.TEXT_ALL); sysOutEntityIfError(response); Representation representation = response.getEntity(); final MediaType mediaType = representation.getMediaType(); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertTrue(mediaType.equals(MediaType.TEXT_PLAIN, true) || mediaType.equals(MediaType.TEXT_HTML, true)); response = get(MediaType.TEXT_PLAIN); sysOutEntityIfError(response); assertTrue(response.getStatus().isSuccess()); representation = response.getEntity(); assertEquals(SimpleTrain.RERP_PLAIN_TEXT, representation.getText()); assertEqualMediaType(MediaType.TEXT_PLAIN, representation); } public void testGetTextMultiple1() throws Exception { if (!ONLY_M2 && !ONLY_TEXT_ALL) { final Response response = accessServer(Method.GET, SimpleTrain.class, TestUtils.createList(new Object[] { PREF_TEXTPLAIN_QUAL05, MediaType.TEXT_CALENDAR })); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals(SimpleTrain.RERP_PLAIN_TEXT, entity.getText()); } } public void testGetTextMultiple2() throws Exception { if (ONLY_TEXT_ALL) { return; } final Response response = accessServer(Method.GET, SimpleTrain.class, TestUtils.createList(new Object[] { PREF_TEXTPLAIN_QUAL05, MediaType.TEXT_HTML })); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation representation = response.getEntity(); assertEqualMediaType(MediaType.TEXT_HTML, representation.getMediaType()); assertEquals(SimpleTrain.RERP_HTML_TEXT, representation.getText()); } public void testHead() throws Exception { if (!ONLY_M2 && !ONLY_TEXT_ALL) { final Response responseHead = accessServer(Method.HEAD, SimpleTrain.class, TestUtils.createList(new Object[] { PREF_TEXTPLAIN_QUAL05, MediaType.TEXT_HTML })); final Response responseGett = accessServer(Method.GET, SimpleTrain.class, TestUtils.createList(new Object[] { PREF_TEXTPLAIN_QUAL05, MediaType.TEXT_HTML })); assertEquals(Status.SUCCESS_OK, responseHead.getStatus()); assertEquals(Status.SUCCESS_OK, responseGett.getStatus()); final Representation entityHead = responseHead.getEntity(); final Representation entityGett = responseGett.getEntity(); assertNotNull(entityHead); assertNotNull(entityGett); assertEqualMediaType(MediaType.TEXT_HTML, entityGett.getMediaType()); assertEquals(SimpleTrain.RERP_HTML_TEXT, entityGett.getText()); } } public void testOptions() throws Exception { final Response response = options(); sysOutEntityIfError(response); assertAllowedMethod(response, Method.GET); } public void testTemplParamsDecoded() throws Exception { final String deEncoded = "decode"; Response response = get(deEncoded + "/66"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("66", response.getEntity().getText()); response = get(deEncoded + "/a+bc"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a bc", response.getEntity().getText()); response = get(deEncoded + "/a%20bc"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a bc", response.getEntity().getText()); } public void testTemplParamsEncoded() throws Exception { final String deEncoded = "encode"; Response response = get(deEncoded + "/66"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("66", response.getEntity().getText()); response = get(deEncoded + "/a+bc"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a+bc", response.getEntity().getText()); response = get(deEncoded + "/a%20bc"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a%20bc", response.getEntity().getText()); } public void testUseAllTests() { assertFalse("You should use all tests", ONLY_M2); assertFalse("You should use all tests", ONLY_TEXT_ALL); } protected Class getRootResourceClass() { throw new UnsupportedOperationException( "You must implement the methods getRootResourceClass() or getAppConfig(). If you only implemented getAppConfig(), you can't use this method"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/SimpleHouseTest.java0000664000175000017500000000717611757206352033300 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.SimpleHouse; /** * One of the first Test classes. * * @author Stephan Koops * @see SimpleHouse */ public class SimpleHouseTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(SimpleHouse.class); } }; } public void testGetHtmlText() throws Exception { final Response response = get(MediaType.TEXT_HTML); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } public void testGetNull() throws Exception { final Response response = get("null"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); final Representation entity = response.getEntity(); if (entity != null) { assertEquals(null, entity.getText()); } } public void testGetNullWithMediaType() throws Exception { final Response response = get("nullWithMediaType"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); final Representation entity = response.getEntity(); if (entity != null) { assertEquals(null, entity.getText()); } } public void testGetPlainText() throws Exception { final Response response = get(MediaType.TEXT_PLAIN); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals(SimpleHouse.RERP_PLAIN_TEXT, entity.getText()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); } public void testGetTextAll() throws Exception { final Response response = get(MediaType.TEXT_ALL); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals(SimpleHouse.RERP_PLAIN_TEXT, entity.getText()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ExcMapperTest.java0000664000175000017500000000575211757206352032725 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.test.jaxrs.services.providers.IllegalArgExcMapper; import org.restlet.test.jaxrs.services.resources.ExcMapperTestResource; /** * @author Stephan Koops * @see ExcMapperTestResource * @see IllegalArgExcMapper */ public class ExcMapperTest extends JaxRsTestCase { /** * @param accMediaType * @param expMediaType */ private void check(MediaType accMediaType, MediaType expMediaType) { final Response response = get(accMediaType); sysOutEntityIfError(response); assertEquals(IllegalArgExcMapper.STATUS, response.getStatus().getCode()); assertEqualMediaType(expMediaType, response); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(ExcMapperTestResource.class); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set getSingletons() { return (Set) Collections.singleton(new IllegalArgExcMapper()); } }; } public void testHtml() { check(MediaType.TEXT_HTML, MediaType.TEXT_HTML); } public void testImage() { check(MediaType.IMAGE_BMP, MediaType.TEXT_PLAIN); } public void testPlain() { check(MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN); } public void testXml() { check(MediaType.TEXT_XML, MediaType.TEXT_PLAIN); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/SecurityContextTest.java0000664000175000017500000002366011757206354034215 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.security.Principal; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import javax.ws.rs.core.SecurityContext; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.jaxrs.RoleChecker; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.SecurityContextService; /** * This test class checks if the Request.evaluatePreconditions methods works * fine. * * @author Stephan Koops * @see SecurityContextService */ @SuppressWarnings("deprecation") public class SecurityContextTest extends JaxRsTestCase { private static final Class SEC_CONT_SERV = SecurityContextService.class; @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(SEC_CONT_SERV); } }; } @Override public boolean shouldStartServerInSetUp() { return false; } /** * @param roleChecker * @throws Exception */ private boolean startServer(RoleChecker roleChecker) throws Exception { startServer(ChallengeScheme.HTTP_BASIC, roleChecker); return true; } /** * Allow access, but forbid all rules * * @throws Exception */ public void test2() throws Exception { if (!startServer(RoleChecker.FORBID_ALL)) { return; } Response response = get(); assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); response = getAuth(null, "ydfsdf", "ydf"); assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); } public void test3() throws Exception { if (!startServer(RoleChecker.FORBID_ALL)) { return; } final Response response = getAuth(null, "admin", "adminPW"); sysOutEntityIfNotStatus(Status.CLIENT_ERROR_FORBIDDEN, response); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, response.getStatus()); } public void test4() throws Exception { if (!startServer(RoleChecker.FORBID_ALL)) { return; } final Response response = post(null, new Form().getWebRepresentation(), new ChallengeResponse(ChallengeScheme.HTTP_BASIC, "alice", "alicesSecret")); sysOutEntityIfNotStatus(Status.CLIENT_ERROR_FORBIDDEN, response); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, response.getStatus()); } public void test5() throws Exception { if (!startServer(RoleChecker.FORBID_ALL)) { return; } final Representation postEntity = new Form("abc=def") .getWebRepresentation(); final ChallengeResponse cr = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "bob", "bobsSecret"); final Response response = post(null, postEntity, cr); sysOutEntityIfNotStatus(Status.CLIENT_ERROR_FORBIDDEN, response); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, response.getStatus()); } /** * @see SecurityContextService#post(SecurityContext, * javax.ws.rs.core.MultivaluedMap, javax.ws.rs.core.UriInfo) * @throws Exception */ public void testAllowAll() throws Exception { if (!startServer(RoleChecker.ALLOW_ALL)) { return; } final ChallengeResponse cr = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "bob", "bobsSecret"); Response response = get(null, cr); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = post(null, new Form("abc=def").getWebRepresentation(), cr); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_CREATED, response.getStatus()); final Reference expecretLocation = createReference(SEC_CONT_SERV, null); assertTrue("The location must start with " + expecretLocation + "; it is " + response.getLocationRef(), response .getLocationRef().toString().startsWith( expecretLocation.toString())); } public void testAuthenticationSchemeBasic() throws Exception { if (!startServer(RoleChecker.ALLOW_ALL)) { return; } final ChallengeResponse cr = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "bob", "bobsSecret"); final Response response = get("authenticationScheme", cr); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); assertEquals(SecurityContext.BASIC_AUTH, entity); } public void testForbidAll() throws Exception { if (!startServer(RoleChecker.FORBID_ALL)) { return; } Response response = get(); assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); response = post(new Form("abc=def").getWebRepresentation()); assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); } /** * @throws Exception */ public void testNoRoles() throws Exception { final RoleChecker exampleAuthorizator = new RoleChecker() { /** * @return true, if the role name and the username starts with the * same char. * @see RoleChecker#isUserInRole(String) */ public boolean isInRole(Principal principal, String role) { if (principal == null) { throw new IllegalArgumentException("No principal given"); } if (role == null) { throw new IllegalArgumentException("No role given"); } if (role.charAt(0) == principal.getName().charAt(0)) { return true; } return false; } }; if (!startServer(exampleAuthorizator)) { return; } Response response = getAuth(null, "fsdf", "xyz"); assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); response = getAuth(null, "fsdf", "baj"); assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); response = getAuth(null, "alice", "alicesSecret"); sysOutEntityIfNotStatus(Status.CLIENT_ERROR_FORBIDDEN, response); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, response.getStatus()); response = getAuth(null, "bob", "bobsSecret"); assertEquals(Status.SUCCESS_OK, response.getStatus()); ChallengeResponse cr; cr = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, "bob", "bobsSecret"); response = post(null, new Form("abc=def").getWebRepresentation(), cr); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_CREATED, response.getStatus()); response = accessServer(Method.PUT, SEC_CONT_SERV, null, null, cr); assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, response .getStatus()); } // hope that Restlet Request.isConfidential() works right with HTTPS public void testSecure() throws Exception { startServer(); final Reference reference = super.createReference("secure"); final Response response = get(reference); assertEquals(Status.REDIRECTION_PERMANENT, response.getStatus()); reference.setScheme("https"); assertEquals(reference, response.getLocationRef()); } public void testUserPrincipalAuth() throws Exception { if (!startServer(RoleChecker.ALLOW_ALL)) { return; } Response response = getAuth("userPrincipal", "alice", "alicesSecret"); assertEquals(Status.SUCCESS_OK, response.getStatus()); String entity = response.getEntity().getText(); assertEquals("alice", entity); response = getAuth("userPrincipal", "bob", "bobsSecret"); assertEquals(Status.SUCCESS_OK, response.getStatus()); entity = response.getEntity().getText(); assertEquals("bob", entity); } public void testUserPrincipalNotAuth() throws Exception { startServer(); final Response response = get("userPrincipal"); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); assertEquals("no principal found", entity); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java0000664000175000017500000003523511757206352032632 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.jaxrs.internal.provider.JaxbElementProvider; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.resources.ProviderTestService; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author Stephan Koops * @see ProviderTestService * @see MessageBodyReader * @see MessageBodyWriter * @see JsonTest */ public class ProviderTest extends JaxRsTestCase { public static final boolean LATER = true; private static Form createForm() { Form form = new Form(); form.add("firstname", "Angela"); form.add("lastname", "Merkel"); return form; } /** * @param subPath * @throws IOException * @throws DOMException */ private void getAndCheckJaxb(String subPath) throws Exception { Response response = get(subPath); assertEquals(Status.SUCCESS_OK, response.getStatus()); DomRepresentation entity = new DomRepresentation(response.getEntity()); Node xml = entity.getDocument().getFirstChild(); System.out.println(subPath + ": " + entity.getText()); assertEquals("person", xml.getNodeName()); NodeList nodeList = xml.getChildNodes(); Node node = nodeList.item(0); assertEquals("firstname", node.getNodeName()); assertEquals("Angela", node.getFirstChild().getNodeValue()); node = nodeList.item(1); assertEquals("lastname", node.getNodeName()); assertEquals("Merkel", node.getFirstChild().getNodeValue()); assertEquals(2, nodeList.getLength()); } /** * @param subPath * @throws IOException */ private Response getAndExpectAlphabet(String subPath) throws IOException { Response response = get(subPath); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); Representation entity = response.getEntity(); assertEquals(ProviderTestService.ALPHABET, entity.getText()); return response; } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(ProviderTestService.class); } }; } /** * @param subPath * @throws IOException */ private void postAndCheckXml(String subPath) throws Exception { final Representation send = new DomRepresentation( new StringRepresentation( "HelmutKohl", MediaType.TEXT_XML)); final Response response = post(subPath, send); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation respEntity = response.getEntity(); assertEquals("Helmut Kohl", respEntity.getText()); } /** * @param subPath * @param postEntity * @param postMediaType * @param responseMediaType * if null, it will not be testet * @throws IOException */ private void postAndExceptGiven(String subPath, String postEntity, MediaType postMediaType, MediaType responseMediaType) throws IOException { Representation entity = new StringRepresentation(postEntity, postMediaType); final Response response = post(subPath, entity); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); entity = response.getEntity(); assertEquals(postEntity, entity.getText()); if (responseMediaType != null) { assertEqualMediaType(responseMediaType, entity); } } public void testBufferedReaderGet() throws Exception { getAndExpectAlphabet("BufferedReader"); } public void testBufferedReaderPost() throws Exception { Representation entity = new StringRepresentation("big test", MediaType.APPLICATION_OCTET_STREAM); final Response response = post("BufferedReader", entity); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); entity = response.getEntity(); assertEquals("big test", entity.getText()); } public void testByteArrayGet() throws Exception { getAndExpectAlphabet("byteArray"); } public void testByteArrayPost() throws Exception { final Representation entity = new StringRepresentation("big test", MediaType.APPLICATION_OCTET_STREAM); final Response response = post("byteArray", entity); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("big test", response.getEntity().getText()); } public void testCharSequenceGet() throws Exception { final Response response = get("CharSequence"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals(ProviderTestService.createCS(), entity.getText()); } public void testCharSequencePost() throws Exception { postAndExceptGiven("CharSequence", "a character sequence", MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN); } public void testFileGet() throws Exception { getAndExpectAlphabet("file"); } public void testFilePost() throws Exception { final Response response = post("file", new StringRepresentation( "big test", MediaType.APPLICATION_OCTET_STREAM)); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("big test", response.getEntity().getText()); } public void testFormGet() throws Exception { final Response response = get("form"); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals("firstname=Angela&lastname=Merkel", entity.getText()); } public void testFormPost() throws Exception { final Response response = post("form", createForm() .getWebRepresentation()); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String respEntity = response.getEntity().getText(); assertEquals("[(firstname,Angela), (lastname,Merkel)]", respEntity); } public void testInputStreamGet() throws Exception { getAndExpectAlphabet("InputStream"); } public void testInputStreamPost() throws Exception { Representation entity = new StringRepresentation("big test", MediaType.APPLICATION_OCTET_STREAM); final Response response = post("InputStream", entity); assertEquals(Status.SUCCESS_OK, response.getStatus()); entity = response.getEntity(); assertEquals("big test", entity.getText()); } /** @see ProviderTestService#jaxbElementGet() */ public void testJaxbElementGet() throws Exception { getAndCheckJaxb("jaxbElement"); } /** @see ProviderTestService#jaxbPost(javax.xml.bind.JAXBElement) */ public void testJaxbElementPost() throws Exception { if (!LATER) { // LATER conversion to JAXBElement doesn't work postAndCheckXml("jaxbElement"); } } /** * @param subPath * @throws IOException * @see ProviderTestService#jaxbPostNamespace(javax.xml.bind.JAXBElement) */ public void testJaxbElementPostRootElement() throws Exception { if (!LATER) { final Representation send = new DomRepresentation( new StringRepresentation( "HelmutKohl\n", MediaType.TEXT_XML)); final Response response = post("jaxbElement/rootElement", send); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation respEntity = response.getEntity(); assertEquals("person", respEntity.getText()); } } @SuppressWarnings("all") public static void main(String[] args) throws Exception { Person person = new Person("vn", "nn"); JaxbElementProvider jaxbElementProvider = new JaxbElementProvider(); jaxbElementProvider.contextResolver = new ContextResolver() { public JAXBContext getContext(Class type) { return null; } }; JAXBElement jaxbElement = new JAXBElement(new QName( "xyz"), Person.class, person); jaxbElementProvider.writeTo(jaxbElement, Person.class, Person.class, null, null, null, System.out); String xml = "vnnn"; Type type = new ParameterizedType() { public Type[] getActualTypeArguments() { return new Type[] { Person.class }; } public Type getOwnerType() { throw new UnsupportedOperationException( "not implemented for this test"); } public Type getRawType() { throw new UnsupportedOperationException( "not implemented for this test"); } }; JAXBElement je = jaxbElementProvider.readFrom( (Class) JAXBElement.class, type, null, null, null, new ByteArrayInputStream(xml.getBytes())); System.out.println(); } public void testJaxbGet() throws Exception { getAndCheckJaxb("jaxb"); } public void testJaxbPost() throws Exception { if (usesTcp()) { return; } postAndCheckXml("jaxb"); } /** @see ProviderTestService#mMapGet() */ public void testMultivaluedMapGet() throws Exception { final Response response = get("MultivaluedMap"); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals("lastname=Merkel&firstname=Angela", entity.getText()); } /** @see ProviderTestService#mMapPost(javax.ws.rs.core.MultivaluedMap) */ public void testMultivaluedMapPost() throws Exception { final Response response = post("MultivaluedMap", createForm() .getWebRepresentation()); assertEquals(Status.SUCCESS_OK, response.getStatus()); final MediaType respMediaType = response.getEntity().getMediaType(); assertEqualMediaType(MediaType.TEXT_PLAIN, respMediaType); final String respEntity = response.getEntity().getText(); assertEquals("[(lastname,Merkel), (firstname,Angela)]", respEntity); } public void testReaderGet() throws Exception { getAndExpectAlphabet("Reader"); } public void testReaderPost() throws Exception { postAndExceptGiven("Reader", "big test", MediaType.APPLICATION_OCTET_STREAM, null); } public void testStringBuilderGet() throws Exception { getAndExpectAlphabet("StringBuilder"); } public void testStringGet() throws Exception { getAndExpectAlphabet("String"); final Response response = get("String2"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals(ProviderTestService.STRING2, entity.getText()); } public void testStringPost() throws Exception { postAndExceptGiven("String", "another String", MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN); } public void testSubStringGet() throws Exception { final Response response = get("String/substring;start=5;end=9"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("FGHI", response.getEntity().getText()); } public void testXmlTransformGet() throws Exception { final Response response = get("source"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); assertEquals("", entity); } public void testXmlTransformPost() throws Exception { final Response response = post("source", new StringRepresentation( "abcdefg", MediaType.TEXT_XML)); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abcdefg", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RecursiveTest.java0000664000175000017500000000674011757206352033006 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.RecursiveTestService; /** * @author Stephan Koops * @see RecursiveTestService */ public class RecursiveTest extends JaxRsTestCase { @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(RecursiveTestService.class); } }; return appConfig; } public void test0() throws Exception { final Response response = get(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("0", response.getEntity().getText()); } public void test1a() throws Exception { final Response response = get("a"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1", response.getEntity().getText()); } public void test1b() throws Exception { final Response response = get("a/"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1", response.getEntity().getText()); } public void test2() throws Exception { final Response response = get("a/a"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("2", response.getEntity().getText()); } public void test2b() throws Exception { final Response response = get("a/a/"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("2", response.getEntity().getText()); } public void test3() throws Exception { final Response response = get("a/a/a"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("3", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/IllegalThingsTest.java0000664000175000017500000000535411757206352033565 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.IllegalThingsTestService; /** * Checks, if illegal things are forbidden. * * @author Stephan Koops * @see IllegalThingsTestService */ public class IllegalThingsTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections .singleton(IllegalThingsTestService.class); } }; } public void testNullSubResource() throws Exception { final Response response = get("nullSubResource"); assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); } public void testPackage() throws Exception { final Response response = get("package"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } public void testPrivate() throws Exception { final Response response = get("private"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } public void testProtected() throws Exception { final Response response = get("protected"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/CookieParamTest.java0000664000175000017500000001352211757206352033225 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.CookieParam; import javax.ws.rs.core.Application; import junit.framework.AssertionFailedError; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Cookie; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.CookieParamTestService; /** * @author Stephan Koops * @see CookieParamTestService * @see CookieParam */ public class CookieParamTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections .singleton(CookieParamTestService.class); } }; } public void test1() throws IOException { Response response = get(new Cookie("c", "value")); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("value", response.getEntity().getText()); response = get(new Cookie("c", "sdfgdfg")); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("sdfgdfg", response.getEntity().getText()); } public void test2() throws IOException { final Response response = get(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); final Representation entity = response.getEntity(); String text; if (entity != null) { text = entity.getText(); } else { text = null; } assertEquals(null, text); } public void testCookieArray() throws Exception { final Request request = createGetRequest("array"); request.getCookies().add(new Cookie("c", "c1")); request.getCookies().add(new Cookie("c", "c2")); request.getCookies().add(new Cookie("d", "c3")); final Response response = accessServer(request); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); final String entityWithoutBrackets = entity.substring(1, entity .length() - 1); assertEquals("c1, c2", entityWithoutBrackets); } public void testCookieSet() throws Exception { final Request request = createGetRequest("Set"); request.getCookies().add(new Cookie("c", "c1")); request.getCookies().add(new Cookie("c", "c2")); request.getCookies().add(new Cookie("d", "c3")); final Response response = accessServer(request); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); final String entityWithoutBrackets = entity.substring(1, entity .length() - 1); try { assertEquals("c1, c2", entityWithoutBrackets); } catch (AssertionFailedError afe) { assertEquals("c2, c1", entityWithoutBrackets); } } public void testCookieSortedSet() throws Exception { final Request request = createGetRequest("SortedSet"); request.getCookies().add(new Cookie("c", "c1")); request.getCookies().add(new Cookie("c", "c2")); request.getCookies().add(new Cookie("d", "c3")); final Response response = accessServer(request); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); assertEquals("c1, c2", entity.substring(1, entity.length() - 1)); } public void testWithDefault() throws IOException { Response response = get("withDefault", new Cookie("c", "value")); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("value", response.getEntity().getText()); response = get("withDefault", new Cookie("c", "sdfgdfg")); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("sdfgdfg", response.getEntity().getText()); response = get("withDefault"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("default", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/package-info.java0000664000175000017500000000311011757206352032507 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Tests for the services / resources in package * {@link org.restlet.ext.jaxrs.services.resource}. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops */ package org.restlet.test.jaxrs.services.tests; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MatrixParamTest.java0000664000175000017500000002326111757206352033261 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.MatrixParam; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.MatrixParamTestService; import org.restlet.test.jaxrs.services.resources.QueryParamTestService; /** * @author Stephan Koops * @see MatrixParamTestService * @see MatrixParam */ public class MatrixParamTest extends JaxRsTestCase { public void checkBothGiven(String subPath) throws IOException { Response response = get(subPath + ";firstname=Angela;lastname=Merkel"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Angela Merkel", response.getEntity().getText()); response = get(subPath + ";lastname=Merkel;firstname=Angela"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Angela Merkel", response.getEntity().getText()); } public void checkOneGiven(String subPath) throws IOException { Response response = get(subPath + ";firstname=Goofy"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Goofy null", response.getEntity().getText()); response = get(subPath + ";lastname=Goofy"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("null Goofy", response.getEntity().getText()); } @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(MatrixParamTestService.class); } }; return appConfig; } public void testA() throws IOException { checkBothGiven("a"); checkOneGiven("a"); } public void testB() throws IOException { checkBothGiven("b"); checkOneGiven("b"); } public void testCheckUnmodifiable() { Response response = get("checkUnmodifiable"); assertTrue( "The List annotated with @MatrixParam seems to be modifiable", response.getStatus().isSuccess()); } public void testDecoded() throws IOException { final Response response = get("b;firstname=George%20U.;lastname=Bush"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("George U. Bush", response.getEntity().getText()); } /** @see MatrixParamTestService#encoded(String, String) */ public void testEncoded() throws IOException { final Response response = get("encoded;firstname=George%20U.;lastname=Bush"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("George%20U. Bush", response.getEntity().getText()); } public void testOne1() throws Exception { final Response response = get("one;name"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[empty]", response.getEntity().getText()); } public void testOne2() throws Exception { final Response response = get("one;name="); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[empty]", response.getEntity().getText()); } public void testOne3() throws Exception { final Response response = get("one;name=x"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("x", response.getEntity().getText()); } public void testOne4() throws Exception { final Response response = get("one;name2=sdf"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[null]", response.getEntity().getText()); } public void testSemicolon() { final Response response1 = get("semicolon"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response1.getStatus()); sysOutEntityIfError(response1); final Response response2 = get("semicolon;mpA=6"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response2.getStatus()); sysOutEntityIfError(response2); final Response response3 = get("semicolon;mpB=6"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response3.getStatus()); sysOutEntityIfError(response3); final Response response4 = get("semicolon;mpB=6;mpA=5"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response4.getStatus()); sysOutEntityIfError(response4); final Response response5 = get("semicolon;mpA=5;mpB=6"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response5.getStatus()); sysOutEntityIfError(response5); } /** @see QueryParamTestService#getDecoded() */ public void testSetterDecoded() throws Exception { final Response response1 = get(";decoded=abc/setterDecoded"); sysOutEntityIfError(response1); assertEquals(Status.SUCCESS_OK, response1.getStatus()); assertEquals("abc", response1.getEntity().getText()); final Response response2 = get(";decoded=%20/setterDecoded"); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); assertEquals(" ", response2.getEntity().getText()); } /** @see QueryParamTestService#getEncoded() */ public void testSetterEncoded() throws Exception { final Response response1 = get(";encoded=abc/setterEncoded"); sysOutEntityIfError(response1); assertEquals(Status.SUCCESS_OK, response1.getStatus()); assertEquals("abc", response1.getEntity().getText()); final Response response2 = get(";encoded=%20/setterEncoded"); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); assertEquals("%20", response2.getEntity().getText()); } public void testSub1() throws Exception { final Response response2 = get("sub;name=abc/one"); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); assertEquals("abc", response2.getEntity().getText()); final Response response3 = get("sub/one;name=def"); sysOutEntityIfError(response3); assertEquals(Status.SUCCESS_OK, response3.getStatus()); assertEquals("def", response3.getEntity().getText()); final Response response4 = get("sub;name=abc/one;name=def"); sysOutEntityIfError(response4); assertEquals(Status.SUCCESS_OK, response4.getStatus()); assertEquals("def", response4.getEntity().getText()); final Response response5 = get("sub;name=abc/allNames;name=def"); sysOutEntityIfError(response5); assertEquals(Status.SUCCESS_OK, response5.getStatus()); assertEquals("[abc, def]", response5.getEntity().getText()); final Response response6 = get("allNames;name=abc"); sysOutEntityIfError(response6); assertEquals(Status.SUCCESS_OK, response6.getStatus()); assertEquals("[abc]", response6.getEntity().getText()); } public void testWithDefault() throws IOException { Response response = get("withDefault;mp=abcde"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abcde", response.getEntity().getText()); response = get("withDefault;mp="); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[empty]", response.getEntity().getText()); response = get("withDefault"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("default", response.getEntity().getText()); } public void testWithoutDefault() throws IOException { Response response = get("withoutDefault;mp=abcde"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abcde", response.getEntity().getText()); response = get("withoutDefault;mp="); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[empty]", response.getEntity().getText()); response = get("withoutDefault"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[null]", response.getEntity().getText()); } public void testWithoutPath() throws Exception { checkBothGiven(""); checkOneGiven(""); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/QueryParamTest.java0000664000175000017500000002552311757206352033125 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.QueryParamTestService; /** * @author Stephan Koops * @see QueryParamTestService */ public class QueryParamTest extends JaxRsTestCase { public void checkBothGiven(String subPath) throws IOException { Response response = get(subPath + "?firstname=Angela&lastname=Merkel"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Angela Merkel", response.getEntity().getText()); response = get(subPath + "?lastname=Merkel&firstname=Angela"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Angela Merkel", response.getEntity().getText()); } /** * @param relPath * @param res0 * @param res1 * @param res2 * @throws IOException */ private void checkMult(String relPath, String res0, String res1, String res2) throws IOException { Response response = get(relPath); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(res0, response.getEntity().getText()); response = get(relPath + "?qp=1"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(res1, response.getEntity().getText()); response = get(relPath + "?qp=1&qp=2"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(res2, response.getEntity().getText()); } public void checkOneGiven(String subPath) throws IOException { Response response = get(subPath + "?firstname=Goofy"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Goofy null", response.getEntity().getText()); response = get(subPath + "?lastname=Goofy"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("null Goofy", response.getEntity().getText()); } @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(QueryParamTestService.class); } }; return appConfig; } public void testA() throws IOException { checkBothGiven("a"); checkOneGiven("a"); } public void testCheckUnmodifiable() { final Response response = get("checkUnmodifiable"); assertTrue( "The List annotated with @QueryParam must not be modifiable", response.getStatus().isSuccess()); } public void testDecoded() throws IOException { final Response response = get("qpDecoded?firstname=George%20U.&lastname=Bush"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("George U. Bush", response.getEntity().getText()); } public void testEncodedA() throws IOException { final Response response = get("encodedA?firstname=George%20U.&lastname=Bush"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("George%20U. Bush", response.getEntity().getText()); } /** @see QueryParamTestService#getDecoded() */ public void testFieldDecoded() throws Exception { final Response response1 = get("decoded?decoded=abc"); sysOutEntityIfError(response1); assertEquals(Status.SUCCESS_OK, response1.getStatus()); assertEquals("abc", response1.getEntity().getText()); final Response response2 = get("decoded?decoded=%20"); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); assertEquals(" ", response2.getEntity().getText()); } /** @see QueryParamTestService#getEncoded() */ public void testFieldEncoded() throws Exception { final Response response1 = get("encoded?encoded=abc"); sysOutEntityIfError(response1); assertEquals(Status.SUCCESS_OK, response1.getStatus()); assertEquals("abc", response1.getEntity().getText()); final Response response2 = get("encoded?encoded=%20"); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); assertEquals("%20", response2.getEntity().getText()); } /** * @see QueryParamTestService#getInt(int, int, int) */ public void testInt() throws Exception { final Response response1 = get("int?n1=1&n2=2&n3=3"); sysOutEntityIfError(response1); assertEquals(Status.SUCCESS_OK, response1.getStatus()); assertEquals("1 2 3", response1.getEntity().getText()); final Response response2 = get("int?n1=1&n2=2"); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); assertEquals("1 2 99", response2.getEntity().getText()); final Response response5 = get("int?n2=2&n3=3"); sysOutEntityIfError(response5); assertEquals(Status.SUCCESS_OK, response5.getStatus()); assertEquals("0 2 3", response5.getEntity().getText()); final Response response4 = get("int?n1=1&n2=2&n3="); sysOutEntityIfError(response4); assertEquals(Status.SUCCESS_OK, response4.getStatus()); assertEquals("1 2 99", response4.getEntity().getText()); final Response response6 = get("int?n1=1&n3=3"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response6.getStatus()); final Response response3 = get("int?n1=1&n2=2&n3"); sysOutEntityIfError(response3); assertEquals(Status.SUCCESS_OK, response3.getStatus()); assertEquals("1 2 99", response3.getEntity().getText()); } /** * @see QueryParamTestService#getInteger(Integer, Integer, Integer) */ public void testInteger() throws Exception { final Response response1 = get("Integer?n1=1&n2=2&n3=3"); sysOutEntityIfError(response1); assertEquals(Status.SUCCESS_OK, response1.getStatus()); assertEquals("1 2 3", response1.getEntity().getText()); final Response response2 = get("Integer?n1=1&n2=2"); sysOutEntityIfError(response2); assertEquals(Status.SUCCESS_OK, response2.getStatus()); assertEquals("1 2 99", response2.getEntity().getText()); final Response response5 = get("Integer?n2=2&n3=3"); sysOutEntityIfError(response5); assertEquals(Status.SUCCESS_OK, response5.getStatus()); assertEquals("null 2 3", response5.getEntity().getText()); final Response response4 = get("Integer?n1=1&n2=2&n3="); sysOutEntityIfError(response4); assertEquals(Status.SUCCESS_OK, response4.getStatus()); assertEquals("1 2 99", response4.getEntity().getText()); final Response response6 = get("Integer?n1=1&n3=3"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response6.getStatus()); final Response response3 = get("Integer?n1=1&n2=2&n3"); sysOutEntityIfError(response3); assertEquals(Status.SUCCESS_OK, response3.getStatus()); assertEquals("1 2 99", response3.getEntity().getText()); } public void testMult1() throws Exception { checkMult("array", "[null]", "[1]", "[1, 2]"); checkMult("arrayWithDefault", "[qv]", "[1]", "[1, 2]"); checkMult("list", "[null]", "[1]", "[1, 2]"); checkMult("listWithDefault", "[qv]", "[1]", "[1, 2]"); } public void testOne1() throws Exception { final Response response = get("one?name"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[empty]", response.getEntity().getText()); } public void testOne2() throws Exception { final Response response = get("one?name="); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[empty]", response.getEntity().getText()); } public void testOne3() throws Exception { final Response response = get("one?name=x"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("x", response.getEntity().getText()); } public void testOne4() throws Exception { final Response response = get("one?name2=sdf"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[null]", response.getEntity().getText()); } public void testQpDecoded() throws IOException { checkBothGiven("qpDecoded"); checkOneGiven("qpDecoded"); } public void testQpEncoded() throws IOException { Response response = get("qpEncoded?firstname=George%20U.&lastname=Bush"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("George%20U. Bush", response.getEntity().getText()); response = get("qpEncoded?lastname=Bush&firstname=George%20U."); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("George%20U. Bush", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MatrixParamTest2.java0000664000175000017500000000662011757206352033343 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.MatrixParam; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.MatrixParamTestService2; /** * @author Stephan Koops * @see MatrixParamTestService2 * @see MatrixParam */ public class MatrixParamTest2 extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(MatrixParamTestService2.class); } }; } public void testEncodedWithDefault() throws Exception { Response response = get("encodedWithDefault;m=1;m=2;x=3"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[1, 2]", response.getEntity().getText()); response = get("encodedWithDefault;m=1;i=2;x=3"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[1]", response.getEntity().getText()); response = get("encodedWithDefault;a=1;i=2;x=3"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[default]", response.getEntity().getText()); } public void testWithoutPath() throws Exception { Response response = get(";firstname=Angela;lastname=Merkel"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Angela Merkel", response.getEntity().getText()); response = get(";lastname=Merkel;firstname=Angela"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Angela Merkel", response.getEntity().getText()); response = get(";firstname=Goofy"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("Goofy null", response.getEntity().getText()); response = get(";lastname=Goofy"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("null Goofy", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ContextsTest.java0000664000175000017500000000562311757206352032645 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.ContextsTestService; /** * @author Stephan Koops * @see ContextsTestService */ public class ContextsTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(ContextsTestService.class); } }; } public void testFields() throws Exception { final Response response = get("fields"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); assertEquals("providers\nuriInfo\n", entity); } public void testLastPathSegm() throws Exception { final Response response = get("lastPathSegm;a=b;c=d;c=e"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); // final String entity = response.getEntity().getText(); // LATER assertEquals("a : [b]\nc : [d, e]\n", entity); } public void testParams() throws Exception { final Response response = get("params"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); assertEquals("providers\nuriInfo\n", entity); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JsonTest.java0000664000175000017500000001427211757206352031747 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import junit.framework.AssertionFailedError; import org.json.JSONException; import org.json.JSONObject; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.ext.jackson.JacksonConverter; import org.restlet.ext.jaxb.JaxbRepresentation; import org.restlet.ext.jaxrs.JaxRsApplication; import org.restlet.ext.jaxrs.internal.provider.JsonProvider; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.resources.JsonTestService; /** * @author Stephan Koops * @see JsonTestService * @see JsonProvider * @see JSONObject */ public class JsonTest extends JaxRsTestCase { public static void main(String[] args) throws Exception { new JsonTest().runServerUntilKeyPressed(); } /** * @param response * @throws JSONException * @throws IOException */ private void checkJsonResponse(Response response) throws JSONException, IOException { sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); JSONObject jsonObject = new JSONObject(response.getEntity().getText()); assertEquals("Angela", jsonObject.get("firstname")); assertEquals("Merkel", jsonObject.get("lastname")); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(JsonTestService.class); } }; } @Override protected void modifyApplication(JaxRsApplication app) { app.getTunnelService().setExtensionsTunnel(true); } @Override protected void setUp() throws Exception { super.setUp(); // Explicitely promote the Jackson converter Engine.getInstance().getRegisteredConverters() .add(0, new JacksonConverter()); } public void testGetJsonObject() throws Exception { final Response response = get("JSONObject"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); try { assertEquals("{\"name1\":\"value1\",\"name2\":\"value2\"}", entity); } catch (AssertionFailedError afe) { assertEquals("{\"name2\":\"value2\",\"name1\":\"value1\"}", entity); } } public void testGetPersonJson() throws Exception { Response response = get("person?firstname=Angela&lastname=Merkel", MediaType.APPLICATION_JSON); checkJsonResponse(response); response = get("person.json?firstname=Angela&lastname=Merkel", MediaType.TEXT_XML); checkJsonResponse(response); response = get("person.json?firstname=Angela&lastname=Merkel", MediaType.IMAGE_GIF); checkJsonResponse(response); } /** * This test using JAXB, but shows that you can serialize Objects by JAXb * and by JSON. * * @param xmlMediaType * @throws IOException */ private void testGetPersonXml(MediaType xmlMediaType) throws IOException { final Response response = get( "person?firstname=Angela&lastname=Merkel", xmlMediaType); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final JaxbRepresentation jaxbReprs = new JaxbRepresentation( response.getEntity(), Person.class); final Person person = jaxbReprs.getObject(); assertEquals("Angela", person.getFirstname()); assertEquals("Merkel", person.getLastname()); } public void testGetPersonXmlA() throws Exception { testGetPersonXml(MediaType.APPLICATION_XML); } public void testGetPersonXmlT() throws Exception { testGetPersonXml(MediaType.TEXT_XML); } public void testPost() throws Exception { final Representation entity = new StringRepresentation("{name:value}", MediaType.APPLICATION_JSON); final Response response = post("JSONObject", entity); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("value", response.getEntity().getText()); } /** * @see JsonTestService#getString() */ public void testString() throws Exception { final Response response = get("String"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEquals("{name:value}", entity.getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MatchedTest.java0000664000175000017500000001312511757206352032377 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.MatchedTestService; /** * @author Stephan Koops * @see MatchedTestService */ public class MatchedTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(MatchedTestService.class); } }; } public void testGet() throws Exception { final Response response = get(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1\n1", response.getEntity().getText()); } public void testGetSub() throws Exception { final Response response = get("sub"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("2\n2", response.getEntity().getText()); } public void testGetSubSameSub() throws Exception { final Response response = get("sub/sameSub"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("3\n3", response.getEntity().getText()); } public void testGetSubSub() throws Exception { final Response response = get("sub/sub"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("3\n3", response.getEntity().getText()); } public void testResourceClassNames() throws Exception { final Response response = get("resourceClassNames"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals( "2\norg.restlet.test.jaxrs.services.resources.MatchedTestService\norg.restlet.test.jaxrs.services.resources.MatchedTestService", response.getEntity().getText()); } public void testSameSubSubUri() throws Exception { final Response response = get("sameSub/sub/uris"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("4" + "\n/matchedTest/sameSub/sub/uris" + "\n/matchedTest/sameSub/sub" + "\n/matchedTest/sameSub" + "\n/matchedTest", response.getEntity().getText()); } public void testUri() throws Exception { final Response response = get("uris"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("2\n/matchedTest/uris\n/matchedTest", response.getEntity() .getText()); } /** * @see MatchedTestService#getUriInfoAttribute(javax.ws.rs.core.UriInfo, * String) */ public void testUriInfos() throws Exception { final Response response404 = get("uriInfo/abc"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response404.getStatus()); final Response response = get("uriInfo/matchedURIs"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); final String expected = "[]\n[/matchedTest/uriInfo/matchedURIs, /matchedTest]"; System.out.println("expected:\n" + expected + "\ngot:\n" + entity); assertEquals(expected, entity); } /** * @see MatchedTestService#getUriInfoAttribute(javax.ws.rs.core.UriInfo, * String) */ public void testUriInfosSub() throws Exception { final Response response404 = get("sub/uriInfo/abc"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response404.getStatus()); final Response response = get("sub/uriInfo/matchedURIs"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String entity = response.getEntity().getText(); final String expected = "[]\n[/matchedTest/sub/uriInfo/matchedURIs, /matchedTest/sub, /matchedTest]"; System.out.println("expected:\n" + expected + "\ngot:\n" + entity); assertEquals(expected, entity); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RepresentationTest.java0000664000175000017500000001044011757206352034031 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.resources.RepresentationTestService; /** * @author Stephan Koops * @see RepresentationTestService */ public class RepresentationTest extends JaxRsTestCase { @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(RepresentationTestService.class); } }; return appConfig; } /** @throws IOException * @see RepresentationTestService#post(Representation) */ public void testDecodePost() throws IOException { final Representation repr = new StringRepresentation("abcde"); final Response response = post("reprDecode", repr); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abcde", response.getEntity().getText()); } /** @throws IOException * @see RepresentationTestService#postJaxb(org.restlet.ext.jaxb.JaxbRepresentation) */ public void testJaxbPost() throws IOException { final Response response = post("jaxb", (Representation) null); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); assertEquals(null, response.getEntity().getText()); } /** @see RepresentationTestService#get() */ public void testReprGet() { final Response response = get("repr"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); } /** @throws IOException * @see RepresentationTestService#postJaxb(org.restlet.ext.jaxb.JaxbRepresentation) */ public void testReprPost() throws IOException { Response response = post("jaxb", new StringRepresentation("abcdef")); assertEquals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE, response .getStatus()); response = post("jaxb", new StringRepresentation( "", MediaType.APPLICATION_XML)); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); String packageName = Person.class.getPackage().getName(); assertEquals(packageName, response.getEntity().getText()); } /** @see RepresentationTestService#getString() */ public void testStringGet() { final Response response = get("reprString"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ContextResolverTest.java0000664000175000017500000000615211757206354034204 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.providers.ContextResolverTestWriter; import org.restlet.test.jaxrs.services.providers.TestContextResolver; import org.restlet.test.jaxrs.services.resources.ContextResolverTestResource; import org.restlet.test.jaxrs.util.TestUtils; /** * @author Stephan Koops * @see ContextResolverTestResource */ public class ContextResolverTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(ContextResolverTestResource.class); } @Override public Set getSingletons() { return TestUtils.createSet(new ContextResolverTestWriter(), new TestContextResolver()); } }; } /** * @throws Exception * @see ContextResolverTestResource#getHomeUri() * @see TestContextResolver */ public void test1() throws Exception { final Response response = get(MediaType.TEXT_HTML); final String entity = response.getEntity().getText(); System.out.println(entity); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_HTML, response.getEntity() .getMediaType()); assertEquals( "\nThe virtual presence of Helmut Kohl is: http://www.restlet.org/persons/Kohl/Helmut", entity); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/Issue594Test.java0000664000175000017500000001127511757206352032370 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.Issue594Resources; /** * @author Stephan Koops * @see Issue594Resources */ public class Issue594Test extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(Issue594Resources.class); } }; } /** * This tests, if a sub resource class of a sub resource class of a root * resource class is accessable. * * @throws Exception */ public void testGetRoot() throws Exception { final Response response = get(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("root", entity.getText()); } public void testGetRepository() throws Exception { final Response response = get("PRJ"); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("project=PRJ", entity.getText()); } public void testGetProject() throws Exception { final Response response = get("PRJ/REPO"); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("project=PRJ\nrepository=REPO", entity.getText()); } public void testGetSchemaDir() throws Exception { final Response response = get("PRJ/REPO/schema"); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("project=PRJ\nrepository=REPO\nschema", entity .getText()); } public void testGetSchema() throws Exception { final Response response = get("PRJ/REPO/schema/SCM"); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("project=PRJ\nrepository=REPO\nschema\nschema=SCM", entity.getText()); } public void testFooBarSimple() throws Exception { final Response response = get("/foo/bar/schema/simple"); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_PLAIN, entity.getMediaType()); assertEquals("project=foo\nrepository=bar\nschema\nschema=simple", entity.getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java0000664000175000017500000003324411757206352032466 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import javax.ws.rs.core.Application; import javax.ws.rs.core.Request; import org.restlet.Response; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Dimension; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Status; import org.restlet.data.Tag; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.test.jaxrs.services.resources.RequestService; import org.restlet.test.jaxrs.util.TestUtils; /** * This test class checks if the Request.evaluatePreconditions methods works * fine. * * @author Stephan Koops * @see RequestService * @see Request * @see CallContext */ public class RequestTest extends JaxRsTestCase { /** * After than 2009-01-08, 12h * * @see EvaluatePreconditionService#getLastModificationDateFromDatastore() */ @SuppressWarnings("deprecation") public static final Date AFTER = new Date(2009 - 1900, 0, 9); // 2009-01-09 /** * Before 2009-01-08, 12h * * @see EvaluatePreconditionService#getLastModificationDateFromDatastore() */ @SuppressWarnings("deprecation") public static final Date BEFORE = new Date(2007 - 1900, 11, 31); // 2007-12-31 private static final Status PREC_FAILED = Status.CLIENT_ERROR_PRECONDITION_FAILED; /** * @param modifiedSince * @param entityTag * @return */ private static Conditions createConditions(Date modifiedSince, Tag entityTag) { final Conditions conditions = new Conditions(); conditions.setModifiedSince(modifiedSince); conditions.setMatch(TestUtils.createList(entityTag)); return conditions; } public static void main(String[] args) throws Exception { new RequestTest().runServerUntilKeyPressed(); } /** * @return */ @SuppressWarnings("all") private Tag getDatastoreETag() { return org.restlet.ext.jaxrs.internal.util.Converter .toRestletTag(RequestService.getEntityTagFromDatastore()); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(RequestService.class); } }; } public void testDateAndEntityTag1Get() throws Exception { final Conditions cond = createConditions(BEFORE, getDatastoreETag()); final Response response = get("date", cond); assertEquals(Status.SUCCESS_OK, response.getStatus()); } /** * @see RequestService#put(Request) */ public void testDateAndEntityTag1Put() throws Exception { final Conditions cond = createConditions(BEFORE, getDatastoreETag()); final Response response = put("date", null, cond); assertEquals(Status.SUCCESS_OK, response.getStatus()); } public void testDateAndEntityTag2Get() throws Exception { final Conditions conditions = createConditions(AFTER, getDatastoreETag()); final Response response = get("date", conditions); assertEquals(Status.REDIRECTION_NOT_MODIFIED, response.getStatus()); } public void testDateAndEntityTag2Put() throws Exception { final Conditions conditions = createConditions(AFTER, getDatastoreETag()); final Response response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testDateAndEntityTag3Get() throws Exception { final Conditions conditions = createConditions(BEFORE, new Tag( "shkhsdk")); final Response response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testDateAndEntityTag3Put() throws Exception { final Conditions conditions = createConditions(BEFORE, new Tag( "shkhsdk")); final Response response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testDateAndEntityTag4Get() throws Exception { final Conditions conditions = createConditions(AFTER, new Tag("shkhsdk")); final Response response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testDateAndEntityTag4Put() throws Exception { final Conditions conditions = createConditions(AFTER, new Tag("shkhsdk")); final Response response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testGetDateNotModified() throws Exception { final Conditions conditions = new Conditions(); conditions.setModifiedSince(AFTER); final Response response = get("date", conditions); assertEquals(Status.REDIRECTION_NOT_MODIFIED, response.getStatus()); assertFalse(response.isEntityAvailable() && response.getEntity().getSize() != 0); // from RFC 2616, Section 10.3.5 // The 304 response MUST include the following header fields: // - ETag and/or Content-Location, if the header would have been sent // in a 200 response to the same request // - Expires, Cache-Control, and/or Vary, if the field-value might // differ from that sent in any previous response for the same // variant } public void testGetEntityTagMatch() throws Exception { Conditions conditions = new Conditions(); conditions.setMatch(TestUtils.createList(getDatastoreETag())); Response response = get("date", conditions); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(RequestService.getLastModificationDateFromDatastore(), response.getEntity().getModificationDate()); assertEquals(getDatastoreETag(), response.getEntity().getTag()); assertNotNull(response.getEntity().getText()); assertTrue(response.getEntity().getSize() > 0); conditions = new Conditions(); conditions.setMatch(TestUtils.createList(new Tag("affer"))); response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testGetEntityTagNoneMatch() throws Exception { Conditions conditions = new Conditions(); conditions.setNoneMatch(TestUtils.createList(getDatastoreETag())); Response response = get("date", conditions); assertEquals(Status.REDIRECTION_NOT_MODIFIED, response.getStatus()); conditions = new Conditions(); conditions.setNoneMatch(TestUtils.createList(new Tag("affer"))); response = get("date", conditions); assertEquals(Status.SUCCESS_OK, response.getStatus()); } /** * @see RequestService#getLastModificationDateFromDatastore() * @throws Exception */ public void testGetModifiedSince() throws Exception { Conditions conditions = new Conditions(); conditions.setModifiedSince(BEFORE); Response response = get("date", conditions); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(RequestService.getLastModificationDateFromDatastore(), response.getEntity().getModificationDate()); assertEquals(getDatastoreETag(), response.getEntity().getTag()); assertNotNull(response.getEntity().getText()); assertTrue(response.getEntity().getSize() > 0); conditions = new Conditions(); conditions.setModifiedSince(AFTER); response = get("date", conditions); assertEquals(Status.REDIRECTION_NOT_MODIFIED, response.getStatus()); assertEquals(RequestService.getLastModificationDateFromDatastore(), response.getEntity().getModificationDate()); assertEquals(getDatastoreETag(), response.getEntity().getTag()); assertEquals(0, response.getEntity().getSize()); } public void testGetUnmodifiedSince() throws Exception { Conditions conditions = new Conditions(); conditions.setUnmodifiedSince(AFTER); Response response = get("date", conditions); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(RequestService.getLastModificationDateFromDatastore(), response.getEntity().getModificationDate()); assertEquals(getDatastoreETag(), response.getEntity().getTag()); assertNotNull(response.getEntity().getText()); assertTrue(response.getEntity().getSize() > 0); conditions = new Conditions(); conditions.setUnmodifiedSince(BEFORE); response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); // NICE testen, was bei ungueltigem Datum passiert: // If-Unmodified-Since-Header ignorieren. } public void testOptions() { final Response response = options(); final Set allowedMethods = response.getAllowedMethods(); assertEquals(3, allowedMethods.size()); assertTrue("allowedOptions must contain ABC", allowedMethods .contains(Method.valueOf("ABC"))); assertTrue("allowedOptions must contain DEF", allowedMethods .contains(Method.valueOf("DEF"))); assertTrue("allowedOptions must contain GHI", allowedMethods .contains(Method.valueOf("GHI"))); assertEquals(3, allowedMethods.size()); } /** * @see RequestService#getLastModificationDateFromDatastore() * @throws Exception */ public void testPutModifiedSince() throws Exception { Conditions conditions = new Conditions(); conditions.setModifiedSince(BEFORE); Response response = put("date", null, conditions); assertEquals(Status.SUCCESS_OK, response.getStatus()); conditions = new Conditions(); conditions.setModifiedSince(AFTER); response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testPutUnmodifiedSince() throws Exception { Conditions conditions = new Conditions(); conditions.setUnmodifiedSince(AFTER); Response response = put("date", null, conditions); assertEquals(Status.SUCCESS_OK, response.getStatus()); conditions = new Conditions(); conditions.setUnmodifiedSince(BEFORE); response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); } public void testSelectVariant() { final ClientInfo clientInfo = new ClientInfo(); final List> accLangs = clientInfo .getAcceptedLanguages(); accLangs.add(new Preference(Language.SPANISH, 1f)); accLangs.add(new Preference(new Language("de"), 0.8f)); clientInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML, 0.5f)); Response response = get("selectVariants", clientInfo); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(MediaType.TEXT_HTML, response.getEntity() .getMediaType()); assertEquals(new Language("de"), TestUtils.getOnlyElement(response .getEntity().getLanguages())); assertTrue("dimensions must contain " + Dimension.MEDIA_TYPE, response .getDimensions().contains(Dimension.MEDIA_TYPE)); assertTrue("dimensions must contain " + Dimension.LANGUAGE, response .getDimensions().contains(Dimension.LANGUAGE)); clientInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN, 1f)); response = get("selectVariants", clientInfo); assertEqualMediaType(MediaType.TEXT_PLAIN, response.getEntity() .getMediaType()); assertEquals(new Language("de"), TestUtils.getOnlyElement(response .getEntity().getLanguages())); accLangs.add(new Preference(Language.ENGLISH, 0.9f)); response = get("selectVariants", clientInfo); assertEqualMediaType(MediaType.TEXT_PLAIN, response.getEntity() .getMediaType()); assertEquals(Language.ENGLISH, TestUtils.getOnlyElement(response .getEntity().getLanguages())); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/PrimitiveWrapperEntityTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/PrimitiveWrapperEntityTest0000664000175000017500000001144111757206352034617 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.StringRepresentation; import org.restlet.test.jaxrs.services.providers.BooleanEntityProvider; import org.restlet.test.jaxrs.services.providers.CharacterEntityProvider; import org.restlet.test.jaxrs.services.providers.IntegerEntityProvider; import org.restlet.test.jaxrs.services.resources.PrimitiveWrapperEntityResource; import org.restlet.test.jaxrs.util.TestUtils; /** * @author Stephan Koops * @see PrimitiveWrapperEntityResource */ public class PrimitiveWrapperEntityTest extends JaxRsTestCase { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected Application getApplication() { final Application appConfig = new Application() { @Override public Set getSingletons() { return (Set) TestUtils.createSet(new IntegerEntityProvider(), new CharacterEntityProvider(), new BooleanEntityProvider()); } @Override public Set> getClasses() { return (Set) Collections.singleton(PrimitiveWrapperEntityResource.class); } }; return appConfig; } public void test1() throws Exception { final Response response = put("intReturnInt", new StringRepresentation( "47")); sysOutEntityIfError(response); assertEquals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE, response .getStatus()); } /** * @see PrimitiveWrapperEntityResource#charReturnCharacter(char) */ public void test2() throws Exception { final Response response = put("charReturnCharacter", new StringRepresentation("x")); sysOutEntityIfError(response); assertEquals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE, response .getStatus()); } /** * @see PrimitiveWrapperEntityResource#BooleanReturnboolean(Boolean) */ public void test3() throws Exception { Response response = put("BooleanReturnboolean", new StringRepresentation("true")); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("true", response.getEntity().getText()); response = put("BooleanReturnboolean", null); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); if (response.getEntity() != null) { assertEquals("false", response.getEntity().getText()); } } public void test4() throws Exception { Response response = put("integerReturnInteger", new StringRepresentation("47")); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("47", response.getEntity().getText()); response = put("integerReturnInteger", null); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); assertEmptyEntity(response); } public void test5() throws Exception { Response response = put("byteArrayReturnByteArray", new StringRepresentation("test", (MediaType) null)); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("test", response.getEntity().getText()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/UriBuilderByServiceTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/UriBuilderByServiceTest.ja0000664000175000017500000001234111757206352034364 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import static org.restlet.data.MediaType.TEXT_HTML; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.UriBuilderTestResource; /** * @author Stephan Koops * @see UriBuilderTestResource * @see ExtendedUriBuilderByServiceTest */ public class UriBuilderByServiceTest extends JaxRsTestCase { /** * @param baseReference * {@link #createBaseRef()} */ static void assertBaseUriAndMediaType(MediaType expectedMT, Response response, boolean checkEntityText, String baseRef) throws IOException { sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEqualMediaType(expectedMT, entity); if (checkEntityText) { while (baseRef.endsWith("/")) baseRef = baseRef.substring(0, baseRef.length() - 1); String entityRef = entity.getText(); while (entityRef.endsWith("/")) entityRef = baseRef.substring(0, entityRef.length() - 1); assertEquals(baseRef, entityRef); } } /** * @param reference * {@link #createReference(String)} */ static void assertUriAndMediaType(MediaType expectedMT, Response response, boolean checkEntityText, String reference) throws IOException { sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final Representation entity = response.getEntity(); assertEqualMediaType(expectedMT, entity.getMediaType()); if (checkEntityText) { assertEquals(reference.toString(), entity.getText()); } } private void assertBaseUriAndMediaType(MediaType expectedMT, Response response, boolean checkEntityText) throws IOException { assertBaseUriAndMediaType(expectedMT, response, checkEntityText, createBaseRef().toString()); } private void assertUriAndMediaType(String expectedSubPath, MediaType expectedMT, Response response, boolean checkEntityText) throws IOException { assertUriAndMediaType(expectedMT, response, checkEntityText, createReference(expectedSubPath).toString()); } @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections .singleton(UriBuilderTestResource.class); } }; return appConfig; } public void testAbsoluteGet() throws Exception { Response response = get("absolute", TEXT_HTML); assertUriAndMediaType("absolute", TEXT_HTML, response, true); } public void testAbsoluteHead() throws Exception { Response response = head("absolute", TEXT_HTML); assertUriAndMediaType("absolute", TEXT_HTML, response, false); } public void testAbsolutePost() throws Exception { Response response = post("absolute", TEXT_HTML); assertUriAndMediaType("absolute", TEXT_HTML, response, true); } public void testBaseGet() throws Exception { Response response = get("base", TEXT_HTML); assertBaseUriAndMediaType(TEXT_HTML, response, true); } public void testBaseHead() throws Exception { Response response = head("base", TEXT_HTML); assertBaseUriAndMediaType(TEXT_HTML, response, false); } public void testBasePost() throws Exception { Response response = post("base", TEXT_HTML); assertBaseUriAndMediaType(TEXT_HTML, response, true); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MultipleResourcesTest.java0000664000175000017500000000541011757206352034516 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.test.jaxrs.services.car.CarListResource; import org.restlet.test.jaxrs.services.resources.SimpleTrain; import org.restlet.test.jaxrs.util.TestUtils; /** * @author Stephan Koops * @see SimpleTrainTest * @see CarTest */ public class MultipleResourcesTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings("unchecked") public Set> getClasses() { return TestUtils.createSet(SimpleTrain.class, CarListResource.class); } }; } @Override public void setUp() throws Exception { super.setUp(); } public void testCar() throws Exception { final CarTest carTest = new CarTest(); carTest.setServerWrapper(getServerWrapper()); carTest.testGetPlainText(); carTest.testGetHtmlText(); carTest.testDelete(); carTest.testGetCar(); carTest.testGetOffers(); } public void testSimpleTrain() throws Exception { final SimpleTrainTest simpleTrainTest = new SimpleTrainTest(); simpleTrainTest.setServerWrapper(getServerWrapper()); simpleTrainTest.testGetPlainText(); simpleTrainTest.testGetHtmlText(); simpleTrainTest.testGetTextAll(); simpleTrainTest.testGetTextMultiple1(); simpleTrainTest.testGetTextMultiple2(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AppPlusXmlTest.java0000664000175000017500000000636411757206352033106 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import junit.framework.AssertionFailedError; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.AppPlusXmlResource; /** * @author Stephan Koops * @see AppPlusXmlResource */ public class AppPlusXmlTest extends JaxRsTestCase { private static final MediaType APP_PERSON_XML = new MediaType( "application/Person+xml"); private void getAndCheck(MediaType mt) { final Response response = get(mt); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final MediaType mediaType = response.getEntity().getMediaType(); assertEqualMediaType(mt, mediaType); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(AppPlusXmlResource.class); } }; } public void testGet() throws Exception { final Response response = get(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); final MediaType mediaType = response.getEntity().getMediaType(); try { assertEqualMediaType(MediaType.TEXT_XML, mediaType); } catch (AssertionFailedError afe) { try { assertEqualMediaType(MediaType.APPLICATION_XML, mediaType); } catch (AssertionFailedError afe2) { assertEqualMediaType(APP_PERSON_XML, mediaType); } } } /** * @see AppPlusXmlResource#getPerson() */ public void testGet2() throws Exception { getAndCheck(MediaType.TEXT_XML); getAndCheck(MediaType.APPLICATION_XML); getAndCheck(APP_PERSON_XML); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/GenericTypeTestCase.java0000664000175000017500000000515411757206354034051 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.providers.GenericTypeMBW; import org.restlet.test.jaxrs.services.resources.GenericTypeResource; /** * @author Stephan Koops * @see GenericTypeResource * @see GenericTypeMBW */ public class GenericTypeTestCase extends JaxRsTestCase { protected Class getRootResourceClass() { return GenericTypeResource.class; } public void testGet() throws IOException { final Response response = get(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc\ndef\n", response.getEntity().getText()); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set getSingletons() { return (Set) Collections.singleton(new GenericTypeMBW()); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(GenericTypeResource.class); } }; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/OwnProviderTest.java0000664000175000017500000000553511757206352033316 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.providers.TextCrazyPersonProvider; import org.restlet.test.jaxrs.services.resources.OwnProviderTestService; import org.restlet.test.jaxrs.util.TestUtils; /** * @author Stephan Koops * @see TextCrazyPersonProvider * @see OwnProviderTestService */ public class OwnProviderTest extends JaxRsTestCase { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected Application getApplication() { final Application appConfig = new Application() { @Override public Set getSingletons() { return (Set) TestUtils.createSet(new TextCrazyPersonProvider()); } @Override public Set> getClasses() { return (Set) Collections.singleton(OwnProviderTestService.class); } }; return appConfig; } /** * @see OwnProviderTestService#get() */ public void test1() throws Exception { final Response response = get(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(new MediaType("text/crazy-person"), response); final String actualEntity = response.getEntity().getText(); final String expectedEntity = "abc def is crazy.\nHeader value for name h1 is h1v"; assertEquals(expectedEntity, actualEntity); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/FormTest.java0000664000175000017500000001235511757206352031741 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.resources.FormTestResource; /** * @author Stephan Koops * @see FormTestResource */ public class FormTest extends JaxRsTestCase { /** * @param subPath * @throws IOException */ private void check(String subPath, boolean cPerhapsDouble) throws IOException { check1(subPath); check2(subPath); check3(subPath, cPerhapsDouble); } /** * @param subPath * @return * @throws IOException */ private Representation check1(String subPath) throws IOException { Form form = new Form(); form.add("a", "b"); Representation webRepresentation = form.getWebRepresentation(); Response response = post(subPath, webRepresentation); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a -> b\n", response.getEntity().getText()); return webRepresentation; } /** * @param subPath * @throws IOException */ private void check2(String subPath) throws IOException { Response response; Form form = new Form(); form.add("a", "b"); form.add("c", "d"); response = post(subPath, form.getWebRepresentation()); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a -> b\nc -> d\n", response.getEntity().getText()); } /** * @param subPath * @param cDouble * the variable c is given double in the entity. If this * parameter is true, c must be returned double, if false, * then only once. * @throws IOException */ private void check3(String subPath, boolean cDouble) throws IOException { Response response; Form form = new Form(); form.add("a", "b"); form.add("c", "d"); form.add("c", "d2"); response = post(subPath, form.getWebRepresentation()); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); String expectedEntity = "a -> b\nc -> d\n"; if (cDouble) expectedEntity += "c -> d2\n"; assertEquals(expectedEntity, response.getEntity().getText()); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(FormTestResource.class); } @Override public Set getSingletons() { return Collections.emptySet(); } }; } /** @see FormTestResource#checkUnmodifiable(java.util.List) */ public void testCheckUnmodifiable() { Form form = new Form(); form.add("a", "b"); form.add("a", "c"); Response response = post("checkUnmodifiable", form .getWebRepresentation()); sysOutEntityIfError(response); assertTrue( "The List annotated with @FormParam must not be modifiable. Status is " + response.getStatus(), response.getStatus() .isSuccess()); } public void testFormAndParam() throws IOException { check("formAndParam", true); } public void testFormOnly() throws IOException { check("formOnly", true); } public void testParamAndForm() throws IOException { check("paramAndForm", true); } /** @see FormTestResource#paramOnly(String, String) */ public void testParamOnly() throws IOException { check("paramOnly", false); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JaxRsTestCase.java0000664000175000017500000005712611757206352032666 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.ws.rs.Path; import javax.ws.rs.core.Application; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Preference; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.jaxrs.JaxRsApplication; import org.restlet.ext.jaxrs.RoleChecker; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.representation.Representation; import org.restlet.security.Authenticator; import org.restlet.test.jaxrs.server.RestletServerTestCase; import org.restlet.test.jaxrs.util.OrderedReadonlySet; import org.restlet.test.jaxrs.util.TestUtils; /** * This class allows easy testing of JAX-RS implementations by starting a server * for a given class and access the server for a given sub pass relative to the * path of the root resource class. * * @author Stephan Koops */ @SuppressWarnings("all") public abstract class JaxRsTestCase extends RestletServerTestCase { /** * Checks, if the allowed methods of an OPTIONS {@link Response} are the * same as the expected. * * @param optionsResponse * @param methods * The methods that must be allowed. If GET is included, a check * for HEAD is automatically done. But it is no problem to add * the HEAD method in the parameters. */ public static void assertAllowedMethod(Response optionsResponse, Method... methods) { if (optionsResponse.getStatus().isError()) { assertEquals(Status.SUCCESS_OK, optionsResponse.getStatus()); } final Set expectedMethods = new HashSet( Arrays.asList(methods)); if (expectedMethods.contains(Method.GET)) { expectedMethods.add(Method.HEAD); } final List allowedMethods = new ArrayList( optionsResponse.getAllowedMethods()); for (final Method method : methods) { assertTrue("allowedMethod must contain " + method, allowedMethods.contains(method)); } assertEquals("allowedMethods.size invalid", expectedMethods.size(), allowedMethods.size()); } /** * Checks, if the entity of the Response is null or empty. * * @param response * @throws IOException */ public static void assertEmptyEntity(Response response) throws IOException { if (response.getEntity() != null) { assertEquals(null, response.getEntity().getText()); } } /** * Check, if the mainType and the subType of the actual MediaType is as * expected. The parameters are ignored. */ public static void assertEqualMediaType(MediaType expected, MediaType actual) { expected = Converter.getMediaTypeWithoutParams(expected); actual = Converter.getMediaTypeWithoutParams(actual); assertEquals(expected, actual); } /** * Check, if the mainType and the subType of the MediaType of the given * entity is as expected. The parameters of the MediaTypes are ignored. */ public static void assertEqualMediaType(MediaType expected, Representation actualEntity) { if (actualEntity == null) fail("The entity must not be null, if a media type should be read"); assertEqualMediaType(expected, actualEntity.getMediaType()); } /** * Check, if the mainType and the subType of the MediaType of the entity of * the given Response is as expected. The parameters of the MediaTypes are * ignored. */ public static void assertEqualMediaType(MediaType expected, Response actualResponse) { if (actualResponse == null) fail("The response must not be null, if an entity should be read"); assertEqualMediaType(expected, actualResponse.getEntity()); } /** * Creates a singleton Collection with the given MediaType as Preference. * * @param accMediaType * @param mediaTypeQuality * the default value is 1. */ public static Collection> createPrefColl( MediaType accMediaType, float mediaTypeQuality) { if (accMediaType == null) { return Collections.emptyList(); } return Collections.singleton(new Preference(accMediaType, mediaTypeQuality)); } /** * Some features are not ready and should only tested on the workspace of * the JAX-RS implementor, and if the actual date is after a given date. * This method checks this. * * Year is 2009 * * @param dayOfMonth * 1-31 * @param month * 1-12 * @return true, if this workspace seems not to be JAX-RS implementors * workspace. */ public static boolean jaxRxImplementorCheck(int dayOfMonth, int month) { return jaxRxImplementorCheck(dayOfMonth, month, 2009); } /** * @param dayOfMonth * 1-31 * @param month * 1-12 * @param year * e.g. 2009 * @return true, if this workspace seems not to be JAX-RS implementors * workspace. * @see #jaxRxImplementorAndAfter(int, int) */ public static boolean jaxRxImplementorCheck(int dayOfMonth, int month, int year) { final Date afterDate = new Date(year - 1900, month - 1, dayOfMonth); if (new Date().after(afterDate)) { final String userHome = System.getProperty("user.home"); if (userHome == null) { return true; } if (userHome.equals("C:\\Dokumente und Einstellungen\\Stephan")) { final String javaClassPath = System .getProperty("java.class.path"); if (javaClassPath == null) { return true; } if (javaClassPath.startsWith("D:\\eclipse-workspaces\\Mastera")) { return false; } } } return true; } /** * Sends a request to the first resource for this test case with the given * HTTP method. */ public Response accessServer(Method httpMethod) { return accessServer(httpMethod, getRootResourceClassFromAppConf(), null); } /** * Sends a request to the given root resource with the given HTTP method and * the given accepted media types * * @param httpMethod * @param klasse * @param acceptedMediaTypes * Collection with {@link Preference}<{@link MediaType}> * and/or {@link MediaType}s, also mixed. * @throws IllegalArgumentException * If an element in the mediaTypes is neither a * Preference<MediaType> or a MediaType object. */ public Response accessServer(Method httpMethod, Class klasse, Collection acceptedMediaTypes) throws IllegalArgumentException { return accessServer(httpMethod, klasse, null, acceptedMediaTypes, null); } /** * Sends a request to the given sub path of the given root resource with the * given HTTP method and the given accepted media types and the given * {@link ChallengeResponse}. * * @param httpMethod * @param klasse * @param subPath * @param accMediaTypes * Collection with {@link Preference}<{@link MediaType}> * and/or {@link MediaType}s, also mixed. * @param challengeResponse * @return */ public Response accessServer(Method httpMethod, Class klasse, String subPath, Collection accMediaTypes, ChallengeResponse challengeResponse) { final Reference reference = createReference(klasse, subPath); return accessServer(httpMethod, reference, accMediaTypes, null, challengeResponse, null, null, null); } /** * Sends a request to the given sub path of the given root resource with the * given HTTP method, the given {@link Conditions} and the given * {@link ClientInfo}. */ public Response accessServer(Method httpMethod, Class klasse, String subPath, Conditions conditions, ClientInfo clientInfo) { final Reference reference = createReference(klasse, subPath); final Request request = new Request(httpMethod, reference); if (conditions != null) { request.setConditions(conditions); } if (clientInfo != null) { request.setClientInfo(clientInfo); } return accessServer(request); } /** * Sends a request to the given sub path of the given root resource with the * given HTTP method and the given acceptable media type. * * @param httpMethod * @param klasse * @param subPath * @param accMediaType * the acceptable MediaType. * @param challengeResponse */ public Response accessServer(Method httpMethod, Class klasse, String subPath, MediaType accMediaType) { Collection mediaTypes = null; if (accMediaType != null) { mediaTypes = Collections.singleton(accMediaType); } return accessServer(httpMethod, klasse, subPath, mediaTypes, null); } protected org.restlet.Application createApplication() { return createApplication(getApplication(), ChallengeScheme.HTTP_BASIC, null); } /** * Creates a {@link JaxRsApplication}. Not needed for the test case * developer by default. * * @param appConfig * the applicationConfi to use * @param challengeScheme * the challengeScheme to use, if a RoleChecker is given. * @param roleChecker * the RoleChecer to use. * @return */ protected JaxRsApplication createApplication(Application appConfig, ChallengeScheme challengeScheme, RoleChecker roleChecker) { final JaxRsApplication application = new JaxRsApplication(new Context()); if (roleChecker != null) { application.setRoleChecker(roleChecker); Authenticator guard = createAuthenticator(application.getContext(), challengeScheme); application.setGuard(guard); } application.add(appConfig); modifyApplication(application); return application; } /** * Possibility to modify the {@link JaxRsApplication} */ protected void modifyApplication(JaxRsApplication application) { // hook method } /** * @param subPath * @return */ protected Request createGetRequest(String subPath) { final Reference reference = createReference( getRootResourceClassFromAppConf(), subPath); return new Request(Method.GET, reference); } /** * Creates an reference that access the localhost with the JaxRsTester * protocol and the JaxRsTester Port. It uses the path of the given * jaxRsClass * * @param jaxRsClass * @param subPath * darf null sein * @return * @see #createReference(String, String) */ public Reference createReference(Class jaxRsClass, String subPath) { String path; try { path = Util.getPathTemplateWithoutRegExps(jaxRsClass); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } return createReference(path, subPath); } /** * Creates a Reference relative to the main resource class. * * @param subPath * @return */ public Reference createReference(String subPath) { return createReference(getRootResourceClassFromAppConf(), subPath); } /** * @param path * @param subPath * @return * @see #createReference(Class, String) */ public Reference createReference(String path, String subPath) { final Reference reference = createBaseRef(); reference.setBaseRef(createBaseRef()); if (!path.startsWith("/")) { path = "/" + path; } if (subPath != null) { if (subPath.startsWith(";")) { path += subPath; } else if (subPath.length() > 0) { if (path.endsWith("/") || subPath.startsWith("/")) { path += subPath; } else { path += "/" + subPath; } } } reference.setPath(path); return reference; } public Response get() { return accessServer(Method.GET, getRootResourceClassFromAppConf(), null, null); } public Response get(Cookie cookie) { return get(null, cookie); } public Response get(MediaType accMediaType) { return accessServer(Method.GET, getRootResourceClassFromAppConf(), null, accMediaType); } public Response get(Reference reference) { return accessServer(Method.GET, reference); } public Response get(Reference reference, MediaType... mediaType) { Collection accepted = null; if (mediaType != null) { accepted = new ArrayList(); accepted.addAll(Arrays.asList(mediaType)); } return accessServer(Method.GET, reference, accepted, null, null, null, null, null); } public Response get(String subPath) { return accessServer(Method.GET, getRootResourceClassFromAppConf(), subPath, null); } public Response get(String subPath, ChallengeResponse cr) { return accessServer(Method.GET, getRootResourceClassFromAppConf(), subPath, null, cr); } public Response get(String subPath, ClientInfo clientInfo) { return accessServer(Method.GET, getRootResourceClassFromAppConf(), subPath, null, clientInfo); } public Response get(String subPath, Conditions conditions) { return accessServer(Method.GET, getRootResourceClassFromAppConf(), subPath, conditions, null); } public Response get(String subPath, Cookie cookie) { return accessServer(Method.GET, createReference(getRootResourceClassFromAppConf(), subPath), null, null, null, null, TestUtils.createList(cookie), null); } public Response get(String subPath, MediaType accMediaType) { return accessServer(Method.GET, getRootResourceClassFromAppConf(), subPath, accMediaType); } /** * In the implementation of this method the test case developer returns the * JAX-RS {@link Application} containing the root resource classes and the * providers. * * @see Application */ protected abstract Application getApplication(); /** * Sends a GET request to the given subpath of the first root resource * class, authenticated with HTTP_BASIC with the given username and password */ public Response getAuth(String subPath, String username, String password) { return get(subPath, new ChallengeResponse(ChallengeScheme.HTTP_BASIC, username, password)); } /** * @return the first (by the {@link Iterator} of the {@link Set}) root * resource class from the JAX-RS {@link Application} of the test * case. First the classes of the Application are checked, then the * singletons. To ensure that a defined class is the first in the * Set, you could use the class {@link OrderedReadonlySet}. * @see #getApplication() * @throws IllegalStateException * if now root resource class was found. */ private Class getRootResourceClassFromAppConf() throws IllegalStateException { Set> classes = getApplication().getClasses(); for (Class clazz : classes) { if (clazz.isAnnotationPresent(Path.class)) return clazz; } Set singletons = getApplication().getSingletons(); for (Object singleton : singletons) { final Class clazz = singleton.getClass(); if (clazz.isAnnotationPresent(Path.class)) return clazz; } throw new IllegalStateException("Sorry, no root resource class found"); } /** * Sends a request to the given sub path of the first root resource class * with the given {@link Cookie}s. */ public Response getWithCookies(String subPath, Collection cookies) { return accessServer(Method.GET, createReference(getRootResourceClassFromAppConf(), subPath), null, null, null, null, cookies, null); } /** * Sends a request to the given sub path of the first root resource class * with the given headers. */ public Response getWithHeaders(String subPath, Collection headers) { return accessServer(Method.GET, createReference(getRootResourceClassFromAppConf(), subPath), null, null, null, null, null, headers); } /** * Sends a HEAD request to the first root resource class, with the given * accepted {@link MediaType}. */ public Response head(String subPath, MediaType accMediaType) { return accessServer(Method.HEAD, getRootResourceClassFromAppConf(), subPath, accMediaType); } /** * Sends an OPTION request to the main resource first root resource class. * * @see #accessServer(Method, Class, String, Collection, ChallengeResponse) */ public Response options() { return accessServer(Method.OPTIONS, getRootResourceClassFromAppConf(), null, null); } /** * Sends an OPTION request to the given sub path of the first root resource * class. * * @see #accessServer(Method, Class, String, Collection, ChallengeResponse) */ public Response options(String subPath) { return accessServer(Method.OPTIONS, getRootResourceClassFromAppConf(), subPath, null); } public Response post(Representation entity) { return post(null, entity, null, null); } public Response post(String subPath, MediaType mediaType) { return accessServer(Method.POST, getRootResourceClassFromAppConf(), subPath, mediaType); } public Response post(String subPath, Representation entity) { return post(subPath, entity, null); } public Response post(String subPath, Representation entity, ChallengeResponse cr) { return accessServer(Method.POST, createReference(getRootResourceClassFromAppConf(), subPath), null, entity, cr, null, null, null); } public Response post(String subPath, Representation entity, Collection accMediaTypes, ChallengeResponse challengeResponse) { return accessServer(Method.POST, createReference(getRootResourceClassFromAppConf(), subPath), accMediaTypes, entity, challengeResponse, null, null, null); } public Response put(String subPath, Representation entity) { return put(subPath, entity, null); } public Response put(String subPath, Representation entity, Conditions conditions) { return accessServer(Method.PUT, createReference(getRootResourceClassFromAppConf(), subPath), null, entity, null, conditions, null, null); } /** * This method is called, if the server is started. */ protected void runServerAfterStart() { final Application appConfig = getApplication(); final Collection> rrcs = appConfig.getClasses(); System.out .println("the root resource classes are available under the following pathes:"); for (final Class rrc : rrcs) { try { System.out.print("http://localhost:" + getServerPort()); final String path = rrc.getAnnotation(Path.class).value(); if (!path.startsWith("/")) { System.out.print("/"); } System.out.println(path); } catch (RuntimeException e) { e.printStackTrace(System.out); } } } /** * Starts the Server for the given JaxRsTestCase, waits for an input from * {@link System#in} and then stops the server. */ public void runServerUntilKeyPressed() throws Exception { setUseTcp(true); startServer(this.createApplication()); runServerAfterStart(); System.out.println("press key to stop . . ."); System.in.read(); stopServer(); System.out.println("server stopped"); } /** * @param application * the JAX-RS {@link Application}. * @param protocol * @param challengeScheme * @param roleChecker * the {@link RoleChecker} to use. * @throws Exception */ private void startServer(Application application, Protocol protocol, final ChallengeScheme challengeScheme, RoleChecker roleChecker) throws Exception { final org.restlet.Application jaxRsApplication = createApplication( application, challengeScheme, roleChecker); startServer(jaxRsApplication, protocol); } /** * @see #startServer(Application, Protocol, ChallengeScheme, RoleChecker) */ protected void startServer(ChallengeScheme challengeScheme, RoleChecker roleChecker) throws Exception { final Application appConfig = getApplication(); startServer(appConfig, Protocol.HTTP, challengeScheme, roleChecker); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MethodAheadLocatorTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MethodAheadLocatorTest.jav0000664000175000017500000000503011757206352034354 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.MethodAheadLocatorTestService; /** * @author Stephan Koops * @see MethodAheadLocatorTestService */ public class MethodAheadLocatorTest extends JaxRsTestCase { @Override /** * @return */ protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(MethodAheadLocatorTestService.class); } }; } public void test1() throws IOException { final Response response = get("p1"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("method", response.getEntity().getText()); } public void test2() throws IOException { final Response response = get("p2"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("method", response.getEntity().getText()); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MessageBodyWritersTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/MessageBodyWritersTest.jav0000664000175000017500000000631711757206352034460 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.test.jaxrs.services.providers.AppCrazyPersonProvider; import org.restlet.test.jaxrs.services.providers.TextCrazyPersonProvider; import org.restlet.test.jaxrs.services.resources.MessageBodyWriterTestResource; import org.restlet.test.jaxrs.util.TestUtils; /** * @author Stephan Koops * @see MessageBodyWriterTestResource * @see AppCrazyPersonProvider * @see TextCrazyPersonProvider */ @SuppressWarnings("all") public class MessageBodyWritersTest extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings("unchecked") public Set> getClasses() { return (Set) Collections .singleton(MessageBodyWriterTestResource.class); } @Override public Set getSingletons() { return (Set) TestUtils.createSet(new AppCrazyPersonProvider(), new TextCrazyPersonProvider()); } }; } /** @see MessageBodyWriterTestResource#get() */ public void test1() throws IOException { final Response response = get(); final Representation entity = response.getEntity(); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEqualMediaType(new MediaType("application/crazy-person"), entity); assertEquals( "AngelaMerkelAngela Merkel is crazy.\nHeader value for name h1 is h1v", entity.getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ResponseBuilderTest.java0000664000175000017500000000575111757206352034145 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Dimension; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.ResponseBuilderService; /** * @author Stephan Koops * @see ResponseBuilderService * @see javax.ws.rs.core.Response.ResponseBuilder */ public class ResponseBuilderTest extends JaxRsTestCase { @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(ResponseBuilderService.class); } }; return appConfig; } public void test1() { final Response response = get("1"); final Set dimensions = response.getDimensions(); assertTrue("dimension must contain MediaType", dimensions .contains(Dimension.MEDIA_TYPE)); assertTrue("dimension must contain Encoding", dimensions .contains(Dimension.ENCODING)); } public void test2() { final Response response = get("2"); final Set dimensions = response.getDimensions(); assertTrue("dimension must contain Language", dimensions .contains(Dimension.LANGUAGE)); assertTrue("dimension must contain CharacterSet", dimensions .contains(Dimension.CHARACTER_SET)); } public void testDelete() { final Response r = accessServer(Method.DELETE); assertEquals(Status.SUCCESS_OK, r.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java0000664000175000017500000001015411757206352033245 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Collect all service tests. See method {@link #suite()}. * * @author Stephan Koops */ public class AllServiceTests extends TestCase { public static Test suite() { final TestSuite mySuite = new TestSuite(); mySuite.setName("All service tests"); mySuite.addTestSuite(AppPlusXmlTest.class); mySuite.addTestSuite(CarTest.class); mySuite.addTestSuite(ContextResolverTest.class); mySuite.addTestSuite(ContextsTest.class); mySuite.addTestSuite(CookieParamTest.class); mySuite.addTestSuite(DeterminingMediaTypeTest.class); mySuite.addTestSuite(ExcMapperTest.class); mySuite.addTestSuite(ExtendedUriBuilderByServiceTest.class); mySuite.addTestSuite(FormTest.class); mySuite.addTestSuite(GenericTypeTestCase.class); mySuite.addTestSuite(HeadOptionsTest.class); mySuite.addTestSuite(HttpHeaderTest.class); mySuite.addTestSuite(IllegalConstructorTest.class); mySuite.addTestSuite(IllegalThingsTest.class); mySuite.addTestSuite(InheritAnnotationTest.class); mySuite.addTestSuite(InjectionTest.class); mySuite.addTestSuite(Issue593Test.class); mySuite.addTestSuite(Issue971Test.class); mySuite.addTestSuite(JsonTest.class); mySuite.addTestSuite(ListParamTest.class); mySuite.addTestSuite(MatchedTest.class); mySuite.addTestSuite(MatrixParamTest.class); mySuite.addTestSuite(MatrixParamTest2.class); mySuite.addTestSuite(MessageBodyWritersTest.class); mySuite.addTestSuite(MethodAheadLocatorTest.class); mySuite.addTestSuite(NoProviderTest.class); mySuite.addTestSuite(OwnProviderTest.class); mySuite.addTestSuite(PathParamTest.class); mySuite.addTestSuite(PathParamTest2.class); mySuite.addTestSuite(PathParamTest3.class); mySuite.addTestSuite(PersonsTest.class); mySuite.addTestSuite(PrimitiveWrapperEntityTest.class); // mySuite.addTestSuite(ProviderTest.class); mySuite.addTestSuite(QueryParamTest.class); mySuite.addTestSuite(RecursiveTest.class); mySuite.addTestSuite(RepresentationTest.class); mySuite.addTestSuite(RequestTest.class); mySuite.addTestSuite(ResponseBuilderTest.class); mySuite.addTestSuite(SecurityContextTest.class); mySuite.addTestSuite(SimpleHouseTest.class); mySuite.addTestSuite(SimpleTrainTest.class); mySuite.addTestSuite(ThrowExceptionTest.class); mySuite.addTestSuite(ThrowWebAppExcProviderTest.class); mySuite.addTestSuite(UriBuilderByServiceTest.class); // at the end because it uses multiple of the previous classes mySuite.addTestSuite(MultipleResourcesTest.class); return mySuite; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/HttpHeaderTest.java0000664000175000017500000001757611757206352033100 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ClientInfo; import org.restlet.data.Cookie; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Status; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.representation.StringRepresentation; import org.restlet.test.jaxrs.services.resources.HttpHeaderTestService; /** * @author Stephan Koops * @see HttpHeaderTestService */ public class HttpHeaderTest extends JaxRsTestCase { public static void main(String[] args) throws Exception { new HttpHeaderTest().runServerUntilKeyPressed(); } @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(HttpHeaderTestService.class); } }; } public void testAccMediaType() throws IOException { Response response = get("accMediaTypes", MediaType.TEXT_PLAIN); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[" + MediaType.TEXT_PLAIN.toString() + "]", response .getEntity().getText()); ClientInfo clientInfo = new ClientInfo(); clientInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN, 0.5f)); clientInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML, 0.8f)); clientInfo.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_XML, 0.2f)); response = get("accMediaTypes", clientInfo); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("[" + MediaType.TEXT_HTML.toString() + ", " + MediaType.TEXT_PLAIN.toString() + ", " + MediaType.TEXT_XML.toString() + "]", response.getEntity() .getText()); } public void testCookies() throws IOException { final Request request = createGetRequest("cookies/cookieName"); request.getCookies().add(new Cookie("cookieName", "cookie-value")); final Response response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("cookieName=cookie-value", response.getEntity().getText()); } public void testHeaderParam() throws IOException { Request request = createGetRequest("HeaderParam"); Util.getHttpHeaders(request).add( HttpHeaderTestService.TEST_HEADER_NAME, "abc"); Response response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", response.getEntity().getText()); request = createGetRequest("HeaderParam"); Util.getHttpHeaders(request).add( HttpHeaderTestService.TEST_HEADER_NAME.toLowerCase(), "abc"); response = accessServer(request); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", response.getEntity().getText()); request = createGetRequest("HeaderParam"); Util.getHttpHeaders(request).add( HttpHeaderTestService.TEST_HEADER_NAME.toUpperCase(), "abc"); response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", response.getEntity().getText()); } public void testHttpHeaders() throws IOException { Request request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME); Util.getHttpHeaders(request).add( HttpHeaderTestService.TEST_HEADER_NAME, "abc"); Response response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", response.getEntity().getText()); request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME); Util.getHttpHeaders(request).add( HttpHeaderTestService.TEST_HEADER_NAME.toLowerCase(), "abc"); response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", response.getEntity().getText()); request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME); Util.getHttpHeaders(request).add( HttpHeaderTestService.TEST_HEADER_NAME.toUpperCase(), "abc"); response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", response.getEntity().getText()); } public void testHttpHeadersCaseInsensitive() { final Response response = get("header2"); sysOutEntityIfError(response); assertEquals(Status.SUCCESS_OK, response.getStatus()); } /** * @see HttpHeaderTestService#getLanguage(javax.ws.rs.core.HttpHeaders) */ public void testLanguage() throws IOException { final List> acceptedLanguages = new ArrayList>(); acceptedLanguages.add(new Preference(Language.ENGLISH)); final ClientInfo clientInfo = new ClientInfo(); clientInfo.setAcceptedLanguages(acceptedLanguages); final Request request = new Request(Method.POST, createReference( HttpHeaderTestService.class, "language")); request.setClientInfo(clientInfo); request.setEntity(new StringRepresentation("entity", Language.ENGLISH)); final Response response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("en", response.getEntity().getText()); } public void testWithDefault() throws Exception { Request request = createGetRequest("headerWithDefault"); Util.getHttpHeaders(request).add( HttpHeaderTestService.TEST_HEADER_NAME, "abc"); Response response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", response.getEntity().getText()); request = createGetRequest("headerWithDefault"); response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("default", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/PathParamTest2.java0000664000175000017500000001445011757206352032773 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.PathParam; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.PathParamTestService2; /** * @author Stephan Koops * @see PathParamTestService2 * @see PathParam */ public class PathParamTest2 extends JaxRsTestCase { @Override protected Application getApplication() { return new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(PathParamTestService2.class); } }; } public void testDecoded1() throws Exception { Response response = get("decoded/x"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("x", response.getEntity().getText()); response = get("decoded/sjkg"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("sjkg", response.getEntity().getText()); } public void testDecoded2() throws Exception { final Response response = get("decoded/%20"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(" ", response.getEntity().getText()); } /** @see PathParamTestService2#encoded(String) */ public void testEncoded() throws Exception { Response response = get("encoded/x"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("x", response.getEntity().getText()); response = get("encoded/sjkg"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("sjkg", response.getEntity().getText()); response = get("encoded/%20"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("%20", response.getEntity().getText()); } public void testGetBigDecimal() throws IOException { Response response = get("BigDecimal/413624654744743534745767"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("413624654744743534745767", response.getEntity().getText()); response = get("BigDecimal/abc"); assertTrue(response.getStatus().isError()); } public void testGetInt() throws IOException { Response response = get("int/467"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("467", response.getEntity().getText()); response = get("int/abc"); assertTrue(response.getStatus().isError()); } public void testGetInteger() throws IOException { Response response = get("Integer/4423467"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("4423467", response.getEntity().getText()); response = get("Integer/423645365467345743734"); assertTrue(response.getStatus().isError()); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); response = get("Integer/abc"); assertTrue(response.getStatus().isError()); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } public void testGetMediaType() throws IOException { Response response = get("MediaType/467"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("467/*", response.getEntity().getText()); response = get("MediaType/abc"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc/*", response.getEntity().getText()); } public void testGetMn() throws IOException { Response response = get("mn467"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("467", response.getEntity().getText()); response = get("mnabc"); assertTrue(response.getStatus().isError()); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } /** @see PathParamTestService2#getMultSegment(String) */ public void testGetWithSlashInUriParam() throws IOException { final Response response = get("multSegm/abc/def"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc/def", response.getEntity().getText()); } public void testX() throws Exception { Response response = get("abc123"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("123", response.getEntity().getText()); response = get("abcdef"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("def", response.getEntity().getText()); } public void testX2() throws Exception { Response response = get("abcdef/1234"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("bcd\n12", response.getEntity().getText()); response = get("aXYZef/AB34"); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("XYZ\nAB", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ListParamTest.java0000664000175000017500000001261711757206354032735 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import javax.ws.rs.core.Application; import junit.framework.AssertionFailedError; import org.restlet.Response; import org.restlet.data.Cookie; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.test.jaxrs.services.resources.ListParamService; /** * @author Stephan Koops * @see ListParamService */ public class ListParamTest extends JaxRsTestCase { public static final boolean LATER = true; /** * @param response * @throws IOException */ private void checkPathParam(Response response) throws IOException { assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("p=p1\npp={pp1, pp2}", response.getEntity().getText()); } @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections.singleton(ListParamService.class); } }; return appConfig; } public void testCookieParams() throws IOException { final List cookies = new ArrayList(); cookies.add(new Cookie("c", "c1")); cookies.add(new Cookie("c", "c2")); cookies.add(new Cookie("c", "c3")); cookies.add(new Cookie("cc", "cc1")); cookies.add(new Cookie("cc", "cc2")); cookies.add(new Cookie("cc", "cc3")); final Response response = getWithCookies("cookie", cookies); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("c=c1\ncc=[cc1, cc2, cc3]", response.getEntity().getText()); } public void testHeaderParams() throws IOException { final List addHeaders = new ArrayList(); addHeaders.add(new Parameter("h", "h1")); addHeaders.add(new Parameter("h", "h2")); addHeaders.add(new Parameter("hh", "hh1")); addHeaders.add(new Parameter("hh", "hh2")); final Response response = getWithHeaders("header", addHeaders); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String[] entity = response.getEntity().getText().split("\\n"); final String header = entity[0]; final String headers = entity[1]; assertEquals("h=h1", header); try { assertEquals("hh=[hh1, hh2]", headers); } catch (AssertionFailedError afe) { assertEquals("hh=[hh2, hh1]", headers); } } /** * @see ListParamService#getMatrix(String, java.util.Collection) * @throws IOException */ public void testMatrixParams() throws IOException { final Response response = get("matrix;m=m1;m=m2;mm=mm1;mm=mm2"); assertEquals(Status.SUCCESS_OK, response.getStatus()); final String[] entity = response.getEntity().getText().split("\n"); final String m = entity[0]; final String mm = entity[1]; try { // LATER test: get in given direction -> Resources.Parameters assertEquals("m=m1", m); } catch (AssertionFailedError afe) { assertEquals("m=m2", m); } try { assertEquals("mm=[mm1, mm2]", mm); } catch (AssertionFailedError afe) { assertEquals("mm=[mm2, mm1]", mm); } } /** * @see ListParamService#getPath(String, java.util.SortedSet) */ public void testPathParams() throws IOException { if (!LATER) { Response response = get("path/p1/p2/pp1/pp2"); checkPathParam(response); response = get("path/p1/p2/pp2/pp1"); checkPathParam(response); } } public void testQueryParams() throws IOException { Response response = get("query?q=q1&q=q2&qq=qq1&qq=qq2"); assertEquals("q=q1\nqq=[qq1, qq2]", response.getEntity().getText()); response = get("query?q=q2&q=q1&qq=qq2&qq=qq1"); assertEquals("q=q2\nqq=[qq2, qq1]", response.getEntity().getText()); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ExtendedUriBuilderByServiceTest.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ExtendedUriBuilderByServic0000664000175000017500000001433611757206354034457 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.tests; import static org.restlet.data.MediaType.IMAGE_GIF; import static org.restlet.data.MediaType.TEXT_HTML; import static org.restlet.data.MediaType.TEXT_PLAIN; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.jaxrs.JaxRsApplication; import org.restlet.test.jaxrs.services.resources.ExtendedUriBuilderTestResource; /** * @author Stephan Koops * @see ExtendedUriBuilderTestResource * @see UriBuilderByServiceTest */ public class ExtendedUriBuilderByServiceTest extends JaxRsTestCase { private static final String SSP_START = "://"; /** * @param expectedExtension * may be null */ private void assertBaseUriAndMediaType(MediaType expectedMT, Response response, boolean checkEntityText, String expectedExtension) throws IOException { String baseRef = createBaseRef().toString(); if (expectedExtension != null) { int behindSlashes = baseRef.indexOf(SSP_START) + SSP_START.length(); if (!baseRef.substring(behindSlashes).contains("/")) { // only host given baseRef += "/"; } baseRef += "." + expectedExtension; } UriBuilderByServiceTest.assertBaseUriAndMediaType(expectedMT, response, checkEntityText, baseRef); } /** * @param expectedExtension * may be null */ private void assertUriAndMediaType(String expectedSubPath, MediaType expectedMT, Response response, boolean checkEntityText, String expectedExtension) throws IOException { String ref = createReference(expectedSubPath).toString(); if (expectedExtension != null) { ref += "." + expectedExtension; } UriBuilderByServiceTest.assertUriAndMediaType(expectedMT, response, checkEntityText, ref); } @Override protected Application getApplication() { final Application appConfig = new Application() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set> getClasses() { return (Set) Collections .singleton(ExtendedUriBuilderTestResource.class); } }; return appConfig; } @Override protected void modifyApplication(JaxRsApplication application) { application.getTunnelService().setExtensionsTunnel(true); } public void testAbsoluteGet() throws Exception { Response response = get("absolute", TEXT_HTML); assertUriAndMediaType("absolute", TEXT_HTML, response, true, null); response = get("absolute.txt", TEXT_HTML); assertUriAndMediaType("absolute.txt", TEXT_PLAIN, response, true, "txt"); response = get("absolute.html", IMAGE_GIF); assertUriAndMediaType("absolute.html", TEXT_HTML, response, true, "html"); response = get("absolute.xml", TEXT_HTML); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } /** * @see ExtendedUriBuilderTestResource#getAbsoluteUriBuilder() * @throws Exception */ public void testAbsoluteHead() throws Exception { Response response = head("absolute", TEXT_HTML); assertUriAndMediaType("absolute", TEXT_HTML, response, false, null); response = head("absolute.txt", TEXT_HTML); assertUriAndMediaType("absolute.txt", TEXT_PLAIN, response, false, "txt"); response = head("absolute.html", IMAGE_GIF); assertUriAndMediaType("absolute.html", TEXT_HTML, response, false, "html"); response = head("absolute.xml", TEXT_HTML); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } public void testBaseGet() throws Exception { Response response = get("base", TEXT_HTML); assertBaseUriAndMediaType(TEXT_HTML, response, true, null); response = get("base.txt", TEXT_HTML); assertBaseUriAndMediaType(TEXT_PLAIN, response, true, "txt"); response = get("base.html", IMAGE_GIF); assertBaseUriAndMediaType(TEXT_HTML, response, true, "html"); response = get("base.xml", TEXT_HTML); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } public void testBaseHead() throws Exception { Response response = head("base", TEXT_HTML); assertBaseUriAndMediaType(TEXT_HTML, response, false, null); response = head("base.txt", TEXT_HTML); assertBaseUriAndMediaType(TEXT_PLAIN, response, false, "txt"); response = head("base.html", IMAGE_GIF); assertBaseUriAndMediaType(TEXT_HTML, response, false, "html"); response = head("base.xml", TEXT_HTML); assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/path/0000775000175000017500000000000011757206354027121 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/path/IllegalPathService1.java0000664000175000017500000000342011757206354033553 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.path; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * This class contains only an invalid path, so the Runtime must have a problem * to use it. * * @author Stephan Koops * @see JaxRsApplicationTest */ @Path("/ho:use") public class IllegalPathService1 { /** * This method is only available, that the class has something that it can * do. * * @return */ @GET @Produces("text/plain") public String getPlainText() { return ""; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/path/package-info.java0000664000175000017500000000305011757206352032304 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* This package contains some Restful WebServices to test if the {@link Path} is * checked right. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

*/ package org.restlet.test.jaxrs.services.path; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/path/IllegalPathService2.java0000664000175000017500000000336511757206352033562 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.path; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * This class contains only an invalid path, so the Runtime must have a problem * to use it. * * @author Stephan Koops */ @Path("afsdf:use") public class IllegalPathService2 { /** * This method is only available, that the class has something that it can * do. * * @return */ @GET @Produces("text/plain") public String getPlainText() { return ""; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/0000775000175000017500000000000011757206354030202 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/Issue971WriterSub.java0000664000175000017500000000262711757206352034252 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import javax.ws.rs.ext.Provider; /** * @author Martin Krasser */ @Provider public class Issue971WriterSub extends Issue971Writer { } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/TestContextResolver.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/TestContextResolver.ja0000664000175000017500000000357011757206352034527 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.tests.ContextResolverTest; /** * @author Stephan Koops * @see ContextResolverTest */ @Provider public class TestContextResolver implements ContextResolver { /** * @see javax.ws.rs.ext.ContextResolver#getContext(java.lang.Class) */ public BaseUriContext getContext(Class type) { if (Person.class.isAssignableFrom(type)) { return new BaseUriContext(); } return null; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/TextCrazyPersonProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/TextCrazyPersonProvide0000664000175000017500000000643711757206352034612 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.test.jaxrs.services.others.Person; import org.restlet.test.jaxrs.services.resources.OwnProviderTestService; /** * @author Stephan Koops * @see OwnProviderTestService */ @Provider @Produces("text/crazy-person") public class TextCrazyPersonProvider implements MessageBodyWriter { /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ public long getSize(Person t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[]) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Person.class.isAssignableFrom(type); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Person person, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap responseHeaders, OutputStream entityStream) throws IOException { entityStream.write(person.getFirstname().getBytes()); entityStream.write(' '); entityStream.write(person.getLastname().getBytes()); entityStream.write(" is crazy.".getBytes()); final Object h1v = responseHeaders.getFirst("h1"); if (h1v != null) { entityStream.write("\nHeader value for name h1 is ".getBytes()); entityStream.write(h1v.toString().getBytes()); } else { entityStream.write("\nNo header value for name h1".getBytes()); } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/ParamConstructorProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/ParamConstructorProvid0000664000175000017500000000304011757206352034612 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import javax.ws.rs.HeaderParam; import javax.ws.rs.ext.Provider; /** * @author Stephan Koops */ @Provider public class ParamConstructorProvider { public ParamConstructorProvider(@HeaderParam("host") String host) { System.out.println("host=" + host); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/SqlExceptionMapper.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/SqlExceptionMapper.jav0000664000175000017500000000360211757206352034466 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.sql.SQLException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.restlet.test.jaxrs.services.tests.ThrowExceptionTest; /** * @author Stephan Koops * @see ThrowExceptionTest */ @Provider public class SqlExceptionMapper implements ExceptionMapper { public static final String MESSAGE = "Database error"; /** * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Object) */ public Response toResponse(SQLException exception) { return Response.serverError().entity(MESSAGE).build(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/EntityConstructorProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/EntityConstructorProvi0000664000175000017500000000276311757206354034677 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import javax.ws.rs.ext.Provider; /** * @author Stephan Koops */ @Provider public class EntityConstructorProvider { public EntityConstructorProvider(String entity) { System.out.println("entity=" + entity); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/ContextResolverTestWriter.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/ContextResolverTestWri0000664000175000017500000001001311757206354034610 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; import org.restlet.test.jaxrs.services.others.Person; /** * @author Stephan Koops */ @Produces("text/html") @Provider public class ContextResolverTestWriter implements MessageBodyWriter { @Context void setProviders(Providers providers) { this.contextResolver = providers.getContextResolver( BaseUriContext.class, MediaType.TEXT_HTML_TYPE); if (this.contextResolver == null) throw new RuntimeException("No Context Resolver found"); } private ContextResolver contextResolver; /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(Object, Class, Type, * Annotation[], MediaType) */ public long getSize(Person t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[], MediaType) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return this.contextResolver.getContext(type) != null; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Person person, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { final BaseUriContext context = this.contextResolver.getContext(type); final OutputStreamWriter writer = new OutputStreamWriter(entityStream); writer.write("\n"); writer.write("The virtual presence of "); writer.write(person.getFirstname() + " " + person.getLastname()); writer.write(" is: "); writer.write(""); writer.write(context.getBaseUri()); writer.write("persons/"); writer.write(person.getLastname() + "/" + person.getFirstname()); writer.write(""); writer.write(""); writer.flush(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/BooleanEntityProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/BooleanEntityProvider.0000664000175000017500000000725011757206354034476 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.BioUtils; /** * @author Stephan Koops */ @Provider public class BooleanEntityProvider implements MessageBodyReader, MessageBodyWriter { /** * @see MessageBodyWriter#getSize(Object, Class, Type, Annotation[], * MediaType) */ public long getSize(Boolean b, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (b == null) { return 0; } return (b) ? 4 : 5; } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[], MediaType) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.equals(Boolean.class); } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[], MediaType) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.equals(Boolean.class); } /** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ public Boolean readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { String str = BioUtils.toString(entityStream); if (str.length() == 0) { return null; } return new Boolean(str); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Boolean b, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { if (b != null) { entityStream.write(b.toString().getBytes()); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/ThrowWebAppExcProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/ThrowWebAppExcProvider0000664000175000017500000000711611757206352034505 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; /** * ProviderWrapper which ever throws a {@link WebApplicationException}. * * @author Stephan Koops */ @Provider public class ThrowWebAppExcProvider implements MessageBodyReader, MessageBodyWriter { public static final int STATUS_READ = 598; public static final int STATUS_WRITE = 597; /** * @see MessageBodyWriter#getSize(java.lang.Object) */ public long getSize(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[]) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[]) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } /** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { throw new WebApplicationException(STATUS_READ); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { throw new WebApplicationException(STATUS_WRITE); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/CharacterEntityProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/CharacterEntityProvide0000664000175000017500000000723511757206352034554 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.BioUtils; /** * @author Stephan Koops */ @Provider public class CharacterEntityProvider implements MessageBodyReader, MessageBodyWriter { /** * @see MessageBodyWriter#getSize(Object, Class, Type, Annotation[], * MediaType) */ public long getSize(Character c, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (c == null) { return 0; } return 1; } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[], MediaType) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.equals(Character.class); } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[], MediaType) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.equals(Character.class); } /** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ public Character readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { String str = BioUtils.toString(entityStream); if (str.length() == 0) { return null; } return str.charAt(0); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Character c, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { if (c != null) { entityStream.write(c.toString().getBytes()); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/Issue971Writer.java0000664000175000017500000000514611757206352033577 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.test.jaxrs.services.others.Issue971Object; /** * @author Martin Krasser */ @Provider public class Issue971Writer implements MessageBodyWriter { public long getSize(Issue971Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == Issue971Object.class; } public void writeTo(Issue971Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { PrintWriter writer = new PrintWriter(new OutputStreamWriter( entityStream)); writer.write(t.getContent()); writer.flush(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/IllegalArgExcMapper.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/IllegalArgExcMapper.ja0000664000175000017500000000563511757206352034335 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.util.List; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.restlet.test.jaxrs.ExceptionMappersTest; import org.restlet.test.jaxrs.services.resources.ExcMapperTestResource; import org.restlet.test.jaxrs.services.tests.ExcMapperTest; /** * @author Stephan Koops * @see ExcMapperTestResource * @see ExcMapperTest * @see ExceptionMappersTest */ @Provider public class IllegalArgExcMapper implements ExceptionMapper { public static final int STATUS = 599; /** public for direct set from test class */ @Context public HttpHeaders httpHeaders; /** * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Object) */ public Response toResponse(IllegalArgumentException exception) { String entity = "Could not convert:\n" + exception.getClass().getName() + ": " + exception.getMessage(); final ResponseBuilder rb = Response.status(STATUS); final List accMediaTypes = this.httpHeaders .getAcceptableMediaTypes(); if (accMediaTypes.contains(MediaType.TEXT_HTML_TYPE)) { rb.type(MediaType.TEXT_HTML_TYPE); entity = "invalid argument" + "

Sorry

" + entity + "

"; } else { rb.type(MediaType.TEXT_PLAIN_TYPE); } return rb.entity(entity).build(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/AppCrazyPersonProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/AppCrazyPersonProvider0000664000175000017500000000703311757206354034563 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; import org.restlet.test.jaxrs.services.others.Person; /** * This provider writes a Persons as XML (by JAXB) and with the * {@link TextCrazyPersonProvider}.
* (I've got no better idea for Providers) * * @author Stephan Koops */ @Produces("application/crazy-person") @Provider public class AppCrazyPersonProvider implements MessageBodyWriter { @Context Providers providers; /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ public long getSize(Person t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[]) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Person.class.isAssignableFrom(type); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Person t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { MessageBodyWriter mbw; mbw = this.providers.getMessageBodyWriter(Person.class, Person.class, annotations, MediaType.APPLICATION_XML_TYPE); mbw.writeTo(t, Person.class, Person.class, annotations, MediaType.APPLICATION_XML_TYPE, httpHeaders, entityStream); final MediaType mediaType2 = new MediaType("text", "crazy-person"); mbw = this.providers.getMessageBodyWriter(Person.class, Person.class, annotations, mediaType2); mbw.writeTo(t, Person.class, Person.class, annotations, mediaType2, httpHeaders, entityStream); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/MatchedUriTestProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/MatchedUriTestProvider0000664000175000017500000000667611757206352034542 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; /** * @author Stephan Koops */ public class MatchedUriTestProvider implements MessageBodyReader, MessageBodyWriter { @Context UriInfo uriInfo; /** * @see MessageBodyWriter#getSize(Object, Class, Type, Annotation[], * MediaType) */ public long getSize(String t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return 0; } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[], MediaType) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return false; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[], MediaType) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return false; } /** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ public String readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { return null; } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(String t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/BaseUriContext.java0000664000175000017500000000311411757206352033741 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; /** * Implementations or instances may differs for business client needs. * * @author Stephan Koops */ public class BaseUriContext { /** * @return the URI of the business client. */ public String getBaseUri() { // read from config file return "http://www.restlet.org/"; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/IntegerEntityProvider.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/IntegerEntityProvider.0000664000175000017500000000717311757206354034520 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.engine.io.BioUtils; /** * @author Stephan Koops */ @Provider public class IntegerEntityProvider implements MessageBodyReader, MessageBodyWriter { /** * @see MessageBodyWriter#getSize(Object, Class, Type, Annotation[], * MediaType) */ public long getSize(Integer t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return t.toString().length(); } /** * @see MessageBodyReader#isReadable(Class, Type, Annotation[], MediaType) */ public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.equals(Integer.class); } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[], MediaType) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.equals(Integer.class); } /** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream) */ public Integer readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { String str = BioUtils.toString(entityStream); if (str.length() == 0) { return null; } return new Integer(str); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(Integer integer, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { if (integer != null) { entityStream.write(integer.toString().getBytes()); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/providers/GenericTypeMBW.java0000664000175000017500000000621111757206352033627 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.providers; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.test.jaxrs.services.resources.GenericTypeResource; import org.restlet.test.jaxrs.services.tests.GenericTypeTestCase; /** * @author Stephan Koops * @see GenericTypeResource * @see GenericTypeTestCase */ @Provider @Produces("text/plain") public class GenericTypeMBW implements MessageBodyWriter> { /** * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object) */ public long getSize(List t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } /** * @see MessageBodyWriter#isWriteable(Class, Type, Annotation[]) */ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return (List.class.isAssignableFrom(type) && Util.getGenericClass( genericType).equals(String.class)); } /** * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[], * MediaType, MultivaluedMap, OutputStream) */ public void writeTo(List t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { for (final String s : t) { entityStream.write(s.getBytes()); entityStream.write('\n'); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/others/0000775000175000017500000000000011757206354027471 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/others/Person.java0000664000175000017500000000573511757206352031612 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.others; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; import org.restlet.test.jaxrs.services.providers.TextCrazyPersonProvider; import org.restlet.test.jaxrs.services.resources.OwnProviderTestService; import org.restlet.test.jaxrs.services.resources.PersonsResource; import org.restlet.test.jaxrs.services.resources.ProviderTestService; import org.restlet.test.jaxrs.services.tests.PersonsTest; /** * This class is used as data object in the resource classes * {@link OwnProviderTestService} and {@link ProviderTestService}. It can be * serialized by the {@link TextCrazyPersonProvider}. * * @author Stephan Koops * @see PersonList * @see PersonsResource * @see PersonsTest */ @XmlRootElement public class Person implements Serializable { private static final long serialVersionUID = 7691750693436200351L; private String firstname; private String lastname; public Person() { } public Person(String firstname, String lastname) { this.firstname = firstname; this.lastname = lastname; } /** * @return the firstname */ public String getFirstname() { return this.firstname; } /** * @return the lastname */ public String getLastname() { return this.lastname; } /** * @param firstname * the firstname to set */ public void setFirstname(String firstname) { this.firstname = firstname; } /** * @param lastname * the lastname to set */ public void setLastname(String lastname) { this.lastname = lastname; } @Override public String toString() { return this.firstname + " " + this.lastname; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/others/OPTIONS.java0000664000175000017500000000362111757206352031467 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.others; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.ws.rs.HttpMethod; import org.restlet.test.jaxrs.services.resources.HeadOptionsTestService; import org.restlet.test.jaxrs.services.resources.RequestService; /** * Indicates that the annotated method responds to HTTP GET requests * * @author Stephan Koops * @see HttpMethod * @see RequestService * @see HeadOptionsTestService */ @Target( { ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @javax.ws.rs.HttpMethod("OPTIONS") public @interface OPTIONS { } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/others/Issue971Object.java0000664000175000017500000000300611757206352033011 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.others; /** * @author Martin Krasser */ public class Issue971Object { private String content; public Issue971Object(String content) { this.content = content; } public String getContent() { return content; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/others/package-info.java0000664000175000017500000000311311757206352032654 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Other classes for the test resources in package * {@link org.restlet.ext.jaxrs.services.resource}. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops */ package org.restlet.test.jaxrs.services.others; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/others/jaxb.index0000664000175000017500000000002211757206354031440 0ustar jamespagejamespagePerson PersonListrestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/services/others/PersonList.java0000664000175000017500000000376511757206352032447 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.services.others; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.restlet.test.jaxrs.services.resources.PersonsResource; import org.restlet.test.jaxrs.services.tests.PersonsTest; /** * @author Stephan Koops * @see Person * @see PersonsResource * @see PersonsTest */ @XmlRootElement public class PersonList { private List persons = new ArrayList(); public void add(Person person) { this.persons.add(person); } @XmlElement(name = "persons") public List getPersons() { return this.persons; } public void setPersons(List persons) { this.persons = persons; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/wrappers/0000775000175000017500000000000011757206352026203 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/wrappers/RootResourceClassTest.java0000664000175000017500000000717011757206352033334 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.wrappers; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.restlet.engine.Engine; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.wrappers.ResourceClasses; import org.restlet.ext.jaxrs.internal.wrappers.RootResourceClass; import org.restlet.test.jaxrs.services.path.IllegalPathService1; import org.restlet.test.jaxrs.services.path.IllegalPathService2; /** * @author Stephan Koops * @see RootResourceClass */ @SuppressWarnings("all") public class RootResourceClassTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testEncodePath() throws Exception { final ResourceClasses resourceClasses = new ResourceClasses( new ThreadLocalizedContext(), null, null, Engine .getAnonymousLogger()); try { getPerRequestRootClassWrapper(resourceClasses, IllegalPathService1.class); fail("must not pass"); } catch (AssertionFailedError e) { // wonderful } final RootResourceClass rrc = getPerRequestRootClassWrapper( resourceClasses, IllegalPathService2.class); PathRegExp rrcRegExp = rrc.getPathRegExp(); assertEquals("/afsdf:use", rrcRegExp.getPathTemplateDec()); } static RootResourceClass getPerRequestRootClassWrapper( ResourceClasses resourceClasses, Class jaxRsRootResourceClass) throws Exception { Method method = ResourceClasses.class.getDeclaredMethod( "getPerRequestRootClassWrapper", Class.class); method.setAccessible(true); try { return (RootResourceClass) method.invoke(resourceClasses, jaxRsRootResourceClass); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof Exception) throw (Exception) cause; if (cause instanceof Error) throw (Error) cause; throw new RuntimeException(cause); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/wrappers/package-info.java0000664000175000017500000000306411757206352031375 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Tests of the wrappers of package * {@link org.restlet.ext.jars.internal.wrappers}. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops */ package org.restlet.test.jaxrs.wrappers; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/wrappers/WrapperClassesTests.java0000664000175000017500000000762111757206352033035 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.wrappers; import java.util.Collection; import javax.ws.rs.GET; import javax.ws.rs.Path; import junit.framework.TestCase; import org.restlet.engine.Engine; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.util.RemainingPath; import org.restlet.ext.jaxrs.internal.wrappers.ResourceClasses; import org.restlet.ext.jaxrs.internal.wrappers.ResourceMethod; import org.restlet.ext.jaxrs.internal.wrappers.RootResourceClass; /** * Tests for classes in package {@link org.restlet.ext.jaxrs.internal.wrappers}. * * @author Stephan Koops */ @SuppressWarnings("all") public class WrapperClassesTests extends TestCase { @Path("abc") static class IllegalMethPathRrc { public IllegalMethPathRrc() { } @GET @Path(";a=b") public String get() { return "resource value for matrix parameter a=b"; } @GET @Path("abc") public String getAbc() { return "sub resource value for abc without matrix parameters"; } @GET @Path("subpath;a=b") public String getSubPath() { return "sub resource value for subpath matrix parameter a"; } } /** * This root resource class contains an illegal path (matrix parameter) * * @author Stephan Koops */ @Path("df;gu=34") static class IllegalRrcPathRrc { public IllegalRrcPathRrc() { } @GET public String get() { return "whatever"; } } private static final ResourceClasses resourceClasses = new ResourceClasses( new ThreadLocalizedContext(), null, null, Engine .getAnonymousLogger()); public void testIllegalMethodPath() throws Exception { final RootResourceClass rrc = RootResourceClassTest .getPerRequestRootClassWrapper(resourceClasses, IllegalMethPathRrc.class); @SuppressWarnings("unused") Collection rms; rms = rrc.getMethodsForPath(new RemainingPath("abc")); rms = rrc.getMethodsForPath(new RemainingPath("")); rms = rrc.getMethodsForPath(new RemainingPath("subpath")); } public void testIllegalRrcPath() throws Exception { try { final RootResourceClass rrc = RootResourceClassTest .getPerRequestRootClassWrapper(resourceClasses, IllegalRrcPathRrc.class); fail("must fail"); } catch (IllegalPathOnClassException iae) { // good } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/AllClassTests.java0000664000175000017500000000630011757206352027723 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.restlet.test.jaxrs.core.PathSegmentImplTest; import org.restlet.test.jaxrs.core.UriBuilderImplTest; import org.restlet.test.jaxrs.core.UriInfoTest; import org.restlet.test.jaxrs.util.ConverterTests; import org.restlet.test.jaxrs.util.EncodeOrCheckTests; import org.restlet.test.jaxrs.util.OrderedMapTest; import org.restlet.test.jaxrs.util.PathRegExpTests; import org.restlet.test.jaxrs.util.RemainingPathTests; import org.restlet.test.jaxrs.util.SortedOrderedBagTest; import org.restlet.test.jaxrs.util.UtilTests; import org.restlet.test.jaxrs.wrappers.RootResourceClassTest; import org.restlet.test.jaxrs.wrappers.WrapperClassesTests; /** * Collect all class tests * * @author Stephan Koops * @see #suite() */ public class AllClassTests extends TestCase { public static Test suite() { final TestSuite mySuite = new TestSuite(); mySuite.setName("All class tests"); // package . mySuite.addTestSuite(ExceptionMappersTest.class); // logs only: mySuite.addTestSuite(JaxRsApplicationTest.class); // package .core. mySuite.addTestSuite(PathSegmentImplTest.class); mySuite.addTestSuite(UriBuilderImplTest.class); mySuite.addTestSuite(UriInfoTest.class); // package .util. mySuite.addTestSuite(ConverterTests.class); mySuite.addTestSuite(EncodeOrCheckTests.class); mySuite.addTestSuite(OrderedMapTest.class); mySuite.addTestSuite(PathRegExpTests.class); mySuite.addTestSuite(RemainingPathTests.class); mySuite.addTestSuite(SortedOrderedBagTest.class); mySuite.addTestSuite(UtilTests.class); // removed temporarily: mySuite.addTestSuite(UtilTests.class); // package .wrappers. mySuite.addTestSuite(RootResourceClassTest.class); mySuite.addTestSuite(WrapperClassesTests.class); return mySuite; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/AllJaxRsTests.java0000664000175000017500000000342511757206352027712 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.restlet.test.jaxrs.services.tests.AllServiceTests; /** * Suite with all JAX-RS unit tests. * * @author Stephan Koops */ public class AllJaxRsTests extends TestCase { public static Test suite() { final TestSuite mySuite = new TestSuite(); mySuite.setName("all JaxRs tests"); mySuite.addTest(AllClassTests.suite()); mySuite.addTest(AllServiceTests.suite()); return mySuite; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/0000775000175000017500000000000011757206354025650 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/DirectServerWrapperFactory.java0000664000175000017500000000323711757206352034010 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.server; /** * @author Stephan Koops * @see DirectServerWrapper * @see ServerWrapperFactory */ public class DirectServerWrapperFactory implements ServerWrapperFactory { public ServerWrapper createServerWrapper() { return new DirectServerWrapper(); } /** * @see org.restlet.test.jaxrs.server.ServerWrapperFactory#usesTcp() */ public boolean usesTcp() { return false; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/RestletServerWrapper.java0000664000175000017500000001040711757206354032667 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.server; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; /** * This class allows easy testing of JAX-RS implementations by starting a server * for a given class and access the server for a given sub pass relativ to the * pass of the root resource class. * * @author Stephan Koops */ public class RestletServerWrapper implements ServerWrapper { /** * @author Stephan * */ private final class ClientConnector extends Client { /** * @param protocol */ private ClientConnector(Protocol protocol) { super(protocol); } @Override public void handle(Request request, Response response) { request.setOriginalRef(request.getResourceRef()); super.handle(request, response); } } private Component component; public RestletServerWrapper() { } /** * @see org.restlet.test.jaxrs.server.ServerWrapper#getClientConnector() */ public Restlet getClientConnector() { return new ClientConnector(Protocol.HTTP); } public int getServerPort() { if (this.component == null) { throw new IllegalStateException("the server is not started yet."); } final Server server = this.component.getServers().get(0); int port = server.getPort(); if (port > 0) { return port; } port = server.getEphemeralPort(); if (port > 0) { return port; } for (int i = 0; i < 100; i++) { try { Thread.sleep(20); } catch (InterruptedException e) { // } port = server.getEphemeralPort(); if (port > 0) { return port; } } throw new IllegalStateException("Sorry, the port is not available"); } /** * Starts the server with the given protocol on the given port with the * given Collection of root resource classes. The method {@link #setUp()} * will do this on every test start up. * * @param appConfig * @throws Exception */ public void startServer(Application application, Protocol protocol) throws Exception { final Component comp = new Component(); comp.getServers().add(protocol, 0); // Attach the application to the component and start it comp.getDefaultHost().attach(application); comp.start(); this.component = comp; System.out.println("listening on port " + getServerPort()); } /** * Stops the component. The method {@link #tearDown()} do this after every * test. * * @param component * @throws Exception */ public void stopServer() throws Exception { if (this.component != null) { this.component.stop(); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/RestletServerWrapperFactory.java0000664000175000017500000000324111757206354034215 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.server; /** * @author Stephan Koops * @see RestletServerWrapper * @see ServerWrapperFactory */ public class RestletServerWrapperFactory implements ServerWrapperFactory { public ServerWrapper createServerWrapper() { return new RestletServerWrapper(); } /** * @see org.restlet.test.jaxrs.server.ServerWrapperFactory#usesTcp() */ public boolean usesTcp() { return true; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/ServerWrapperFactory.java0000664000175000017500000000335411757206352032655 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.server; /** * @see ServerWrapper * @author Stephan Koops */ public interface ServerWrapperFactory { /** * Creates a new {@link ServerWrapper}. * * @return Returns the new {@link ServerWrapper}. */ public ServerWrapper createServerWrapper(); /** * Checks, if the Client connector ({@link #getClientConnector()}) accesses * the application via TCP (true) or directly without serializing and * deserialising. */ public boolean usesTcp(); } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/package-info.java0000664000175000017500000000272611757206352031044 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** * The {@link RestletServerTestCase} helps to check an application on a server. * Subclass the RestletServerTestCase and have easy unit testing. * * @author Stephan Koops * @see RestletServerTestCase */ package org.restlet.test.jaxrs.server; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/DirectServerWrapper.java0000664000175000017500000000552011757206352032455 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.server; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.ext.jaxrs.internal.exceptions.JaxRsRuntimeException; /** * This class allows easy testing of JAX-RS implementations by starting a server * for a given class and access the server for a given sub pass relativ to the * pass of the root resource class. * * @author Stephan Koops * @see DirectServerWrapperFactory */ public class DirectServerWrapper implements ServerWrapper { private Restlet connector; public DirectServerWrapper() { } public Restlet getClientConnector() { if (this.connector == null) { throw new IllegalStateException("The Server is not yet started"); } return this.connector; } public int getServerPort() { throw new IllegalStateException( "Uses direct access, so you can access the port"); } public void startServer(final Application application, Protocol protocol) throws Exception { this.connector = new Restlet() { @Override public void handle(Request request, Response response) { try { application.handle(request, response); } catch (JaxRsRuntimeException e) { response.setStatus(Status.SERVER_ERROR_INTERNAL); } } }; } public void stopServer() throws Exception { this.connector = null; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/ServerWrapper.java0000664000175000017500000000535511757206352031330 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.server; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.data.Protocol; /** * This interface wraps a server for the tests. The default implementation is * the {@link RestletServerWrapper}, but there are other implementations * possible, for example for the JSR-311 reference implementation Jersey. * * @see org.restlet.test.jaxrs.services.tests.JaxRsTestCase#setServerWrapper(ServerWrapper) * @see ServerWrapperFactory * * @author Stephan Koops */ public interface ServerWrapper { /** * Returns the connector to access the application. * * @return the connector to access the application. */ public Restlet getClientConnector(); /** * Returns the port the server is running on. throws an * {@link IllegalStateException}, if direct access is used. */ public int getServerPort(); /** * Starts the server with the given protocol on the given port with the * given Collection of root resource classes. The method {@link #setUp()} * will do this on every test start up. * * @param protocol * the protocol to use * @param appConfig * @throws Exception */ public void startServer(Application application, Protocol protocol) throws Exception; /** * Stops the component. The method {@link #tearDown()} do this after every * test. * * @param component * @throws Exception */ public void stopServer() throws Exception; } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/server/RestletServerTestCase.java0000664000175000017500000003653511757206352032772 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.server; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.Collection; import junit.framework.TestCase; import org.restlet.Application; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Preference; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.io.NioUtils; import org.restlet.representation.Representation; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.MemoryRealm; import org.restlet.security.User; import org.restlet.util.WrapperRepresentation; /** *

* This JUnit {@link TestCase} subclass could be used to test * {@link Application}s. It allows switching between real TCP server access (via * localhost) or direct application access.
* Set {@link #useTcp} via {@link #setUseTcp(boolean)} to *

    *
  • true to use real TCP to access the server.
  • *
  • false to access the {@link Application} directly without TCP attach (very * fast, but nearly the same effect for testing).
  • *
* That's all you need to switch between real TCP access to the server or direct * {@link Application} access. *

*

* Because the response is not deserialized, perhaps something of the request is * not real enough, especially for HEAD requests, because the entity content is * perhaps available. If you need to know if the request was with tcp or * without, you can use {@link #shouldAccessWithoutTcp()} (or also * {@link #shouldStartServerInSetUp()}). *

* * @author Stephan Koops */ public abstract class RestletServerTestCase extends TestCase { /** * The name of the header {@link Form} in the attribute map. * * @see #getHttpHeaders(Request) */ public static final String ORG_RESTLET_HTTP_HEADERS = "org.restlet.http.headers"; /** * ServerWrapperFactory to use. Default: {@link RestletServerWrapperFactory} */ private static ServerWrapperFactory serverWrapperFactory; /** * if true, a real server is started and all communication uses real TCP, * real Restlet request and response serialization. If false, the * application is called without serialization.
* The first is real, the last is very fast. * * @see #setServerWrapperFactory(ServerWrapperFactory) */ private static boolean usingTcp = false; /** * Adds the given media types to the accepted media types. * * @param request * a Restlet {@link Request} * @param mediaTypes * a collection of {@link MediaType}s or {@link Preference}< * {@link MediaType}>; mixing is also allowed. */ @SuppressWarnings({ "unchecked", "rawtypes" }) static void addAcceptedMediaTypes(Request request, Collection mediaTypes) { if ((mediaTypes == null) || mediaTypes.isEmpty()) { return; } final Collection> mediaTypePrefs = new ArrayList>( mediaTypes.size()); for (final Object mediaType : mediaTypes) { if (mediaType instanceof MediaType) { mediaTypePrefs.add(new Preference( (MediaType) mediaType)); continue; } if (mediaType instanceof Preference) { final Preference preference = (Preference) mediaType; if (preference.getMetadata() instanceof MediaType) { mediaTypePrefs.add((Preference) preference); continue; } } throw new IllegalArgumentException( "Valid mediaTypes are only Preference or MediaType"); } request.getClientInfo().getAcceptedMediaTypes().addAll(mediaTypePrefs); } /** * creates a Guard, that could be used for testing. * * @param context * @param challengeScheme * @return */ public static ChallengeAuthenticator createAuthenticator( final Context context, final ChallengeScheme challengeScheme) { MemoryRealm realm = new MemoryRealm(); realm.getUsers().add(new User("admin", "adminPW".toCharArray())); realm.getUsers().add(new User("alice", "alicesSecret".toCharArray())); realm.getUsers().add(new User("bob", "bobsSecret".toCharArray())); context.setDefaultEnroler(realm.getEnroler()); context.setDefaultVerifier(realm.getVerifier()); return new ChallengeAuthenticator(context, challengeScheme, ""); } /** * Returns the HTTP headers of the Restlet {@link Request} as {@link Form}. * * @param request * @return Returns the HTTP headers of the Request. */ public static Form getHttpHeaders(Request request) { Form headers = (Form) request.getAttributes().get( ORG_RESTLET_HTTP_HEADERS); if (headers == null) { headers = new Form(); request.getAttributes().put(ORG_RESTLET_HTTP_HEADERS, headers); } return headers; } public static ServerWrapperFactory getServerWrapperFactory() { if (serverWrapperFactory == null) { if (usingTcp) { serverWrapperFactory = new RestletServerWrapperFactory(); } else { serverWrapperFactory = new DirectServerWrapperFactory(); } } return serverWrapperFactory; } /** * Sets the default ServerWrapper. Should be called before setUp. * * @param newServerWrapper */ public static void setServerWrapperFactory(ServerWrapperFactory swf) { if (swf == null) { throw new IllegalArgumentException( "null is an illegal ServerWrapperFactory"); } serverWrapperFactory = swf; } /** * @param usingTcp * the useTcp to set */ public static void setUseTcp(boolean usingTcp) { if (usingTcp) { if ((serverWrapperFactory != null) && !serverWrapperFactory.usesTcp()) { serverWrapperFactory = null; } } else { if ((serverWrapperFactory != null) && serverWrapperFactory.usesTcp()) { serverWrapperFactory = null; } } RestletServerTestCase.usingTcp = usingTcp; } /** * @param response */ public static void sysOutEntity(Response response) { final Representation entity = response.getEntity(); try { if (entity != null) { System.out.println(entity.getText()); } else { System.out.println("[no Entity available]"); } } catch (IOException e) { System.out.println("Entity not readable: "); e.printStackTrace(System.out); } } /** * Utility method: Prints the entity to System.out, if the status indicates * an error. * * @param response * @throws IOException */ public static void sysOutEntityIfError(Response response) { if (response.getStatus().isError()) { sysOutEntity(response); } } /** * @param status * @param response */ public static void sysOutEntityIfNotStatus(Status status, Response response) { if (!response.getStatus().equals(status)) { sysOutEntity(response); } } /** * @return the useTcp */ public static boolean usesTcp() { return usingTcp; } /** * ServerWrapper to use. */ protected ServerWrapper serverWrapper; /** * */ public RestletServerTestCase() { super(); } /** * @param name */ public RestletServerTestCase(String name) { super(name); } public Response accessServer(Method httpMethod, Reference reference) { return accessServer(httpMethod, reference, null, null, null, null, null, null); } /** * access the server with the given values. * * @param httpMethod * The HTTP method to use. * @param reference * The {@link Reference} * @param accMediaTypes * the accepted {@link MediaType}s and/or {@link Preference}< * {@link MediaType}> (may be mixed). May be null or empty. * @param entity * the entity to send. null for GET and DELETE requests * @param challengeResponse * @param conditions * the conditions to send with the request. May be null. * @param addCookies * {@link Cookie}s to add to the {@link Request}. May be null. * @param addHeaders * headers to add to the request. May be null. * @return * @see #accessServer(Request) * @see #accessServer(Method, Reference) */ @SuppressWarnings("rawtypes") public Response accessServer(Method httpMethod, Reference reference, Collection accMediaTypes, Representation entity, ChallengeResponse challengeResponse, Conditions conditions, Collection addCookies, Collection addHeaders) { final Request request = new Request(httpMethod, reference); addAcceptedMediaTypes(request, accMediaTypes); request.setChallengeResponse(challengeResponse); request.setEntity(entity); request.setConditions(conditions); if (addCookies != null) { request.getCookies().addAll(addCookies); } if (addHeaders != null) { getHttpHeaders(request).addAll(addHeaders); } return accessServer(request); } /** * @param request * @return * @see #accessServer(Method, Reference) * @see #accessServer(Method, Reference, Collection, Representation, * ChallengeResponse, Conditions, Collection, Collection) */ public Response accessServer(Request request) { final Reference reference = request.getResourceRef(); if (reference.getBaseRef() == null) { reference.setBaseRef(reference.getHostIdentifier()); } request.setOriginalRef(reference.getTargetRef()); final Restlet connector = getClientConnector(); if (shouldAccessWithoutTcp()) { final String hostDomain = request.getResourceRef().getHostDomain(); getHttpHeaders(request).add("host", hostDomain); } Response response = new Response(request); connector.handle(request, response); if (!usingTcp && request.getMethod().equals(Method.HEAD)) { response.setEntity(new WrapperRepresentation(response.getEntity()) { @Override public ReadableByteChannel getChannel() throws IOException { return NioUtils.getChannel(getStream()); } @Override public Reader getReader() throws IOException { return new StringReader(""); } @Override public InputStream getStream() throws IOException { return new ByteArrayInputStream(new byte[0]); } @Override public String getText() { return null; } @Override public boolean isAvailable() { return false; } @Override public void write(OutputStream outputStream) throws IOException { } @Override public void write(WritableByteChannel writableChannel) throws IOException { } @Override public void write(Writer writer) throws IOException { } }); } return response; } /** * Creates the application and returns it. You can define other abstract * methods for this. */ protected abstract Application createApplication(); protected Reference createBaseRef() { final Reference reference = new Reference(); reference.setProtocol(Protocol.HTTP); reference.setAuthority("localhost"); if (!shouldAccessWithoutTcp()) { reference.setHostPort(getServerWrapper().getServerPort()); } return reference; } /** * @return */ private Restlet getClientConnector() { return getServerWrapper().getClientConnector(); } public int getServerPort() { return getServerWrapper().getServerPort(); } public ServerWrapper getServerWrapper() { if (this.serverWrapper == null) { this.serverWrapper = getServerWrapperFactory() .createServerWrapper(); } return this.serverWrapper; } /** * This methods shows information about the started server after starting * it.
* You may override this method to do what ever you want */ protected void runServerAfterStart() { System.out.print("server is accessable via http://localhost:"); System.out.println(getServerPort()); } /** *

* Starts the current test case as a normal HTTP server (sets * {@link #useTcp} to true), waits for an input from {@link System#in} and * then stops the server.
* After startup the method {@link #runServerAfterStart()} is called; you * may override it to give more information about the startet server. *

*

* This method is easy to use. Just instantiate the unit test case class and * call this method, e.g. in the main method. *

*/ public void runServerUntilKeyPressed() throws Exception { setUseTcp(true); startServer(createApplication()); runServerAfterStart(); System.out.println("press key to stop . . ."); System.in.read(); stopServer(); System.out.println("server stopped"); } public void setServerWrapper(ServerWrapper serverWrapper) { this.serverWrapper = serverWrapper; } @Override protected void setUp() throws Exception { super.setUp(); if (shouldStartServerInSetUp()) { startServer(createApplication()); } } /** * @return */ public boolean shouldAccessWithoutTcp() { return getServerWrapper() instanceof DirectServerWrapper; } public boolean shouldStartServerInSetUp() { return true; } /** * @param application * @throws Exception */ public void startServer() throws Exception { startServer(createApplication()); } /** * @param application * @throws Exception */ public void startServer(Application application) throws Exception { startServer(application, Protocol.HTTP); } /** * @param jaxRsApplication * @param protocol * @throws Exception */ protected void startServer(Application jaxRsApplication, Protocol protocol) throws Exception { try { getServerWrapper().startServer(jaxRsApplication, protocol); } catch (Exception e) { try { stopServer(); } catch (Exception e1) { // ignore exception, throw before catched Exception later } throw e; } } /** * @throws Exception * @see {@link #accessServer(Request)} */ protected void stopServer() throws Exception { if (this.serverWrapper != null) { this.serverWrapper.stopServer(); } this.serverWrapper = null; } @Override protected void tearDown() throws Exception { super.tearDown(); stopServer(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/ExceptionMappersTest.java0000664000175000017500000001141711757206354031337 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import junit.framework.TestCase; import org.restlet.engine.Engine; import org.restlet.ext.jaxrs.internal.core.MultivaluedMapImpl; import org.restlet.ext.jaxrs.internal.exceptions.JaxRsRuntimeException; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; import org.restlet.test.jaxrs.services.providers.IllegalArgExcMapper; /** * @author Stephan Koops * @see ExceptionMappers * @see IllegalArgExcMapper */ @SuppressWarnings("all") public class ExceptionMappersTest extends TestCase { private static final class TestHttpHeaders implements HttpHeaders { private final List accMediaTypes = new ArrayList(); /** * @see javax.ws.rs.core.HttpHeaders#getAcceptableLanguages() */ public List getAcceptableLanguages() { return new ArrayList(); } public List getAcceptableMediaTypes() { return this.accMediaTypes; } public Map getCookies() { return Collections.emptyMap(); } public Locale getLanguage() { return null; } public MediaType getMediaType() { return null; } public List getRequestHeader(String name) { return Collections.emptyList(); } public MultivaluedMap getRequestHeaders() { return new MultivaluedMapImpl(); } } private static final int INTERNAL_SERVER_ERROR = Status.INTERNAL_SERVER_ERROR .getStatusCode(); private JaxRsProviders exceptionMappers; /** * @param exc * @return */ private Response convert(Throwable exc) { return this.exceptionMappers.convert(exc); } /** * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); final IllegalArgExcMapper illegalArgExcMapper = new IllegalArgExcMapper(); illegalArgExcMapper.httpHeaders = new TestHttpHeaders(); this.exceptionMappers = new JaxRsProviders(null, null, null, Engine .getAnonymousLogger()); this.exceptionMappers.addSingleton(illegalArgExcMapper, false); } @Override protected void tearDown() throws Exception { this.exceptionMappers = null; super.tearDown(); } public void testIae() throws Exception { final Response r = convert(new IllegalArgumentException()); assertNotNull(r); assertEquals(IllegalArgExcMapper.STATUS, r.getStatus()); } public void testIoe() throws Exception { IOException ioException = new IOException( "This exception is planned for testing !"); try { Response r = convert(ioException); assertEquals(500, r.getStatus()); } catch (JaxRsRuntimeException e) { assertEquals(ioException, e.getCause()); } } public void testNfe() throws Exception { final Response r = convert(new NumberFormatException()); assertNotNull(r); assertEquals(IllegalArgExcMapper.STATUS, r.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/package-info.java0000664000175000017500000000300411757206352027524 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Implementations of package javax.ws.rs.core. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops */ package org.restlet.test.jaxrs; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/0000775000175000017500000000000011757206354025317 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/TestUtils.java0000664000175000017500000000615611757206352030130 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Set; import javax.ws.rs.core.MediaType; import org.restlet.engine.io.BioUtils; import org.restlet.ext.jaxrs.internal.util.Util; /** * Utility methods for the tests. * * @author Stephan Koops */ @SuppressWarnings("all") public class TestUtils { /** * @param objetcs * @return */ public static List createList(A... objects) { return Util.createList(objects); } public static MediaType createMediaType(String type, String subtype, String... keysAndValues) { return new MediaType(type, subtype, Util.createMap(keysAndValues)); } /** * @param rootResourceClass * @return */ public static Set createSet(A... objects) { return Util.createSet(objects); } /** * Reads the full inputStream and returns an byte-array of it * * @param inputStream * @return * @throws IOException */ public static byte[] getByteArray(InputStream inputStream) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(4096); BioUtils.copy(inputStream, byteStream); return byteStream.toByteArray(); } /** * @param list * @return */ public static A getLastElement(List list) { return Util.getLastElement(list); } /** * @param languages * @return */ public static A getOnlyElement(List languages) { return Util.getOnlyElement(languages); } /** * Sleeps 100 seconds. Will not throw an InterruptedException */ public static void sleep() { try { Thread.sleep(100); } catch (InterruptedException e) { // shit happens } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/OrderedReadonlySet.java0000664000175000017500000000747211757206354031732 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; /** * @author Stephan * */ public class OrderedReadonlySet implements Set { private final List elements; /** * * @param data will not check, if no duplicates are in the data */ public OrderedReadonlySet(E... data) { this.elements = Arrays.asList(data); } /** * @see java.util.Set#add(java.lang.Object) */ public boolean add(E o) { throw new UnsupportedOperationException("unmodifiable"); } /** * @see java.util.Set#addAll(java.util.Collection) */ public boolean addAll(Collection c) { throw new UnsupportedOperationException("unmodifiable"); } /** * @see java.util.Set#clear() */ public void clear() { throw new UnsupportedOperationException("unmodifiable"); } /** * @see java.util.Set#contains(java.lang.Object) */ public boolean contains(Object o) { throw new UnsupportedOperationException("not yet implemented"); } /** * @see java.util.Set#containsAll(java.util.Collection) */ public boolean containsAll(Collection c) { throw new UnsupportedOperationException("not yet implemented"); } /** * @see java.util.Set#isEmpty() */ public boolean isEmpty() { return elements.isEmpty(); } /** * @see java.util.Set#iterator() */ public Iterator iterator() { return elements.iterator(); } /** * @see java.util.Set#remove(java.lang.Object) */ public boolean remove(Object o) { throw new UnsupportedOperationException("unmodifiable"); } /** * @see java.util.Set#removeAll(java.util.Collection) */ public boolean removeAll(Collection c) { throw new UnsupportedOperationException("unmodifiable"); } /** * @see java.util.Set#retainAll(java.util.Collection) */ public boolean retainAll(Collection c) { throw new UnsupportedOperationException("unmodifiable"); } /** * @see java.util.Set#size() */ public int size() { return elements.size(); } /** * @see java.util.Set#toArray() */ public Object[] toArray() { throw new UnsupportedOperationException("not yet implemented"); } /** * @see java.util.Set#toArray(T[]) */ public T[] toArray(T[] a) { throw new UnsupportedOperationException("not yet implemented"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/RemainingPathTests.java0000664000175000017500000001173411757206352031737 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import java.lang.reflect.Method; import junit.framework.TestCase; import org.restlet.ext.jaxrs.internal.util.RemainingPath; /** * @author Stephan Koops * @see RemainingPath */ @SuppressWarnings("all") public class RemainingPathTests extends TestCase { /** * assertEqualsAfterRemove * * @param expected * @param actual */ public void aear(String expected, String actual) { try { Method removeMatrixParams = RemainingPath.class.getDeclaredMethod( "removeMatrixParams", String.class); removeMatrixParams.setAccessible(true); String removed = (String) removeMatrixParams.invoke(null, actual); assertEquals(expected, removed); } catch (Exception e) { throw new RuntimeException(e); } } public void testRemoveParams1() { aear("sdhfk/", "sdhfk;sdf"); aear("sdhfk/", "sdhfk;sdf=1"); aear("sdhfk/", "sdhfk;sdf=1?"); aear("sdhfk/", "sdhfk;sdf=1?x"); aear("sdhfk/", "sdhfk;sdf=1?x&"); aear("sdhfk/", "sdhfk;sdf=1?x&;"); aear("sdhfk/", "sdhfk;sdf=1?x&;/"); aear("sdhfk/", "sdhfk;sdf=1?x&;c/"); aear("sdhfk/", "sdhfk;sdf=1?x&;c/sdf"); } public void testRemoveParams11() { aear("/ddf/", ";/ddf"); aear("/ddf/", ";sdf/ddf"); aear("/ddf/", ";sdf=/ddf"); aear("/ddf/", ";sdf=sfsd/ddf"); aear("/ddf/", ";sdf=sfsd;/ddf"); aear("/ddf/", ";sdf=sfsd;sdf/ddf"); } public void testRemoveParams3() { aear("sdhfk/gkjj/", "sdhfk;sdf/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj?"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj?f"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj?f="); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj?f=5"); } public void testRemoveParams5() { aear("sdhfk/gkjj/", "sdhfk/gkjj"); aear("sdhfk/gkjj/", "sdhfk;/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff/gkjj"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj"); } public void testRemoveParams7() { aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj/"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;/"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;;/"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;dd/"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;dd=/"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;dd=we/"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;dd=we/;d"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;dd=we/;d=f"); aear("sdhfk/gkjj/", "sdhfk;sdf=1;ff=2/gkjj;dd=we/;d=f;"); } public void testRemoveParams9() { aear("sdhfk/gkjj/a/", "sdhfk;sdf=1;ff=2/gkjj/a"); } public void testRemoveParamsEmptyResult1() { aear("/", ";"); aear("/", ";df"); aear("/", ";df="); aear("/", ";df=sdfsdf"); aear("/", ";df=sdfsdf?"); aear("/", ";df=sdfsdf?sdf"); aear("/", ";df=sdfsdf?sdf="); aear("/", ";df=sdfsdf?sdf=sdffs"); } public void testRemoveParamsEmptyResult2() { aear("/", "?"); aear("/", "?df"); aear("/", "?df="); aear("/", "?df=sdfsdf"); aear("/", "?df=sdfsdf&"); aear("/", "?df=sdfsdf&sdf"); aear("/", "?df=sdfsdf&sdf="); aear("/", "?df=sdfsdf&sdf=sdffs"); aear("/", "?df=sdfsdf?sdf=sdffs"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/UtilTests.java0000664000175000017500000001636211757206352030130 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import junit.framework.TestCase; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.core.MultivaluedMapImpl; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.util.Util; /** * @author Stephan Koops * @see PathRegExp */ @SuppressWarnings("all") public class UtilTests extends TestCase { /** test interface for test of {@link Util#doesImplement(Class, Class)}. */ private static class C1 { } /** test class for test of {@link Util#doesImplement(Class, Class)}. */ private static class C2 extends C1 implements I1 { } /** test class for test of {@link Util#doesImplement(Class, Class)}. */ private static class C3 implements I1 { } /** test class for test of {@link Util#doesImplement(Class, Class)}. */ private static class C4 extends C3 { } /** test class for test of {@link Util#doesImplement(Class, Class)}. */ private static class C5 extends C3 implements I2 { } /** test interface for test of {@link Util#doesImplement(Class, Class)}. */ private static interface I1 { } /** test interface for test of {@link Util#doesImplement(Class, Class)}. */ private static interface I2 extends I1 { } private MultivaluedMap httpHeaders; private void checkPathTemplateWithoutRegExp(String expectedOut, String in) throws IllegalPathException { assertEquals(expectedOut, Util.getPathTemplateWithoutRegExps(in, null)); } private void checkPathTemplateWithoutRegExpIllegal(String in) { try { Util.getPathTemplateWithoutRegExps(in, null); fail("\"" + in + "\" must not be allowed"); } catch (IllegalPathException e) { // wonderful } } /** * @return the {@link CharacterSet} as String */ private String getCss() { return Util.getCharsetName(this.httpHeaders, null); } /** * @return the {@link MediaType} without any parameter */ private MediaType getMt() { final MediaType mediaType = Util.getMediaType(this.httpHeaders); if (mediaType == null) { return null; } return Converter.getMediaTypeWithoutParams(mediaType); } /** * @return the {@link MediaType} without any parameter as String */ private String getMts() { final MediaType mediaType = getMt(); if (mediaType == null) { return null; } return mediaType.toString(); } private void setContentType(MediaType mediaType, CharacterSet characterSet) { if (characterSet != null) { mediaType.getParameters().add("charset", characterSet.getName()); } setContentType(mediaType.toString()); } private void setContentType(String contentType) { this.httpHeaders.add(HttpHeaders.CONTENT_TYPE, contentType); } public void setUp() { this.httpHeaders = new MultivaluedMapImpl(); } @Override protected void tearDown() throws Exception { this.httpHeaders = null; super.tearDown(); } public void testDoesImplements() { assertTrue(Util.doesImplement(String.class, CharSequence.class)); assertFalse(Util.doesImplement(CharSequence.class, String.class)); assertFalse(Util.doesImplement(Object.class, CharSequence.class)); assertTrue(Util.doesImplement(Integer.class, Comparable.class)); assertFalse(Util.doesImplement(C1.class, I1.class)); assertFalse(Util.doesImplement(C1.class, I2.class)); assertTrue(Util.doesImplement(C2.class, I1.class)); assertFalse(Util.doesImplement(C2.class, I2.class)); assertTrue(Util.doesImplement(C3.class, I1.class)); assertFalse(Util.doesImplement(C3.class, I2.class)); assertTrue(Util.doesImplement(C4.class, I1.class)); assertFalse(Util.doesImplement(C4.class, I2.class)); assertTrue(Util.doesImplement(C5.class, I1.class)); assertTrue(Util.doesImplement(C5.class, I2.class)); } public void testGetOfContentType0() { assertEquals(null, getCss()); assertEquals(null, getMts()); } public void testGetOfContentType1() { setContentType("a/b;charset=CS"); assertEquals("CS", getCss()); assertEquals("a/b", getMts()); } public void testGetOfContentType2() { setContentType(MediaType.TEXT_HTML, null); assertEquals(null, getCss()); assertEquals(MediaType.TEXT_HTML, getMt()); } public void testGetOfContentType3() { setContentType("a/b ;charset=CS"); assertEquals("CS", getCss()); assertEquals("a/b", getMts()); } public void testGetOfContentType4() { setContentType("a/b;d=g;charset=CS"); assertEquals("CS", getCss()); assertEquals("a/b", getMts()); } public void testGetPathTemplateWithoutRegExp() throws IllegalPathException { checkPathTemplateWithoutRegExp("abc", "abc"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{de}fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{de:sd}fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{ de}fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{ de }fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{de }fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{de :}fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{de : }fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{de : yx}fg"); checkPathTemplateWithoutRegExp("abc{de}fg", "abc{de : yx }fg"); checkPathTemplateWithoutRegExpIllegal("abc{}hjk"); checkPathTemplateWithoutRegExpIllegal("abc{:}hjk"); checkPathTemplateWithoutRegExpIllegal("abc{:sdf}hjk"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/EncodeOrCheckTests.java0000664000175000017500000002520111757206352031637 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.restlet.ext.jaxrs.internal.util.EncodeOrCheck; /** * @author Stephan Koops * @see EncodeOrCheck */ @SuppressWarnings("all") public class EncodeOrCheckTests extends TestCase { static final Method FRAGMENT; static final Method FULL_MATRIX; static final Method FULL_QUERY; static final Method HOST; static final Method NAME_OR_VALUE; static final Method PATH_SEGMENT_WITH_MATRIX; static final Method PATH_WITHOUT_MATRIX; static final Method SCHEME; static final Method USER_INFO; static { try { FRAGMENT = EncodeOrCheck.class.getMethod("fragment", CharSequence.class); FULL_MATRIX = EncodeOrCheck.class.getMethod("fullMatrix", CharSequence.class); FULL_QUERY = EncodeOrCheck.class.getMethod("fullQuery", CharSequence.class, Boolean.TYPE); HOST = EncodeOrCheck.class.getMethod("host", String.class); NAME_OR_VALUE = EncodeOrCheck.class.getMethod("nameOrValue", Object.class, Boolean.TYPE, String.class); PATH_SEGMENT_WITH_MATRIX = EncodeOrCheck.class.getMethod( "pathSegmentWithMatrix", CharSequence.class, Boolean.TYPE); PATH_WITHOUT_MATRIX = EncodeOrCheck.class.getMethod( "pathWithoutMatrix", CharSequence.class); SCHEME = EncodeOrCheck.class.getMethod("scheme", String.class); USER_INFO = EncodeOrCheck.class.getMethod("userInfo", CharSequence.class, Boolean.TYPE); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } /** * @param method * static method. The in value is the first parameter. If the * method has two or three parameters, the second is the encode * value. If it has three arguments, a generic error message is * used for it. * @param in * @param encode * must not be null, if the method has more than one argument. * @param out * if null, an IllegalArgumentException must be thrown * @throws IllegalAccessException * @throws IllegalArgumentException * @throws RuntimeException */ private void check(Method method, String in, Boolean encode, String out) { Object result; try { final int paramCount = method.getParameterTypes().length; if (paramCount == 0) { throw new AssertionFailedError( ("The method " + method + " must have between 1 and 3 parameters")); } else if (paramCount == 1) { result = method.invoke(null, in); } else if ((paramCount == 2) && (encode != null)) { result = method.invoke(null, in, encode); } else if ((paramCount == 3) && (encode != null)) { result = method.invoke(null, in, encode, "{generic test error message}"); } else { throw new AssertionFailedError( ("The method " + method + " has to much parameters")); } if (paramCount > 1) { if (out == null) { fail("must throw an IllegalArgumentException for \"" + in + "\" and encode = " + encode); } assertEquals(out, result != null ? result.toString() : null); } } catch (InvocationTargetException e) { if (!(e.getCause() instanceof IllegalArgumentException)) { throw (RuntimeException) e.getCause(); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /** encoding necessary; not encoding must throw an exception */ void checkEncoding(Method method, String in, String encodedOut) { check(method, in, true, encodedOut); check(method, in, false, null); } void checkForInvalidCharFail(String uriPart) { try { EncodeOrCheck.checkForInvalidUriChars(uriPart, -1, ""); fail("\"" + uriPart + "\" contains an invalid char. The test must fail"); } catch (IllegalArgumentException e) { // wonderful } } /** * in String full invalid */ void checkInvalid(Method method, String in) { check(method, in, true, null); check(method, in, false, null); } /** * No encoding necessary */ void checkNoEncode(Method method, String testString) { check(method, testString, true, testString); check(method, testString, false, testString); } public void testCheckForInvalidUriChars() { final String allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890{}"; EncodeOrCheck.checkForInvalidUriChars(allowed, -1, ""); EncodeOrCheck.checkForInvalidUriChars("aaaaa", -1, ""); EncodeOrCheck.checkForInvalidUriChars("\\\\\\", -1, ""); checkForInvalidCharFail("a:a"); checkForInvalidCharFail("a:1"); checkForInvalidCharFail("/a:"); checkForInvalidCharFail("a:"); checkForInvalidCharFail("/"); checkForInvalidCharFail(" "); checkForInvalidCharFail("\0"); checkForInvalidCharFail("abc{ }kg jj"); EncodeOrCheck.checkForInvalidUriChars("abc{ }kgjj", -1, "test"); } public void testEncodePathWithoutMatrix() { EncodeOrCheck.pathWithoutMatrix(""); EncodeOrCheck.pathWithoutMatrix("%20"); } public void testFragment() { checkNoEncode(FRAGMENT, EncodeOrCheck.UNRESERVED); checkInvalid(FRAGMENT, "{}"); checkNoEncode(FRAGMENT, "dfd{ %K}7"); checkInvalid(FRAGMENT, "dfd{ { %K}}}7"); checkInvalid(FRAGMENT, "dfd{}7"); } public void testFullMatrixes() { xtestFullQueryOrMatrix(FULL_MATRIX, ';', '&'); checkEncoding(FULL_MATRIX, "jhg jk", "jhg%20jk"); } public void testFullQueries() { xtestFullQueryOrMatrix(FULL_QUERY, '&', ';'); checkEncoding(FULL_QUERY, "jhg jk", "jhg+jk"); } public void testHost() throws Exception { checkNoEncode(HOST, "a"); checkNoEncode(HOST, "a{sdf}f"); checkNoEncode(HOST, "a{ }f"); checkEncoding(HOST, "a{ } f", "a{ }%20f"); checkNoEncode(HOST, "98.76.54.32"); checkNoEncode(HOST, "9876:fg12::5432"); // host = IP-literal / IPv4address / reg-name // IP-literal = "[" ( IPv6address / IPvFuture ) "]" // IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) // NICE also allow national special chars etc. in a host } public void testNameOrValue() { checkNoEncode(NAME_OR_VALUE, ""); checkNoEncode(NAME_OR_VALUE, "sdf"); assertEquals("sdf%20hfdf", EncodeOrCheck.nameOrValue("sdf%20hfdf", false, "guj")); assertEquals("sdf%2520hfdf", EncodeOrCheck.nameOrValue("sdf%20hfdf", true, "guj")); checkEncoding(NAME_OR_VALUE, "abc def", "abc%20def"); final StringBuilder reservedEnc = new StringBuilder(); for (int i = 0; i < EncodeOrCheck.RESERVED.length(); i++) { EncodeOrCheck.toHex(EncodeOrCheck.RESERVED.charAt(i), reservedEnc); } checkEncoding(NAME_OR_VALUE, EncodeOrCheck.RESERVED, reservedEnc .toString()); } public void testPathSegmentWithMatrix() { checkNoEncode(PATH_SEGMENT_WITH_MATRIX, ""); checkNoEncode(PATH_SEGMENT_WITH_MATRIX, "sdf"); checkEncoding(PATH_SEGMENT_WITH_MATRIX, "abc def", "abc%20def"); checkNoEncode(PATH_SEGMENT_WITH_MATRIX, "abc;1298=213"); } public void testSchemeCheck() { // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) EncodeOrCheck.scheme("f"); } public void testUserInfo() { checkNoEncode(USER_INFO, ""); // userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) checkNoEncode(USER_INFO, "a"); checkNoEncode(USER_INFO, "a{g}a"); checkNoEncode(USER_INFO, "a{g }a"); checkNoEncode(USER_INFO, "user:password"); checkEncoding(USER_INFO, "a{g } a", "a{g }%20a"); } /** * @param delim * ';' or '&' * @param nonDelim * '&' or ';' */ private void xtestFullQueryOrMatrix(Method method, char delim, char nonDelim) { final String nonDelimStr = (nonDelim == ';' ? "%3B" : "%26"); final String str = "jshfk=kzi" + delim + "hk=" + delim + "k" + delim + delim; checkNoEncode(method, str); checkEncoding(method, str + nonDelim, str + nonDelimStr); checkNoEncode(method, ""); // LATER is the following right? checkEncoding(method, "%20", "%2520"); checkEncoding(method, delim + "=" + nonDelim + "?", delim + "=" + nonDelimStr + "%3F"); checkNoEncode(method, "{s&?df}"); checkNoEncode(method, "{sdf}"); checkNoEncode(method, delim + "{sdf}"); checkInvalid(method, "gg{nk{}}"); checkInvalid(method, "gg{nk{"); checkInvalid(method, "gg}ff"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/package-info.java0000664000175000017500000000305211757206352030504 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Tests for the classes of package {@link org.restlet.ext.jaxrs.internal.util}. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops */ package org.restlet.test.jaxrs.util; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/SortedOrderedBagTest.java0000664000175000017500000001023411757206352032177 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import junit.framework.TestCase; import org.restlet.ext.jaxrs.internal.util.SortedOrderedBag; /** * @author Stephan Koops * @see SortedOrderedBag */ @SuppressWarnings("all") public class SortedOrderedBagTest extends TestCase { public void test2() { SortedOrderedBag sob = new SortedOrderedBag(); sob.add(1); assertEqualsSOB(sob, 1); sob.add(1); assertEqualsSOB(sob, 1, 1); sob.add(1); assertEqualsSOB(sob, 1, 1, 1); sob.add(0); assertEqualsSOB(sob, 0, 1, 1, 1); sob.add(4); assertEqualsSOB(sob, 0, 1, 1, 1, 4); sob.add(2); assertEqualsSOB(sob, 0, 1, 1, 1, 2, 4); } public void test1() { SortedOrderedBag sob = new SortedOrderedBag(); sob.add(1); assertEqualsSOB(sob, 1); sob.add(2); assertEqualsSOB(sob, 1, 2); sob.add(3); assertEqualsSOB(sob, 1, 2, 3); sob.add(4); assertEqualsSOB(sob, 1, 2, 3, 4); sob.add(5); assertEqualsSOB(sob, 1, 2, 3, 4, 5); sob.add(6); assertEqualsSOB(sob, 1, 2, 3, 4, 5, 6); } public void test0() { SortedOrderedBag sob = new SortedOrderedBag(); sob.add(6); assertEqualsSOB(sob, 6); sob.add(5); assertEqualsSOB(sob, 5, 6); sob.add(4); assertEqualsSOB(sob, 4, 5, 6); sob.add(3); assertEqualsSOB(sob, 3, 4, 5, 6); sob.add(2); assertEqualsSOB(sob, 2, 3, 4, 5, 6); sob.add(1); assertEqualsSOB(sob, 1, 2, 3, 4, 5, 6); } public void test3() { SortedOrderedBag sob = new SortedOrderedBag(); sob.add(1); assertEqualsSOB(sob, 1); sob.add(1); assertEqualsSOB(sob, 1, 1); sob.add(0); assertEqualsSOB(sob, 0, 1, 1); sob.add(4); assertEqualsSOB(sob, 0, 1, 1, 4); sob.add(2); assertEqualsSOB(sob, 0, 1, 1, 2, 4); } public void testString() { SortedOrderedBag sob = new SortedOrderedBag( String.CASE_INSENSITIVE_ORDER); sob.add("a"); assertEqualsSOB(sob, "a"); sob.add("b"); assertEqualsSOB(sob, "a", "b"); sob.add("B"); assertEqualsSOB(sob, "a", "b", "B"); sob.add("b"); assertEqualsSOB(sob, "a", "b", "B", "b"); sob.add("A"); assertEqualsSOB(sob, "a", "A", "b", "B", "b"); } public static
void assertEqualsSOB(SortedOrderedBag given, A... expected) { // System.out.println("given = " + given); // System.out.println("expected=" + Arrays.asList(expected)); assertEquals("the size differs:", expected.length, given.size()); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], given.get(i)); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/PathRegExpTests.java0000664000175000017500000001736611757206352031227 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import java.lang.reflect.Constructor; import javax.ws.rs.Path; import junit.framework.TestCase; import org.restlet.ext.jaxrs.internal.util.MatchingResult; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.util.RemainingPath; /** * @author Stephan Koops * @see PathRegExp */ public class PathRegExpTests extends TestCase { static final String ID1 = "id1"; static final String ID2 = "id2"; /** as {@link #PATH_PATTERN_2} but without "/" at end */ static final String PATH_PATTERN_1 = "/abc/{" + ID1 + "}/shf/{" + ID2 + "}/xyz"; /** as {@link #PATH_PATTERN_1} but with "/" at end */ static final String PATH_PATTERN_2 = PATH_PATTERN_1 + "/"; /** as {@link #VALID_PATH_2} but without "/" at end */ static final String VALID_PATH_1 = "/abc/25478/shf/12345/xyz"; /** as {@link #VALID_PATH_2} but without "/" at end */ static final RemainingPath VALID_PATH_1_RP = new RemainingPath(VALID_PATH_1); /** as {@link #VALID_PATH_1} but with "/" at end */ public static final String VALID_PATH_2 = VALID_PATH_1 + "/"; /** as {@link #VALID_PATH_1} but with "/" at end */ public static final RemainingPath VALID_PATH_2_RP = new RemainingPath( VALID_PATH_2); private static final PathRegExp newPathRegExp(String pathPattern) { try { final Constructor constructor; final Class pathRegExpClass = PathRegExp.class; constructor = pathRegExpClass.getDeclaredConstructor(String.class, Path.class); constructor.setAccessible(true); return constructor.newInstance(pathPattern, null); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } private final PathRegExp regExpMultipleSegments1 = newPathRegExp(PATH_PATTERN_1); private final PathRegExp regExpMultipleSegments2 = newPathRegExp(PATH_PATTERN_2); private final PathRegExp regExpOneSegment1 = newPathRegExp(PATH_PATTERN_1); private final PathRegExp regExpOneSegment2 = newPathRegExp(PATH_PATTERN_2); /** * Test method for * {@link org.restlet.ext.jaxrs.internal.util.PathRegExp#match(java.lang.String)} . */ public void testMatchM1() { MatchingResult matchingResult = this.regExpMultipleSegments1 .match(VALID_PATH_1_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); assertEquals(new RemainingPath(""), matchingResult .getFinalCapturingGroup()); matchingResult = this.regExpMultipleSegments1.match(VALID_PATH_2_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); assertEquals(new RemainingPath(""), matchingResult .getFinalCapturingGroup()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.util.PathRegExp#match(java.lang.String)} . */ public void testMatchM2() { MatchingResult matchingResult = this.regExpMultipleSegments2 .match(VALID_PATH_1_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); matchingResult = this.regExpMultipleSegments2.match(VALID_PATH_2_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); assertEquals(new RemainingPath(""), matchingResult .getFinalCapturingGroup()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.util.PathRegExp#match(java.lang.String)} . */ public void testMatchM3() { final String rest = "/jkgjg"; tryWithRest(rest); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.util.PathRegExp#match(java.lang.String)} . */ public void testMatchM4() { final String rest = "/qarear/iuguz/izu/"; tryWithRest(rest); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.util.PathRegExp#match(java.lang.String)} . */ public void testMatchO1() { final MatchingResult matchingResult = this.regExpOneSegment1 .match(VALID_PATH_1_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); assertEquals(new RemainingPath(""), matchingResult .getFinalCapturingGroup()); this.regExpOneSegment1.match(VALID_PATH_2_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); assertEquals(new RemainingPath(""), matchingResult .getFinalCapturingGroup()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.util.PathRegExp#match(java.lang.String)} . */ public void testMatchO21() { MatchingResult matchingResult = this.regExpOneSegment2 .match(VALID_PATH_1_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); matchingResult = this.regExpOneSegment2.match(VALID_PATH_2_RP); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); assertEquals(new RemainingPath(""), matchingResult .getFinalCapturingGroup()); } /** * @param rest */ private void tryWithRest(final String rest) { final MatchingResult matchingResult = this.regExpMultipleSegments2 .match(new RemainingPath(VALID_PATH_2 + rest)); assertNotNull(matchingResult); assertEquals("25478", matchingResult.getVariables().get(ID1)); assertEquals("12345", matchingResult.getVariables().get(ID2)); assertEquals(new RemainingPath(rest), matchingResult .getFinalCapturingGroup()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/ConverterTests.java0000664000175000017500000000725411757206354031164 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import static org.restlet.ext.jaxrs.internal.util.Converter.getMediaTypeWithoutParams; import static org.restlet.ext.jaxrs.internal.util.Converter.toLanguage; import static org.restlet.ext.jaxrs.internal.util.Converter.toLocale; import java.util.Locale; import junit.framework.TestCase; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.util.PathRegExp; /** * @author Stephan Koops * @see PathRegExp */ @SuppressWarnings("all") public class ConverterTests extends TestCase { private void checkToLanguageToLocale(Locale locale) { assertEquals(locale, toLocale(toLanguage(locale))); } public void testGetMediaTypeWitoutParams1() { assertEquals(null, getMediaTypeWithoutParams((MediaType) null)); assertEquals(MediaType.TEXT_HTML, getMediaTypeWithoutParams(MediaType.TEXT_HTML)); } public void testGetMediaTypeWitoutParams2() { Form params = new Form(); params.add("abc", "def"); final MediaType mt = new MediaType("a/b", params); assertEquals("a/b", getMediaTypeWithoutParams(mt).toString()); } public void testToLanguageToLocale() { checkToLanguageToLocale(Locale.CANADA); checkToLanguageToLocale(Locale.CANADA_FRENCH); checkToLanguageToLocale(Locale.CHINA); checkToLanguageToLocale(Locale.CHINESE); checkToLanguageToLocale(Locale.ENGLISH); checkToLanguageToLocale(Locale.FRANCE); checkToLanguageToLocale(Locale.FRENCH); checkToLanguageToLocale(Locale.GERMAN); checkToLanguageToLocale(Locale.GERMANY); checkToLanguageToLocale(Locale.ITALIAN); checkToLanguageToLocale(Locale.ITALY); checkToLanguageToLocale(Locale.JAPAN); checkToLanguageToLocale(Locale.JAPANESE); checkToLanguageToLocale(Locale.KOREA); checkToLanguageToLocale(Locale.KOREAN); checkToLanguageToLocale(Locale.PRC); checkToLanguageToLocale(Locale.SIMPLIFIED_CHINESE); checkToLanguageToLocale(Locale.TAIWAN); checkToLanguageToLocale(Locale.TRADITIONAL_CHINESE); checkToLanguageToLocale(Locale.UK); checkToLanguageToLocale(Locale.US); } public void testToLocale() { assertEquals(new Locale("abc"), toLocale("abc")); assertEquals(new Locale("abc", "", "def"), toLocale("abc__def")); assertEquals(new Locale("abc", "def"), toLocale("abc_def")); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/util/OrderedMapTest.java0000664000175000017500000000364511757206352031052 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.util; import junit.framework.TestCase; import org.restlet.ext.jaxrs.internal.util.OrderedMap; /** * @author Stephan Koops * @see OrderedMap */ @SuppressWarnings("all") public class OrderedMapTest extends TestCase { public void test2() { OrderedMap sob = new OrderedMap(); sob.add("a", 1); assertEquals("[a -> 1]", sob.toString()); sob.add("b", 2); assertEquals("[a -> 1, b -> 2]", sob.toString()); sob.add("d", 1); assertEquals("[a -> 1, b -> 2, d -> 1]", sob.toString()); sob.add("c", 0); assertEquals("[a -> 1, b -> 2, d -> 1, c -> 0]", sob.toString()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/core/0000775000175000017500000000000011757206354025272 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/core/UriInfoTest.java0000664000175000017500000003025711757206352030355 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.core; import java.net.URI; import java.util.List; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import junit.framework.TestCase; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.ext.jaxrs.RoleChecker; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; /** * @author Stephan Koops * @see ThreadLocalizedUriInfo * @see UriInfo */ @SuppressWarnings("all") public class UriInfoTest extends TestCase { private static final String BASE_REF_STR = "http://localhost/test/"; private static final Reference BASE_REF = new Reference(BASE_REF_STR); private static final String RELATIV_1 = "relativ/a/b"; private static final String RELATIV_2 = "relativ/%20a%20/%21b%40%2C"; private static final String RELATIV_2_DECODED = "relativ/ a /!b@,"; private static final Reference REFERENCE_1 = new Reference(BASE_REF, BASE_REF_STR + RELATIV_1); private static final Reference REFERENCE_2 = new Reference(BASE_REF, BASE_REF_STR + RELATIV_2); protected static void assertUnmodifiable( MultivaluedMap multivaluedMap) { try { multivaluedMap.add("jh,", "hkj"); } catch (NotYetImplementedException usoe) { throw usoe; } catch (UnsupportedOperationException usoe) { // must be thrown, because it should be unmodifiable } }; private static final UriInfo createUriInfo1() { return newUriInfo(REFERENCE_1, BASE_REF); }; private static final UriInfo createUriInfo2() { return newUriInfo(REFERENCE_2, BASE_REF); }; private static final ThreadLocalizedUriInfo createUriInfo5() { return newUriInfo(new Reference(BASE_REF, BASE_REF_STR + "hfk;abc=%20def;ghi=jkl"), BASE_REF); }; private static final ThreadLocalizedUriInfo createUriInfo7() { return newUriInfo(new Reference(BASE_REF, BASE_REF_STR + "abc?def=123&ghi=456"), BASE_REF); }; private static final ThreadLocalizedUriInfo createUriInfo8() { return newUriInfo(new Reference(BASE_REF, BASE_REF_STR + "abc?def=1+23&gh%20i=45%206"), BASE_REF); } /** * creates a new UriInfo object. *

* You could only use one of these UriInfos at the same time !!! * * @param resourceRef * @param rootRef * @return */ static ThreadLocalizedUriInfo newUriInfo(Reference resourceRef, Reference rootRef) { final Request request = new Request(); request.setResourceRef(resourceRef); request.setOriginalRef(resourceRef); request.setRootRef(rootRef); final Response response = new Response(request); Response.setCurrent(response); final CallContext callContext = new CallContext(request, response, RoleChecker.REJECT_WITH_ERROR); final ThreadLocalizedContext tlContext = new ThreadLocalizedContext(); tlContext.set(callContext); return new ThreadLocalizedUriInfo(tlContext); } // the Template parameters are tested in SimpleTrain and SimpleTrainTest private void checkEntry(String expectedValue, String key, MultivaluedMap templateParameters) { assertEquals(expectedValue, templateParameters.getFirst(key)); } /** * @param pathSegments * @param path0 * @param tpSize0 * templatParamaterSize * @param path1 * @param tpSize1 * @param path2 * @param tpSize2 */ private void checkPathSegments(List pathSegments, String path0, int tpSize0, String path1, int tpSize1, String path2, int tpSize2) { assertEquals(3, pathSegments.size()); final PathSegment pathSegment0 = pathSegments.get(0); final PathSegment pathSegment1 = pathSegments.get(1); final PathSegment pathSegment2 = pathSegments.get(2); assertEquals(path0, pathSegment0.getPath()); assertEquals(tpSize0, pathSegment0.getMatrixParameters().size()); assertEquals(path1, pathSegment1.getPath()); assertEquals(tpSize1, pathSegment1.getMatrixParameters().size()); assertEquals(path2, pathSegment2.getPath()); assertEquals(tpSize2, pathSegment2.getMatrixParameters().size()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getAbsolutePath()} * . */ public void testGetAbsolutePath() throws Exception { UriBuilderImplTest.assertEqualsURI(BASE_REF_STR + RELATIV_1, createUriInfo1().getAbsolutePath()); UriBuilderImplTest.assertEqualsURI(BASE_REF_STR + RELATIV_2, createUriInfo2().getAbsolutePath()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getAbsolutePathBuilder()} * . */ public void testGetAbsolutePathBuilder() throws Exception { UriBuilderImplTest.assertEqualsURI(BASE_REF_STR + RELATIV_1, createUriInfo1().getAbsolutePathBuilder()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getBaseUri()} * . */ public void testGetBaseUri() { final URI baseUri1 = createUriInfo1().getBaseUri(); assertEquals(BASE_REF_STR, baseUri1.toString()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getBaseUriBuilder()} * . */ public void testGetBaseUriBuilder() throws Exception { final URI uri = createUriInfo1().getBaseUri(); UriBuilderImplTest.assertEqualsURI(BASE_REF_STR, uri); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getPath()} * . */ public void testGetPath() { assertEquals(RELATIV_1, createUriInfo1().getPath()); assertEquals(RELATIV_2_DECODED, createUriInfo2().getPath()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getPath(boolean)} * . */ public void testGetPathBoolean() { assertEquals(RELATIV_1, createUriInfo1().getPath(true)); assertEquals(RELATIV_1, createUriInfo1().getPath(false)); assertEquals(RELATIV_2_DECODED, createUriInfo2().getPath(true)); assertEquals(RELATIV_2, createUriInfo2().getPath(false)); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getPathSegments()} * . */ public void testGetPathSegments() { // must be alid for every UriInfo assertEquals(createUriInfo1().getPathSegments(true), createUriInfo1() .getPathSegments()); assertEquals(createUriInfo2().getPathSegments(true), createUriInfo2() .getPathSegments()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getPathSegments(boolean)} * . */ public void testGetPathSegmentsBoolean() { checkPathSegments(createUriInfo1().getPathSegments(true), "relativ", 0, "a", 0, "b", 0); checkPathSegments(createUriInfo1().getPathSegments(false), "relativ", 0, "a", 0, "b", 0); checkPathSegments(createUriInfo2().getPathSegments(true), "relativ", 0, " a ", 0, "!b@,", 0); checkPathSegments(createUriInfo2().getPathSegments(false), "relativ", 0, "%20a%20", 0, "%21b%40%2C", 0); final UriInfo uriInfo = newUriInfo(new Reference(BASE_REF, BASE_REF_STR + "abc/def;ghi=jkl;mno=pqr/stu;vwx=yz"), BASE_REF); final List pathSegments = uriInfo.getPathSegments(); checkPathSegments(pathSegments, "abc", 0, "def", 2, "stu", 1); final MultivaluedMap templateParameters1 = pathSegments .get(1).getMatrixParameters(); assertEquals(2, templateParameters1.size()); checkEntry("jkl", "ghi", templateParameters1); checkEntry("pqr", "mno", templateParameters1); final MultivaluedMap templateParameters2 = pathSegments .get(2).getMatrixParameters(); assertEquals(1, templateParameters2.size()); checkEntry("yz", "vwx", templateParameters2); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getQueryParameters(boolean)} * . */ public void testGetQueryParametersDecoded() { assertEquals("123", createUriInfo7().getQueryParameters(true).getFirst( "def")); assertEquals("456", createUriInfo7().getQueryParameters(true).getFirst( "ghi")); assertEquals(2, createUriInfo7().getQueryParameters(true).size()); assertEquals("1 23", createUriInfo8().getQueryParameters(true) .getFirst("def")); assertEquals("45 6", createUriInfo8().getQueryParameters(true) .getFirst("gh i")); assertEquals(2, createUriInfo8().getQueryParameters(true).size()); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getQueryParameters()} * . */ public void testGetQueryParametersEncoded() { assertEquals("123", createUriInfo7().getQueryParameters(false) .getFirst("def")); assertEquals("456", createUriInfo7().getQueryParameters(false) .getFirst("ghi")); assertEquals(2, createUriInfo7().getQueryParameters(false).size()); assertEquals("1+23", createUriInfo8().getQueryParameters(false) .getFirst("def")); assertEquals("45%206", createUriInfo8().getQueryParameters(false) .getFirst("gh%20i")); assertEquals(2, createUriInfo8().getQueryParameters(false).size()); } public void testGetQueryParametersUnmodifiable() { assertUnmodifiable(createUriInfo5().getQueryParameters(true)); assertUnmodifiable(createUriInfo5().getQueryParameters(false)); } /** * Test method for * {@link org.restlet.ext.jaxrs.internal.core.ThreadLocalizedUriInfo#getRequestUri()} * . */ public void testGetRequestUri() throws Exception { final URI uri1 = createUriInfo1().getRequestUri(); assertEquals(new URI("http://localhost/test/relativ/a/b"), uri1); } public void testGetRequestUriBuilder() throws Exception { final UriBuilder uriBuilder1 = createUriInfo1().getRequestUriBuilder(); UriBuilderImplTest.assertEqualsURI( "http://localhost/test/relativ/a/b", uriBuilder1); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/core/ExtendedJaxRsUriBuilderTest.java0000664000175000017500000006636411757206354033513 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.core; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.restlet.Application; import org.restlet.data.Reference; import org.restlet.ext.jaxrs.ExtendedUriBuilder; import org.restlet.test.jaxrs.services.car.CarListResource; import org.restlet.test.jaxrs.services.car.CarResource; import org.restlet.test.jaxrs.services.resources.SimpleTrain; /** * @author Stephan Koops * @see ExtendedUriBuilder */ public class ExtendedJaxRsUriBuilderTest extends TestCase { private static final String TEMPL_VARS_EXPECTED = "abc://username:password@www.secure.org:8080/def/ghi;jkl=mno/pqr.yz;stu=vwx?ABC=DEF&GHI=JKL#MNO"; private static final URI URI_NO_EXT; static { try { URI_NO_EXT = new URI("http://localhost/path1/path2"); } catch (URISyntaxException e) { throw new RuntimeException( "Can not initialize ExtendedJaxRsUriBuilderTest"); } } /** * @param expectedUri * @param actualUri * @throws URISyntaxException */ static void assertEqualsURI(String expectedUri, URI actualUri) throws URISyntaxException { UriBuilderImplTest.assertEqualsURI(expectedUri, actualUri); } static void assertEqualsURI(String expectedUri, ExtendedUriBuilder actualBuilder) throws Exception { UriBuilderImplTest.assertEqualsURI(expectedUri, actualBuilder); } static void assertEqualsURI(String expectedUri, ExtendedUriBuilder actualBuilder, boolean encode) throws Exception { UriBuilderImplTest.assertEqualsURI(expectedUri, actualBuilder, encode); } static void assertEqualsUriSlashAllowed(String expectedUri, ExtendedUriBuilder actual) throws URISyntaxException { UriBuilderImplTest.assertEqualsUriSlashAllowed(expectedUri, actual); } /** * Note, that the actual value is at the beginning, because of the * expectedPathSegents must be the last parameter. * * @param expectedScheme * @param expectedUserInfo * @param expectedHost * @param expectedPort * @param expectedExtension * @param expectedQuery * @param actualUriBuilder * @param compareResult * if true, also the builded URIs are compared (this causes * trouble sometimes, e.g. with "/"). * @param expectedPathSegments */ private static void assertEqualUriBuilder(String expectedScheme, String expectedUserInfo, String expectedHost, String expectedPort, String expectedPath, String expectedExtension, String expectedQuery, ExtendedUriBuilder actualUriBuilder, boolean compareResult) throws Exception { assertEquals(expectedScheme, getScheme(actualUriBuilder)); assertEquals(expectedUserInfo, getUserInfo(actualUriBuilder)); assertEquals(expectedHost, getHost(actualUriBuilder)); assertEquals(expectedPort, getPort(actualUriBuilder)); final String actPath = getPath(actualUriBuilder); try { assertEquals(expectedPath, actPath); } catch (junit.framework.ComparisonFailure cf) { if (expectedPath == null) assertEquals("", actPath); } assertEquals(expectedExtension, actualUriBuilder.getExtension()); CharSequence actualQuery = getQuery(actualUriBuilder); if (actualQuery != null) { actualQuery = actualQuery.toString(); } assertEquals(expectedQuery, actualQuery); if (compareResult) { ExtendedUriBuilder expectedUriBuilder = ExtendedUriBuilder .newInstance(); if (expectedScheme != null) { expectedUriBuilder.scheme(expectedScheme); } if (expectedUserInfo != null) { expectedUriBuilder.userInfo(expectedUserInfo); } if (expectedHost != null) { expectedUriBuilder.host(expectedHost); } expectedUriBuilder.port(expectedPort); expectedUriBuilder.path(expectedPath); expectedUriBuilder.extension(expectedExtension); if (expectedQuery != null) { expectedUriBuilder.replaceQuery(expectedQuery); } String expectedURI = expectedUriBuilder.build().toString(); String atualURI = actualUriBuilder.build().toString(); assertEquals(expectedURI, atualURI); } } /** * @param uriBuilderImpl * @return */ private static String getHost(ExtendedUriBuilder uriBuilderImpl) throws Exception { return UriBuilderImplTest.getFieldValue(uriBuilderImpl, "host"); } private static String getPath(ExtendedUriBuilder uriBuilderImpl) throws Exception { final Object path = UriBuilderImplTest.getFieldValue(uriBuilderImpl, "path"); if (path == null) { return null; } return path.toString(); } private static String getPort(ExtendedUriBuilder uriBuilderImpl) throws Exception { return UriBuilderImplTest.getFieldValue(uriBuilderImpl, "port"); } private static String getQuery(ExtendedUriBuilder uriBuilderImpl) throws Exception { return UriBuilderImplTest.getFieldValue(uriBuilderImpl, "query"); } private static String getScheme(ExtendedUriBuilder uriBuilderImpl) throws Exception { return UriBuilderImplTest.getFieldValue(uriBuilderImpl, "scheme"); } private static String getUserInfo(ExtendedUriBuilder uriBuilderImpl) throws Exception { return UriBuilderImplTest.getFieldValue(uriBuilderImpl, "userInfo"); } private ExtendedUriBuilder uriBuilder; /** * UriBuilder with variableNames. */ private ExtendedUriBuilder uriBuilderWithVars; private URI buildFromTemplVarsWithMap(ExtendedUriBuilder uriBuilder) { final Map vars = new HashMap(); vars.put("scheme", "abc"); vars.put("userInfo", "username:password"); vars.put("host", "www.secure.org"); vars.put("port", "8080"); vars.put("path1", "def"); vars.put("path2", "ghi"); vars.put("mp2Name", "jkl"); vars.put("mp2Value", "mno"); vars.put("path3", "pqr"); vars.put("mp3Name", "stu"); vars.put("mp3Value", "vwx"); vars.put("extension", "yz"); vars.put("qp1Name", "ABC"); vars.put("qp1Value", "DEF"); vars.put("qp2Name", "GHI"); vars.put("qp2Value", "JKL"); vars.put("fragment", "MNO"); return uriBuilder.buildFromMap(vars); } private URI buildFromTemplVarsWithStrings(ExtendedUriBuilder uriBuilder) { return uriBuilder.build("abc", "username:password", "www.secure.org", "8080", "def", "ghi", "jkl", "mno", "pqr", "yz", "stu", "vwx", "ABC", "DEF", "GHI", "JKL", "MNO"); } private void changeWithTemplVars(ExtendedUriBuilder uriBuilder) throws IllegalArgumentException { uriBuilder.scheme("{scheme}"); uriBuilder.userInfo("{userInfo}"); uriBuilder.host("{host}"); uriBuilder.port("{port}"); uriBuilder.replacePath("{path1}"); uriBuilder.path("{path2}"); uriBuilder.replaceMatrix("{mp2Name}={mp2Value}"); uriBuilder.path("{path3}"); uriBuilder.matrixParam("{mp3Name}", "{mp3Value}"); uriBuilder.replaceQuery("{qp1Name}={qp1Value}"); uriBuilder.queryParam("{qp2Name}", "{qp2Value}"); uriBuilder.fragment("{fragment}"); } @Override protected void setUp() throws Exception { super.setUp(); Application.setCurrent(new Application()); this.uriBuilder = ExtendedUriBuilder.newInstance(); this.uriBuilder.host("localhost"); this.uriBuilder.segment("path1", "path2"); this.uriBuilder.scheme("http"); this.uriBuilderWithVars = ExtendedUriBuilder.newInstance(); this.uriBuilderWithVars.host("localhost"); this.uriBuilderWithVars.scheme("http"); this.uriBuilderWithVars.segment("abc", "{var1}", "def", "{var2}"); this.uriBuilderWithVars.extension("{extension}"); } /** * Test method for {@link ExtendedUriBuilder#build(String[])}. */ public void testBuildFromArray() throws Exception { try { this.uriBuilderWithVars.build("123"); fail("must fail, because there are not enough arguments"); } catch (IllegalArgumentException e) { // wonderful } URI uri = this.uriBuilderWithVars.build("123", "456", ""); assertEqualsURI("http://localhost/abc/123/def/456.", uri); ExtendedUriBuilder uriBuilder2 = this.uriBuilderWithVars.clone(); assertEqualsURI("http://localhost/abc/123/def/456.html", uriBuilder2 .build("123", "456", "html")); assertEquals(this.uriBuilderWithVars.toString(), uriBuilder2.toString()); uriBuilder2.path("{var3}"); uri = this.uriBuilderWithVars.build("123", "456", "pdf"); assertEqualsURI("http://localhost/abc/123/def/456.pdf", uri); try { uriBuilder2.build("123", "456"); fail("must fail, because there are not enough arguments"); } catch (IllegalArgumentException e) { // wonderful } final URI uri2 = uriBuilder2.build("123", "456", "789", ""); assertEqualsURI("http://localhost/abc/123/def/456/789.", uri2); } /** * Test method for {@link ExtendedUriBuilder#build(Map)}. */ public void testBuildFromMap() throws Exception { final Map vars = new HashMap(); try { this.uriBuilderWithVars.buildFromMap(vars); fail("must fail, because missing UriTemplate variables"); } catch (IllegalArgumentException e) { // wonderful } vars.put("var1", "123"); try { this.uriBuilderWithVars.buildFromMap(vars); fail("must fail, because missing UriTemplate variable"); } catch (IllegalArgumentException e) { // wonderful } vars.put("var2", "456"); vars.put("extension", "odt"); assertEqualsURI("http://localhost/abc/123/def/456.odt", this.uriBuilderWithVars.buildFromMap(vars)); vars.put("var3", "789"); assertEqualsURI("http://localhost/abc/123/def/456.odt", this.uriBuilderWithVars.buildFromMap(vars)); vars.put("var2", " "); assertEqualsURI("http://localhost/abc/123/def/%20.odt", this.uriBuilderWithVars.buildFromMap(vars)); } public void testBuildWithArgs() throws Exception { assertEquals(URI_NO_EXT, this.uriBuilder.build("a", "b")); assertEquals(URI_NO_EXT, this.uriBuilder.build(" ", "b")); URI uri = this.uriBuilderWithVars.build("a", "b", "odt"); assertEqualsURI("http://localhost/abc/a/def/b.odt", uri); uri = this.uriBuilderWithVars.build("%20", "b", "xml"); assertEqualsURI("http://localhost/abc/%2520/def/b.xml", uri); uri = this.uriBuilderWithVars.build(" ", "b", ""); assertEqualsURI("http://localhost/abc/%20/def/b.", uri); } /** * Test method for {@link ExtendedUriBuilder#build()}. */ public void testBuildWithoutArgs() throws Exception { assertEquals(URI_NO_EXT, this.uriBuilder.build()); try { this.uriBuilderWithVars.build(); fail("must fail, because vars are required"); } catch (IllegalArgumentException ube) { // wonderful } } /** * Test method for {@link ExtendedUriBuilder#clone()}. */ public void testClone() { assertEquals(this.uriBuilder.build(), this.uriBuilder.clone().build()); } /** * Test method for {@link ExtendedUriBuilder#encode(boolean)} . */ public void testEncode() throws Exception { ExtendedUriBuilder uriBuilder = ExtendedUriBuilder.newInstance(); uriBuilder.host("www.xyz.de"); uriBuilder.scheme("http"); uriBuilder.segment("path1", "path2"); uriBuilder.path("hh ho"); assertEqualsURI("http://www.xyz.de/path1/path2/hh%20ho", uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#fragment(String)}. */ public void testFragmentEnc() throws Exception { this.uriBuilder.fragment(String.valueOf((char) 9)); assertEqualsURI(URI_NO_EXT + "#%09", this.uriBuilder, true); this.uriBuilder.fragment("anker"); assertEqualsURI(URI_NO_EXT + "#anker", this.uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#host(String)}. */ public void testHostEnc() throws Exception { this.uriBuilder.host("test.domain.org"); assertEqualsURI("http://test.domain.org/path1/path2", this.uriBuilder, true); try { this.uriBuilder.host("test.domain .org a"); fail(); } catch (IllegalArgumentException iae) { // good } assertEqualsURI("http://test.domain.org/path1/path2", this.uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#replaceMatrixParams(String)} * and {@link ExtendedUriBuilder#matrixParam(String, String)}. */ public void testMatrixParam() throws Exception { this.uriBuilder.matrixParam("mp1", "mv1"); assertEqualsURI(URI_NO_EXT + ";mp1=mv1", this.uriBuilder, true); this.uriBuilder.matrixParam("mp1", "mv2"); assertEqualsURI(URI_NO_EXT + ";mp1=mv1;mp1=mv2", this.uriBuilder, true); this.uriBuilder.matrixParam("mp3", "mv3"); try { assertEqualsURI(URI_NO_EXT + ";mp1=mv1;mp1=mv2;mp3=mv3", this.uriBuilder, true); } catch (AssertionFailedError afe) { // try another possibility assertEqualsURI(URI_NO_EXT + ";mp3=mv3;mp1=mv1;mp1=mv2", this.uriBuilder, true); } this.uriBuilder.replaceMatrix("mp4=mv4"); assertEqualsURI(URI_NO_EXT + ";mp4=mv4", this.uriBuilder, true); this.uriBuilder.replaceMatrix(""); assertEquals(new URI(URI_NO_EXT + ";"), this.uriBuilder.build()); this.uriBuilder.replaceMatrix(null); assertEquals(URI_NO_EXT, this.uriBuilder.build()); this.uriBuilder.matrixParam("jkj$sdf", "ij a%20"); assertEqualsURI(URI_NO_EXT + ";jkj%24sdf=ij%20a%2520", this.uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#path(Class)}. */ public void testPathClass() throws Exception { this.uriBuilder.replacePath(null); this.uriBuilder.path(SimpleTrain.class); assertEqualsURI("http://localhost" + SimpleTrain.PATH, this.uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#path(Class, String)}. */ public void testPathClassString() throws Exception { this.uriBuilder.replacePath(null); this.uriBuilder.path(CarListResource.class, "getOffers"); assertEqualsURI("http://localhost/" + CarListResource.PATH + "/" + CarListResource.OFFERS_PATH, this.uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#path(Class, String)}. */ public void testPathClassStringEnc() throws Exception { this.uriBuilder.replacePath(null); this.uriBuilder.path(CarListResource.class, "getOffers"); assertEqualsURI("http://localhost/" + CarListResource.PATH + "/" + CarListResource.OFFERS_PATH, this.uriBuilder, true); } /** * Test method for * {@link ExtendedUriBuilder#path(java.lang.reflect.Method[])}. */ public void testPathMethodArray() throws Exception { this.uriBuilder.replacePath(null); final Method findCar = CarListResource.class.getMethod("findCar", Integer.TYPE); final Method engine = CarResource.class.getMethod("findEngine"); this.uriBuilder.path(CarListResource.class); this.uriBuilder.path(findCar).path(engine); assertEqualsURI("http://localhost/" + CarListResource.PATH + "/5/engine", this.uriBuilder.build("5")); } /** * Test method for {@link ExtendedUriBuilder#path(String[])}. */ public void testPathStringArrayEnc() throws Exception { this.uriBuilder.segment("jjj", "kkk", "ll"); assertEqualsURI(URI_NO_EXT + "/jjj/kkk/ll", this.uriBuilder, true); this.uriBuilder.path("mno"); assertEqualsURI(URI_NO_EXT + "/jjj/kkk/ll/mno", this.uriBuilder, true); this.uriBuilder.path(" "); assertEqualsURI(URI_NO_EXT + "/jjj/kkk/ll/mno/%20", this.uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#port(int)}. */ public void testPort() throws Exception { this.uriBuilder.port(4711); assertEqualsURI("http://localhost:4711/path1/path2", this.uriBuilder, true); this.uriBuilder.port(-1); assertEqualsURI("http://localhost/path1/path2", this.uriBuilder, true); } /** * Test method for {@link ExtendedUriBuilder#queryParam(String, String)}. */ public void testQueryEnc() throws Exception { this.uriBuilder.queryParam("qn", "qv"); assertEqualsURI(URI_NO_EXT + "?qn=qv", this.uriBuilder, true); this.uriBuilder.queryParam("qn", "qv2"); assertEqualsURI(URI_NO_EXT + "?qn=qv&qn=qv2", this.uriBuilder, true); this.uriBuilder.queryParam("qn3", "qv3"); assertEqualsURI(URI_NO_EXT + "?qn=qv&qn=qv2&qn3=qv3", this.uriBuilder, true); this.uriBuilder.replaceQuery("qnNew=qvNew"); assertEqualsURI(URI_NO_EXT + "?qnNew=qvNew", this.uriBuilder, true); this.uriBuilder.replaceQuery(null); this.uriBuilder.queryParam("na$me", "George U."); assertEqualsURI(URI_NO_EXT + "?na%24me=George%20U.", this.uriBuilder, true); } public void testreplaceMatrix() throws Exception { this.uriBuilder.matrixParam("a", "b"); this.uriBuilder.matrixParam("c", "d"); assertEqualsURI("http://localhost/path1/path2;a=b;c=d", this.uriBuilder); this.uriBuilder.replaceMatrix("ksd hflk"); assertEqualsURI("http://localhost/path1/path2;ksd%20hflk", this.uriBuilder); this.uriBuilder.replaceMatrix("e=f"); assertEqualsURI("http://localhost/path1/path2;e=f", this.uriBuilder); } /** * Test method for {@link ExtendedUriBuilder#replacePath(String)}. */ public void testReplacePath() throws Exception { this.uriBuilder.replacePath("newPath"); assertEqualsURI("http://localhost/newPath", this.uriBuilder); this.uriBuilder.replacePath(""); assertEqualUriBuilder("http", null, "localhost", null, "", null, null, this.uriBuilder, true); assertEqualsUriSlashAllowed("http://localhost", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r t"); assertEqualsURI("http://localhost/gh/r%20t", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t"); assertEqualsURI("http://localhost/gh/r;t", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t=6"); assertEqualsURI("http://localhost/gh/r;t=6", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t="); assertEqualsURI("http://localhost/gh/r;t=", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t=6;g"); assertEqualsURI("http://localhost/gh/r;t=6;g", this.uriBuilder); } public void testReplaceQueryParams() throws Exception { this.uriBuilder.queryParam("a", "b"); this.uriBuilder.queryParam("c", "d"); assertEqualsURI("http://localhost/path1/path2?a=b&c=d", this.uriBuilder); this.uriBuilder.replaceQuery("ksd hflk"); assertEqualsURI("http://localhost/path1/path2?ksd+hflk", this.uriBuilder); this.uriBuilder.replaceQuery("e=f"); assertEqualsURI("http://localhost/path1/path2?e=f", this.uriBuilder); } /** * Test method for {@link ExtendedUriBuilder#scheme(String)}. */ public void testScheme() throws Exception { this.uriBuilder.scheme("ftp"); assertEqualsURI("ftp://localhost/path1/path2", this.uriBuilder); this.uriBuilder.scheme("f4.-+tp"); assertEqualsURI("f4.-+tp://localhost/path1/path2", this.uriBuilder); try { this.uriBuilder.scheme("44"); fail(); } catch (IllegalArgumentException iae) { // good } assertEqualsURI("f4.-+tp://localhost/path1/path2", this.uriBuilder); try { this.uriBuilder.scheme("f\0"); fail(); } catch (IllegalArgumentException iae) { // good } assertEqualsURI("f4.-+tp://localhost/path1/path2", this.uriBuilder); } /** * Test method for {@link ExtendedUriBuilder#schemeSpecificPart(String)}. */ public void testSchemeSpecificPart() throws Exception { this.uriBuilder.schemeSpecificPart("//shkf"); this.uriBuilder.replacePath(""); assertEqualUriBuilder("http", null, "shkf", null, "", null, null, this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//shkf-host/akfshdf"); assertEqualUriBuilder("http", null, "shkf-host", null, "/akfshdf", null, null, this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//user@shkf/akfshdf/akjhf"); assertEqualUriBuilder("http", "user", "shkf", null, "/akfshdf/akjhf", null, null, this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//shkf:4711/akjhf?a=b"); assertEqualUriBuilder("http", null, "shkf", "4711", "/akjhf", null, "a=b", this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//www.domain.org/akjhf;1=2?a=b"); assertEqualUriBuilder("http", null, "www.domain.org", null, "/akjhf;1=2", null, "a=b", this.uriBuilder, true); this.uriBuilder .schemeSpecificPart("//www.domain.org/akjhf;1=2;3=4?a=b"); assertEqualUriBuilder("http", null, "www.domain.org", null, "/akjhf;1=2;3=4", null, "a=b", this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//www.domain.org/ "); assertEquals("http://www.domain.org/%20", this.uriBuilder.build() .toString()); } public void testStaticFromPath() throws Exception { ExtendedUriBuilder uriBuilder = ExtendedUriBuilder.fromPath("path"); assertEqualUriBuilder(null, null, null, null, "path", null, null, uriBuilder, true); assertEqualsURI("path", uriBuilder); uriBuilder = ExtendedUriBuilder.fromPath("path1/path2/abc.html"); assertEqualUriBuilder(null, null, null, null, "path1/path2/abc", ".html", null, uriBuilder, true); assertEqualsURI("path1/path2/abc.html", uriBuilder); uriBuilder = ExtendedUriBuilder .fromPath("path1/path2;mp1=mv 1;mp2=mv2/abc.html"); assertEqualUriBuilder(null, null, null, null, "path1/path2;mp1=mv%201;mp2=mv2/abc", ".html", null, uriBuilder, false); assertEquals("path1/path2;mp1=mv%201;mp2=mv2/abc.html", uriBuilder .build().toString()); final String path = "path1/path2;mp1=mv1" + Reference.encode("?") + ";mp2=mv2/abc.html"; uriBuilder = ExtendedUriBuilder.fromPath(path); assertEqualUriBuilder(null, null, null, null, "path1/path2;mp1=mv1%3F;mp2=mv2/abc", ".html", null, uriBuilder, false); } public void testTemplateParams() throws Exception { changeWithTemplVars(this.uriBuilderWithVars); URI uri = buildFromTemplVarsWithMap(this.uriBuilderWithVars); assertEqualsURI(TEMPL_VARS_EXPECTED, uri); uri = buildFromTemplVarsWithStrings(this.uriBuilderWithVars); assertEqualsURI(TEMPL_VARS_EXPECTED, uri); } // TEST if ExtendedUriBuilder.build works, if there are matrix parameters or // not and if there are only matrix parameters, but no extension and no path /** * Test method for {@link ExtendedUriBuilder#toString()}. */ public void testToString() { assertEquals("http://localhost/path1/path2", this.uriBuilder.toString()); } /** * Test method for {@link ExtendedUriBuilder#uri(java.net.URI)}. */ public void testUri() throws Exception { URI u = new URI("ftp", "test.org", null, null, "fragment"); this.uriBuilder.uri(u); assertEqualsURI("ftp://test.org/#fragment", this.uriBuilder); u = new URI("ftp", "test.org", "/path", "qu=ery", "fragment"); this.uriBuilder.uri(u); assertEqualsURI("ftp://test.org/path?qu=ery#fragment", this.uriBuilder); final String id = "4711"; final URI collectionUri = new URI( "http://localhost:8181/SecurityContextTestService"); final URI location = ExtendedUriBuilder.fromUri(collectionUri).path( "{id}").build(id); assertEqualsURI(collectionUri + "/4711", location); } /** * Test method for {@link ExtendedUriBuilder#userInfo(String)}. */ public void testUserInfo() throws Exception { this.uriBuilder.userInfo("username"); assertEqualsURI("http://username@localhost/path1/path2", this.uriBuilder); this.uriBuilder.replacePath((String) null); this.uriBuilder.host("abc"); this.uriBuilder.userInfo("username:pw"); assertEqualsUriSlashAllowed("http://username:pw@abc", this.uriBuilder); this.uriBuilder.userInfo("rkj;s78:&=+$,"); assertEqualsUriSlashAllowed("http://rkj;s78:&=+$,@abc", this.uriBuilder); this.uriBuilder.userInfo(" "); assertEqualsUriSlashAllowed("http://%20@abc", this.uriBuilder); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/core/PathSegmentImplTest.java0000664000175000017500000000666111757206352032045 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.core; import java.util.List; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import junit.framework.TestCase; import org.restlet.ext.jaxrs.internal.core.PathSegmentImpl; /** * @author Stephan Koops * @see PathSegmentImpl * @see PathSegment */ @SuppressWarnings("all") public class PathSegmentImplTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testParseMatrixParams() { final MultivaluedMap matrixParams = PathSegmentImpl .parseMatrixParams("mpn1=mpv1;mpn1=mpv2;mpn3=mpv3", true); final List mpn1 = matrixParams.get("mpn1"); assertEquals(2, mpn1.size()); assertEquals("mpv1", mpn1.get(0)); assertEquals("mpv2", mpn1.get(1)); final List mpn3 = matrixParams.get("mpn3"); assertEquals(1, mpn3.size()); assertEquals("mpv3", mpn3.get(0)); } public void testParseMatrixParamsFalseFalse() { final MultivaluedMap matrixParams = PathSegmentImpl .parseMatrixParams("mpn1=mpv1%20;mpn1=mp%20v2;mp%20n3=%20mpv3", false); final List mpn1 = matrixParams.get("mpn1"); assertEquals(2, mpn1.size()); assertEquals("mpv1%20", mpn1.get(0)); assertEquals("mp%20v2", mpn1.get(1)); final List mpn3 = matrixParams.get("mp%20n3"); assertEquals(1, mpn3.size()); assertEquals("%20mpv3", mpn3.get(0)); } public void testParseMatrixParamsTrueFalse() { final MultivaluedMap matrixParams = PathSegmentImpl .parseMatrixParams("mpn1=mpv1%20;mpn1=mp%20v2;mp%20n3=%20mpv3", true); final List mpn1 = matrixParams.get("mpn1"); assertEquals(2, mpn1.size()); assertEquals("mpv1 ", mpn1.get(0)); assertEquals("mp v2", mpn1.get(1)); final List mpn3 = matrixParams.get("mp n3"); assertEquals(1, mpn3.size()); assertEquals(" mpv3", mpn3.get(0)); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/core/package-info.java0000664000175000017500000000301111757206352030452 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ /** *

* Implementations of package javax.ws.rs.core. *

*

* This extension as well as the JAX-RS specification are currently under * development. You should only use this extension for experimental purpose. *

* * @author Stephan Koops */ package org.restlet.test.jaxrs.core; restlet-2.0.14/org.restlet.test/src/org/restlet/test/jaxrs/core/UriBuilderImplTest.java0000664000175000017500000007552611757206354031704 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.jaxrs.core; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.ext.RuntimeDelegate; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.restlet.data.Reference; import org.restlet.ext.jaxrs.ExtendedUriBuilder; import org.restlet.ext.jaxrs.internal.core.UriBuilderImpl; import org.restlet.test.jaxrs.services.car.CarListResource; import org.restlet.test.jaxrs.services.car.CarResource; import org.restlet.test.jaxrs.services.resources.SimpleTrain; /** * @author Stephan Koops * @see UriBuilder * @see UriBuilderImpl * @see ExtendedUriBuilder */ @SuppressWarnings("all") public class UriBuilderImplTest extends TestCase { private static final String TEMPL_VARS_EXPECTED = "abc://username:password@www.secure.org:8080/def/ghi;jkl=mno/pqr;stu=vwx?ABC=DEF&GHI=JKL#MNO"; private static final URI URI_1; static { try { URI_1 = new URI("http://localhost/path1/path2"); } catch (URISyntaxException e) { throw new RuntimeException("Can not initialize JaxRsUriBuilderTest"); } } /** * @param expectedUri * @param actualUri * @throws URISyntaxException */ static void assertEqualsURI(String expectedUri, URI actualUri) throws URISyntaxException { assertEquals(expectedUri, actualUri.toString()); assertEquals(new URI(expectedUri), actualUri); } static void assertEqualsURI(String expectedUri, UriBuilder actualBuilder) throws Exception { assertEqualsURI(expectedUri, actualBuilder, true); } static void assertEqualsURI(String expectedUri, UriBuilder actualBuilder, boolean encode) throws Exception { URI actual; if (encode) actual = actualBuilder.buildFromEncoded(); else actual = actualBuilder.build(); assertEqualsURI(expectedUri, actual); } static void assertEqualsUriSlashAllowed(String expectedUri, UriBuilder actual) throws URISyntaxException { try { assertEqualsURI(expectedUri, actual.build()); } catch (AssertionFailedError ife) { assertEqualsURI(expectedUri + "/", actual.build()); } } /** * Note, that the actual value is at the beginning, because of the * expectedPathSegents must be the last parameter. * * @param expectedScheme * @param expectedUserInfo * @param expectedHost * @param expectedPort * @param expectedQuery * @param actualUriBuilder * @param compareResult * if true, also the builded URIs are compared (this causes * trouble sometimes, e.g. with "/"). * @param expectedPathSegments */ private static void assertEqualUriBuilder(String expectedScheme, String expectedUserInfo, String expectedHost, String expectedPort, String expectedPath, String expectedQuery, UriBuilder actualUriBuilder, boolean compareResult) throws Exception { if (actualUriBuilder.getClass().getPackage().getName().startsWith( "org.restlet.ext.jaxrs")) { assertEquals(expectedScheme, getScheme(actualUriBuilder)); assertEquals(expectedUserInfo, getUserInfo(actualUriBuilder)); assertEquals(expectedHost, getHost(actualUriBuilder)); assertEquals(expectedPort, getPort(actualUriBuilder)); final String actPath = getPath(actualUriBuilder); try { assertEquals(expectedPath, actPath); } catch (junit.framework.ComparisonFailure cf) { if (expectedPath == null) assertEquals("", actPath); } CharSequence actualQuery = getQuery(actualUriBuilder); if (actualQuery != null) { actualQuery = actualQuery.toString(); } assertEquals(expectedQuery, actualQuery); } if (compareResult) { UriBuilder expectedUriBuilder = RuntimeDelegate.getInstance() .createUriBuilder(); if (expectedScheme != null) { expectedUriBuilder.scheme(expectedScheme); } if (expectedUserInfo != null) { expectedUriBuilder.userInfo(expectedUserInfo); } if (expectedHost != null) { expectedUriBuilder.host(expectedHost); } if (expectedUriBuilder instanceof UriBuilderImpl) { ((UriBuilderImpl) expectedUriBuilder).port(expectedPort); } else if (expectedUriBuilder instanceof ExtendedUriBuilder) { ((ExtendedUriBuilder) expectedUriBuilder).port(expectedPort); } else { if (expectedPort == null || expectedPort.equals("")) { expectedUriBuilder.port(-1); } else { try { int portInt = Integer.valueOf(expectedPort); } catch (NumberFormatException e) { System.out .println("Sorry, could not do this test with an expected port \"" + expectedPort + "\" and an UriBuilder of type " + expectedUriBuilder.getClass()); } } } expectedUriBuilder.path(expectedPath); if (expectedQuery != null) { expectedUriBuilder.replaceQuery(expectedQuery); } String expectedURI = expectedUriBuilder.build().toString(); String atualURI = actualUriBuilder.build().toString(); assertEquals(expectedURI, atualURI); } } /** * @param uriBuilder * @param fieldName * @return * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException */ static String getFieldValue(UriBuilder uriBuilder, String fieldName) throws Exception { Field queryField; try { queryField = uriBuilder.getClass().getDeclaredField(fieldName); } catch (NoSuchFieldException e) { queryField = uriBuilder.getClass().getSuperclass() .getDeclaredField(fieldName); } queryField.setAccessible(true); final Object value = queryField.get(uriBuilder); if (value == null) { return null; } return value.toString(); } /** * @param uriBuilderImpl * @return */ private static String getHost(UriBuilder uriBuilder) throws Exception { return getFieldValue(uriBuilder, "host"); } /** * @param uriBuilderImpl * @return */ @SuppressWarnings("unchecked") private static String getPath(UriBuilder uriBuilder) throws Exception { final Object path = getFieldValue(uriBuilder, "path"); if (path == null) { return null; } return path.toString(); } /** * @param uriBuilderImpl * @return */ private static String getPort(UriBuilder uriBuilder) throws Exception { return getFieldValue(uriBuilder, "port"); } /** * @param uriBuilderImpl * @return */ private static String getQuery(UriBuilder uriBuilder) throws Exception { return getFieldValue(uriBuilder, "query"); } /** * @param uriBuilderImpl * @return */ private static String getScheme(UriBuilder uriBuilder) throws Exception { return getFieldValue(uriBuilder, "scheme"); } /** * @param uriBuilderImpl * @return */ private static String getUserInfo(UriBuilder uriBuilder) throws Exception { return getFieldValue(uriBuilder, "userInfo"); } public static void main(String[] args) { System.out.println(Reference.encode("%")); } private UriBuilder uriBuilder; /** * UriBuilder with variableNames. */ private UriBuilder uriBuilderWithVars; private URI buildFromTemplVarsWithMap(UriBuilder uriBuilder) { final Map vars = new HashMap(); vars.put("scheme", "abc"); vars.put("userInfo", "username:password"); vars.put("host", "www.secure.org"); vars.put("port", "8080"); vars.put("path1", "def"); vars.put("path2", "ghi"); vars.put("mp2Name", "jkl"); vars.put("mp2Value", "mno"); vars.put("path3", "pqr"); vars.put("mp3Name", "stu"); vars.put("mp3Value", "vwx"); vars.put("qp1Name", "ABC"); vars.put("qp1Value", "DEF"); vars.put("qp2Name", "GHI"); vars.put("qp2Value", "JKL"); vars.put("fragment", "MNO"); return uriBuilder.buildFromMap(vars); } private URI buildFromTemplVarsWithStrings(UriBuilder uriBuilder) { return uriBuilder.build("abc", "username:password", "www.secure.org", "8080", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "ABC", "DEF", "GHI", "JKL", "MNO"); } /** * @throws IllegalArgumentException */ private void changeWithTemplVars(UriBuilderImpl uriBuilder) { uriBuilder.scheme("{scheme}"); uriBuilder.userInfo("{userInfo}"); uriBuilder.host("{host}"); uriBuilder.port("{port}"); uriBuilder.replacePath("{path1}"); uriBuilder.path("{path2}"); uriBuilder.replaceMatrix("{mp2Name}={mp2Value}"); uriBuilder.path("{path3}"); uriBuilder.matrixParam("{mp3Name}", "{mp3Value}"); uriBuilder.replaceQuery("{qp1Name}={qp1Value}"); uriBuilder.queryParam("{qp2Name}", "{qp2Value}"); uriBuilder.fragment("{fragment}"); } @Override protected void setUp() throws Exception { super.setUp(); this.uriBuilder = RuntimeDelegate.getInstance().createUriBuilder(); this.uriBuilder.host("localhost"); this.uriBuilder.segment("path1", "path2"); this.uriBuilder.scheme("http"); this.uriBuilderWithVars = RuntimeDelegate.getInstance() .createUriBuilder(); this.uriBuilderWithVars.host("localhost"); this.uriBuilderWithVars.scheme("http"); this.uriBuilderWithVars.segment("abc", "{var1}", "def", "{var2}"); } @Override protected void tearDown() throws Exception { this.uriBuilder = null; this.uriBuilderWithVars = null; super.tearDown(); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#build(java.lang.String[])} * . */ public void testBuildFromArray() throws Exception { try { this.uriBuilderWithVars.build("123"); fail("must fail, because there are not enough arguments"); } catch (IllegalArgumentException e) { // wonderful } URI uri = this.uriBuilderWithVars.build("123", "456"); assertEqualsURI("http://localhost/abc/123/def/456", uri); final UriBuilder uriBuilder2 = this.uriBuilderWithVars.clone(); assertEqualsURI("http://localhost/abc/123/def/456", uriBuilder2.build( "123", "456")); assertEquals(this.uriBuilderWithVars.toString(), uriBuilder2.toString()); uriBuilder2.path("{var3}"); uri = this.uriBuilderWithVars.build("123", "456"); assertEqualsURI("http://localhost/abc/123/def/456", uri); try { uriBuilder2.build("123", "456"); fail("must fail, because there are not enough arguments"); } catch (IllegalArgumentException e) { // wonderful } final URI uri2 = uriBuilder2.build("123", "456", "789"); assertEqualsURI("http://localhost/abc/123/def/456/789", uri2); } public void testBuildFromEncoded() throws Exception { assertEquals(URI_1, this.uriBuilder.buildFromEncoded("a", "b")); assertEquals(URI_1, this.uriBuilder.buildFromEncoded(" ", "b")); URI uri = this.uriBuilderWithVars.buildFromEncoded("a", "b"); assertEqualsURI("http://localhost/abc/a/def/b", uri); uri = this.uriBuilderWithVars.buildFromEncoded("%20", "b"); assertEqualsURI("http://localhost/abc/%20/def/b", uri); try { uri = this.uriBuilderWithVars.buildFromEncoded(" ", "b"); fail("must fail"); } catch (IllegalArgumentException e) { // wonderful } } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#build(java.util.Map)} . */ public void testBuildFromMap() throws Exception { final Map vars = new HashMap(); try { this.uriBuilderWithVars.buildFromMap(vars); fail("must fail, because missing UriTemplate variables"); } catch (IllegalArgumentException e) { // wonderful } vars.put("var1", "123"); try { this.uriBuilderWithVars.buildFromMap(vars); fail("must fail, because missing UriTemplate variable"); } catch (IllegalArgumentException e) { // wonderful } vars.put("var2", "456"); assertEqualsURI("http://localhost/abc/123/def/456", this.uriBuilderWithVars.buildFromMap(vars)); vars.put("var3", "789"); assertEqualsURI("http://localhost/abc/123/def/456", this.uriBuilderWithVars.buildFromMap(vars)); vars.put("var2", " "); assertEqualsURI("http://localhost/abc/123/def/%20", this.uriBuilderWithVars.buildFromMap(vars)); } public void testBuildWithArgs() throws Exception { assertEquals(URI_1, this.uriBuilder.build("a", "b")); assertEquals(URI_1, this.uriBuilder.build(" ", "b")); URI uri = this.uriBuilderWithVars.build("a", "b"); assertEqualsURI("http://localhost/abc/a/def/b", uri); uri = this.uriBuilderWithVars.build("%20", "b"); assertEqualsURI("http://localhost/abc/%2520/def/b", uri); uri = this.uriBuilderWithVars.build(" ", "b"); assertEqualsURI("http://localhost/abc/%20/def/b", uri); } /** * Test method for {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#build()} * . */ public void testBuildWithoutArgs() throws Exception { assertEquals(URI_1, this.uriBuilder.build()); try { this.uriBuilderWithVars.build(); fail("must fail, because vars are required"); } catch (IllegalArgumentException ube) { // wonderful } } /** * Test method for {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#clone()} * . */ public void testClone() { assertEquals(this.uriBuilder.build(), this.uriBuilder.clone().build()); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#encode(boolean)} . */ public void testEncode() throws Exception { final UriBuilder uriBuilder = RuntimeDelegate.getInstance() .createUriBuilder(); uriBuilder.host("www.xyz.de"); uriBuilder.scheme("http"); uriBuilder.segment("path1", "path2"); uriBuilder.path("hh ho"); assertEqualsURI("http://www.xyz.de/path1/path2/hh%20ho", uriBuilder, true); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#fragment(java.lang.String)} * . */ public void testFragmentEnc() throws Exception { this.uriBuilder.fragment(String.valueOf((char) 9)); assertEqualsURI(URI_1 + "#%09", this.uriBuilder, true); this.uriBuilder.fragment("anker"); assertEqualsURI(URI_1 + "#anker", this.uriBuilder, true); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#host(java.lang.String)} * . */ public void testHostEnc() throws Exception { this.uriBuilder.host("test.domain.org"); assertEqualsURI("http://test.domain.org/path1/path2", this.uriBuilder, true); try { this.uriBuilder.host("test.domain .org a"); fail(); } catch (IllegalArgumentException iae) { // good } assertEqualsURI("http://test.domain.org/path1/path2", this.uriBuilder, true); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#replaceMatrixParams(java.lang.String)} * . and * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#matrixParam(java.lang.String, java.lang.String)} * . */ public void testMatrixParam() throws Exception { this.uriBuilder.matrixParam("mp1", "mv1"); assertEqualsURI(URI_1 + ";mp1=mv1", this.uriBuilder, true); this.uriBuilder.matrixParam("mp1", "mv2"); assertEqualsURI(URI_1 + ";mp1=mv1;mp1=mv2", this.uriBuilder, true); this.uriBuilder.matrixParam("mp3", "mv3"); try { assertEqualsURI(URI_1 + ";mp1=mv1;mp1=mv2;mp3=mv3", this.uriBuilder, true); } catch (AssertionFailedError afe) { // try another possibility assertEqualsURI(URI_1 + ";mp3=mv3;mp1=mv1;mp1=mv2", this.uriBuilder, true); } this.uriBuilder.replaceMatrix("mp4=mv4"); assertEqualsURI(URI_1 + ";mp4=mv4", this.uriBuilder, true); this.uriBuilder.replaceMatrix(""); assertEquals(new URI(URI_1 + ";"), this.uriBuilder.build()); this.uriBuilder.replaceMatrix(null); assertEquals(URI_1, this.uriBuilder.build()); this.uriBuilder.matrixParam("jkj$sdf", "ij a%20"); assertEqualsURI(URI_1 + ";jkj%24sdf=ij%20a%2520", this.uriBuilder, true); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#path(java.lang.Class)} . */ public void testPathClass() throws Exception { this.uriBuilder.replacePath(null); this.uriBuilder.path(SimpleTrain.class); assertEqualsURI("http://localhost" + SimpleTrain.PATH, this.uriBuilder, true); } /** * Test method for {@link AbstractUriBuilder#path(Class, String). */ public void testPathClassString() throws Exception { this.uriBuilder.replacePath(null); this.uriBuilder.path(CarListResource.class, "getOffers"); assertEqualsURI("http://localhost/" + CarListResource.OFFERS_PATH, this.uriBuilder, true); } /** * Test method for {@link AbstractUriBuilder#path(Class, String). */ public void testPathClassStringEnc() throws Exception { this.uriBuilder.replacePath(null); this.uriBuilder.path(CarListResource.class, "getOffers"); assertEqualsURI("http://localhost/" + CarListResource.OFFERS_PATH, this.uriBuilder, true); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#path(java.lang.reflect.Method[])} * . */ public void testPathMethodArray() throws Exception { this.uriBuilder.replacePath(null); final Method findCar = CarListResource.class.getMethod("findCar", Integer.TYPE); final Method engine = CarResource.class.getMethod("findEngine"); this.uriBuilder.path(CarListResource.class); this.uriBuilder.path(findCar).path(engine); assertEqualsURI("http://localhost/" + CarListResource.PATH + "/5/engine", this.uriBuilder.build("5")); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#path(java.lang.String[])} * . */ public void testPathStringArrayEnc() throws Exception { this.uriBuilder.segment("jjj", "kkk", "ll"); assertEqualsURI(URI_1 + "/jjj/kkk/ll", this.uriBuilder, true); this.uriBuilder.path("mno"); assertEqualsURI(URI_1 + "/jjj/kkk/ll/mno", this.uriBuilder, true); this.uriBuilder.path(" "); assertEqualsURI(URI_1 + "/jjj/kkk/ll/mno/%20", this.uriBuilder, true); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#port(int)}. */ public void testPort() throws Exception { this.uriBuilder.port(4711); assertEqualsURI("http://localhost:4711/path1/path2", this.uriBuilder, true); this.uriBuilder.port(-1); assertEqualsURI("http://localhost/path1/path2", this.uriBuilder, true); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#queryParam(java.lang.String, java.lang.String)} * . */ public void testQueryEnc() throws Exception { this.uriBuilder.queryParam("qn", "qv"); assertEqualsURI(URI_1 + "?qn=qv", this.uriBuilder, true); this.uriBuilder.queryParam("qn", "qv2"); assertEqualsURI(URI_1 + "?qn=qv&qn=qv2", this.uriBuilder, true); this.uriBuilder.queryParam("qn3", "qv3"); assertEqualsURI(URI_1 + "?qn=qv&qn=qv2&qn3=qv3", this.uriBuilder, true); this.uriBuilder.replaceQuery("qnNew=qvNew"); assertEqualsURI(URI_1 + "?qnNew=qvNew", this.uriBuilder, true); this.uriBuilder.replaceQuery(null); this.uriBuilder.queryParam("na$me", "George U."); assertEqualsURI(URI_1 + "?na%24me=George%20U.", this.uriBuilder, true); } public void testreplaceMatrix() throws Exception { this.uriBuilder.matrixParam("a", "b"); this.uriBuilder.matrixParam("c", "d"); assertEqualsURI("http://localhost/path1/path2;a=b;c=d", this.uriBuilder); this.uriBuilder.replaceMatrix("ksd hflk"); assertEqualsURI("http://localhost/path1/path2;ksd%20hflk", this.uriBuilder); this.uriBuilder.replaceMatrix("e=f"); assertEqualsURI("http://localhost/path1/path2;e=f", this.uriBuilder); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#replacePath(java.lang.String)} * . */ public void testReplacePath() throws Exception { this.uriBuilder.replacePath("newPath"); assertEqualsURI("http://localhost/newPath", this.uriBuilder); this.uriBuilder.replacePath(""); assertEqualUriBuilder("http", null, "localhost", null, "", null, this.uriBuilder, true); assertEqualsUriSlashAllowed("http://localhost", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r t"); assertEqualsURI("http://localhost/gh/r%20t", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t"); assertEqualsURI("http://localhost/gh/r;t", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t=6"); assertEqualsURI("http://localhost/gh/r;t=6", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t="); assertEqualsURI("http://localhost/gh/r;t=", this.uriBuilder); this.uriBuilder.replacePath("gh").path("r;t=6;g"); assertEqualsURI("http://localhost/gh/r;t=6;g", this.uriBuilder); } public void testReplaceQueryParams() throws Exception { this.uriBuilder.queryParam("a", "b"); this.uriBuilder.queryParam("c", "d"); assertEqualsURI("http://localhost/path1/path2?a=b&c=d", this.uriBuilder); this.uriBuilder.replaceQuery("ksd hflk"); assertEqualsURI("http://localhost/path1/path2?ksd+hflk", this.uriBuilder); this.uriBuilder.replaceQuery("e=f"); assertEqualsURI("http://localhost/path1/path2?e=f", this.uriBuilder); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#scheme(java.lang.String)} * . */ public void testScheme() throws Exception { this.uriBuilder.scheme("ftp"); assertEqualsURI("ftp://localhost/path1/path2", this.uriBuilder); this.uriBuilder.scheme("f4.-+tp"); assertEqualsURI("f4.-+tp://localhost/path1/path2", this.uriBuilder); try { this.uriBuilder.scheme("44"); fail(); } catch (IllegalArgumentException iae) { // good } assertEqualsURI("f4.-+tp://localhost/path1/path2", this.uriBuilder); try { this.uriBuilder.scheme("f\0"); fail(); } catch (IllegalArgumentException iae) { // good } assertEqualsURI("f4.-+tp://localhost/path1/path2", this.uriBuilder); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#schemeSpecificPart(java.lang.String)} * . */ public void testSchemeSpecificPart() throws Exception { this.uriBuilder.schemeSpecificPart("//shkf"); this.uriBuilder.replacePath(""); assertEqualUriBuilder("http", null, "shkf", null, "", null, this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//shkf-host/akfshdf"); assertEqualUriBuilder("http", null, "shkf-host", null, "/akfshdf", null, this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//user@shkf/akfshdf/akjhf"); assertEqualUriBuilder("http", "user", "shkf", null, "/akfshdf/akjhf", null, this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//shkf:4711/akjhf?a=b"); assertEqualUriBuilder("http", null, "shkf", "4711", "/akjhf", "a=b", this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//www.domain.org/akjhf;1=2?a=b"); assertEqualUriBuilder("http", null, "www.domain.org", null, "/akjhf;1=2", "a=b", this.uriBuilder, true); this.uriBuilder .schemeSpecificPart("//www.domain.org/akjhf;1=2;3=4?a=b"); assertEqualUriBuilder("http", null, "www.domain.org", null, "/akjhf;1=2;3=4", "a=b", this.uriBuilder, true); this.uriBuilder.schemeSpecificPart("//www.domain.org/ "); assertEquals("http://www.domain.org/%20", this.uriBuilder.build() .toString()); } /** * * @throws Exception */ public void testStaticFromPath() throws Exception { UriBuilder uriBuilder = UriBuilder.fromPath("path"); if (uriBuilder instanceof UriBuilderImpl) { assertEqualUriBuilder(null, null, null, null, "path", null, uriBuilder, true); } assertEqualsURI("path", uriBuilder); uriBuilder = UriBuilder.fromPath("path1/path2/abc.html"); if (uriBuilder instanceof UriBuilderImpl) { assertEqualUriBuilder(null, null, null, null, "path1/path2/abc.html", null, uriBuilder, true); } assertEqualsURI("path1/path2/abc.html", uriBuilder); uriBuilder = UriBuilder .fromPath("path1/path2;mp1=mv 1;mp2=mv2/abc.html"); if (uriBuilder instanceof UriBuilderImpl) { assertEqualUriBuilder(null, null, null, null, "path1/path2;mp1=mv%201;mp2=mv2/abc.html", null, uriBuilder, false); } assertEquals("path1/path2;mp1=mv%201;mp2=mv2/abc.html", uriBuilder .build().toString()); final String path = "path1/path2;mp1=mv1" + Reference.encode("?") + ";mp2=mv2/abc.html"; uriBuilder = UriBuilder.fromPath(path); if (uriBuilder instanceof UriBuilderImpl) { assertEqualUriBuilder(null, null, null, null, "path1/path2;mp1=mv1%3F;mp2=mv2/abc.html", null, uriBuilder, false); } } public void testTemplateParams() throws Exception { changeWithTemplVars((UriBuilderImpl) this.uriBuilderWithVars); URI uri = buildFromTemplVarsWithMap(this.uriBuilderWithVars); assertEqualsURI(TEMPL_VARS_EXPECTED, uri); uri = buildFromTemplVarsWithStrings(this.uriBuilderWithVars); assertEqualsURI(TEMPL_VARS_EXPECTED, uri); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#toString()}. */ public void testToString() { assertEquals("http://localhost/path1/path2", this.uriBuilder.toString()); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#uri(java.net.URI)} . */ public void testUri() throws Exception { URI u = new URI("ftp", "test.org", null, null, "fragment"); this.uriBuilder.uri(u); assertEqualsURI("ftp://test.org/#fragment", this.uriBuilder); u = new URI("ftp", "test.org", "/path", "qu=ery", "fragment"); this.uriBuilder.uri(u); assertEqualsURI("ftp://test.org/path?qu=ery#fragment", this.uriBuilder); final String id = "4711"; final URI collectionUri = new URI( "http://localhost:8181/SecurityContextTestService"); final URI location = UriBuilder.fromUri(collectionUri).path("{id}") .build(id); assertEqualsURI(collectionUri + "/4711", location); } /** * Test method for * {@link org.restlet.ext.jaxrs.impl.UriBuilderImpl#userInfo(java.lang.String)} * . */ public void testUserInfo() throws Exception { this.uriBuilder.userInfo("username"); assertEqualsURI("http://username@localhost/path1/path2", this.uriBuilder); this.uriBuilder.replacePath((String) null); this.uriBuilder.host("abc"); this.uriBuilder.userInfo("username:pw"); assertEqualsUriSlashAllowed("http://username:pw@abc", this.uriBuilder); this.uriBuilder.userInfo("rkj;s78:&=+$,"); assertEqualsUriSlashAllowed("http://rkj;s78:&=+$,@abc", this.uriBuilder); this.uriBuilder.userInfo(" "); assertEqualsUriSlashAllowed("http://%20@abc", this.uriBuilder); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/RestletTestSuite.java0000664000175000017500000001446711757206352027364 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import junit.framework.Test; import junit.framework.TestSuite; import org.restlet.test.component.ComponentXmlConfigTestCase; import org.restlet.test.component.ComponentXmlTestCase; import org.restlet.test.connector.FileClientTestCase; import org.restlet.test.connector.RestartTestCase; import org.restlet.test.connector.RiapTestCase; import org.restlet.test.data.AuthenticationInfoTestCase; import org.restlet.test.data.ConnegTestCase; import org.restlet.test.data.CookieTestCase; import org.restlet.test.data.FileReferenceTestCase; import org.restlet.test.data.LanguageTestCase; import org.restlet.test.data.MediaTypeTestCase; import org.restlet.test.data.ProductTokenTestCase; import org.restlet.test.data.RangeTestCase; import org.restlet.test.data.RecipientInfoTestCase; import org.restlet.test.data.ReferenceTestCase; import org.restlet.test.data.StatusTestCase; import org.restlet.test.engine.EngineTestSuite; import org.restlet.test.ext.atom.AtomTestCase; import org.restlet.test.ext.freemarker.FreeMarkerTestCase; import org.restlet.test.ext.gwt.GwtConverterTest; import org.restlet.test.ext.jaxb.JaxbBasicConverterTest; import org.restlet.test.ext.jaxb.JaxbIntegrationConverterTestCase; import org.restlet.test.ext.odata.ODataTestSuite; import org.restlet.test.ext.spring.AllSpringTests; import org.restlet.test.ext.velocity.VelocityTestCase; import org.restlet.test.ext.wadl.WadlTestCase; import org.restlet.test.ext.xml.ResolvingTransformerTestCase; import org.restlet.test.ext.xml.RestletXmlTestCase; import org.restlet.test.ext.xml.TransformerTestCase; import org.restlet.test.jaxrs.AllJaxRsTests; import org.restlet.test.representation.AppendableRepresentationTestCase; import org.restlet.test.representation.DigesterRepresentationTestCase; import org.restlet.test.representation.RangeRepresentationTestCase; import org.restlet.test.resource.ResourceTestSuite; import org.restlet.test.routing.FilterTestCase; import org.restlet.test.routing.RedirectTestCase; import org.restlet.test.routing.RouteListTestCase; import org.restlet.test.routing.ValidatorTestCase; import org.restlet.test.security.DigestVerifierTestCase; import org.restlet.test.security.HttpBasicTestCase; import org.restlet.test.security.HttpDigestTestCase; import org.restlet.test.security.RoleTestCase; import org.restlet.test.security.SecurityTestCase; import org.restlet.test.util.TemplateTestCase; /** * Suite of unit tests for the Restlet RI. * * @author Jerome Louvel */ public class RestletTestSuite extends TestSuite { /** * JUnit constructor. * * @return The unit test. */ public static Test suite() { return new RestletTestSuite(); } /** Constructor. */ public RestletTestSuite() { addTest(ResourceTestSuite.suite()); addTestSuite(AppendableRepresentationTestCase.class); addTestSuite(AtomTestCase.class); addTestSuite(AuthenticationInfoTestCase.class); addTestSuite(CallTestCase.class); addTestSuite(ComponentXmlConfigTestCase.class); addTestSuite(CookieTestCase.class); addTestSuite(ConnegTestCase.class); addTestSuite(FileClientTestCase.class); addTestSuite(FileReferenceTestCase.class); addTestSuite(FilterTestCase.class); addTestSuite(FreeMarkerTestCase.class); addTestSuite(GwtConverterTest.class); addTestSuite(JaxbBasicConverterTest.class); addTestSuite(JaxbIntegrationConverterTestCase.class); addTestSuite(LanguageTestCase.class); addTestSuite(MediaTypeTestCase.class); addTestSuite(ProductTokenTestCase.class); addTestSuite(ReferenceTestCase.class); addTestSuite(ResolvingTransformerTestCase.class); addTestSuite(RestartTestCase.class); addTestSuite(RestletXmlTestCase.class); addTestSuite(RiapTestCase.class); addTestSuite(RouteListTestCase.class); addTestSuite(DigestVerifierTestCase.class); addTestSuite(RecipientInfoTestCase.class); addTestSuite(RoleTestCase.class); addTestSuite(StatusTestCase.class); addTestSuite(TemplateTestCase.class); addTestSuite(TransformerTestCase.class); addTestSuite(ValidatorTestCase.class); addTestSuite(VelocityTestCase.class); addTestSuite(WadlTestCase.class); addTest(ODataTestSuite.suite()); // TODO Fix Zip client test case // addTestSuite(ZipClientTestCase.class); // Tests based on HTTP client connectors are not supported by the GAE // edition. addTestSuite(ComponentXmlTestCase.class); addTestSuite(DigesterRepresentationTestCase.class); addTestSuite(HeaderTestCase.class); addTestSuite(HttpBasicTestCase.class); addTestSuite(HttpDigestTestCase.class); addTestSuite(RangeTestCase.class); addTestSuite(RangeRepresentationTestCase.class); addTestSuite(RedirectTestCase.class); addTestSuite(SecurityTestCase.class); addTestSuite(TemplateFilterTestCase.class); addTest(EngineTestSuite.suite()); addTest(AllJaxRsTests.suite()); addTest(AllSpringTests.suite()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/AbstractFilterTestCase.java0000664000175000017500000001010611757206354030421 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.routing.Filter; /** * Tests where every Filter should run through. * * @author Lars Heuer */ public abstract class AbstractFilterTestCase extends RestletTestCase { /** * Returns a Filter to be used for the tests. * * @return Filter instance. */ protected abstract Filter getFilter(); /** * Returns a request. * * @return Request instance. */ protected abstract Request getRequest(); /** * Returns a response. * * @param request * The associated request. * @return Response instance. */ protected abstract Response getResponse(Request request); /** * Returns a restlet. * * @return Restlet instance. */ protected abstract Restlet getRestlet(); /** * Returns a restlet class. * * @return Restlet class. */ protected abstract Class getRestletClass(); /** * Test Restlet instance attaching/detaching. */ public void testAttachDetachInstance() throws Exception { final Filter filter = getFilter(); assertFalse(filter.hasNext()); filter.setNext(getRestlet()); filter.start(); assertTrue(filter.isStarted()); assertFalse(filter.isStopped()); final Request request = getRequest(); final Response response = getResponse(request); filter.handle(request, response); assertTrue(filter.hasNext()); filter.setNext((Restlet) null); assertFalse(filter.hasNext()); } /** * Test not started Filter. */ public void testIllegalStartedState() throws Exception { final Filter filter = getFilter(); filter.setNext(getRestlet()); assertTrue(filter.hasNext()); assertFalse(filter.isStarted()); assertTrue(filter.isStopped()); final Request request = getRequest(); final Response response = getResponse(request); try { filter.handle(request, response); if (!filter.isStarted()) { fail("Filter handles call without being started"); } } catch (Exception ex) { // noop. } } /** * Test with null target. */ public void testIllegalTarget() throws Exception { final Filter filter = getFilter(); filter.start(); assertTrue(filter.isStarted()); assertFalse(filter.isStopped()); assertFalse(filter.hasNext()); final Request request = getRequest(); final Response response = getResponse(request); try { filter.handle(request, response); fail("Filter handles call without a target"); } catch (Exception ex) { // noop. } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/0000775000175000017500000000000012001473213024437 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/EngineTestSuite.java0000664000175000017500000000622511757206352030405 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import junit.framework.Test; import junit.framework.TestSuite; /** * Suite of unit tests for the Restlet Framework. * * @author Jerome Louvel */ public class EngineTestSuite extends TestSuite { /** * JUnit constructor. * * @return The unit test. */ public static Test suite() { return new EngineTestSuite(); } /** Constructor. */ public EngineTestSuite() { addTestSuite(AlphaNumericComparatorTestCase.class); addTestSuite(AnnotationUtilsTestCase.class); addTestSuite(Base64TestCase.class); addTestSuite(BioUtilsTestCase.class); addTestSuite(ByteUtilsTestCase.class); addTestSuite(CookiesTestCase.class); addTestSuite(ContentTypeTestCase.class); addTestSuite(FormTestCase.class); addTestSuite(HeaderTestCase.class); addTestSuite(HttpCallTestCase.class); addTestSuite(ImmutableDateTestCase.class); addTestSuite(InputEntityStreamTestCase.class); addTestSuite(UnclosableInputStreamTestCase.class); addTestSuite(UnclosableOutputStreamTestCase.class); addTestSuite(PreferencesTestCase.class); // Tests based on HTTP client connectors are not supported by the GAE // edition. addTestSuite(AuthenticationTestCase.class); addTestSuite(ChunkedEncodingPutTestCase.class); addTestSuite(ChunkedEncodingTestCase.class); addTestSuite(ChunkedInputStreamTestCase.class); addTestSuite(ChunkedOutputStreamTestCase.class); addTestSuite(GetTestCase.class); addTestSuite(GetChunkedTestCase.class); addTestSuite(PostPutTestCase.class); addTestSuite(RemoteClientAddressTestCase.class); addTestSuite(SslGetTestCase.class); addTestSuite(SslClientContextGetTestCase.class); addTestSuite(TunnelFilterTestCase.class); addTestSuite(UserAgentTunnelFilterTestCase.class); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/ChunkedInputStreamTestCase.java0000664000175000017500000001167711757206352032546 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.restlet.engine.http.io.ChunkedInputStream; import org.restlet.engine.http.io.ChunkedOutputStream; import org.restlet.test.RestletTestCase; /** * Test cases for the chunked decoding. * * @author
Kevin Conaway */ public class ChunkedInputStreamTestCase extends RestletTestCase { private String read(InputStream input) throws IOException { final byte[] buffer = new byte[1024]; final StringBuilder result = new StringBuilder(); int bytesRead = input.read(buffer); while (bytesRead != -1) { result.append(new String(buffer, 0, bytesRead)); bytesRead = input.read(buffer); } return result.toString(); } public void testClose() throws IOException { final String data = "test data"; InputStream input = write(data); InputStream chunked = new ChunkedInputStream(null, input); assertEquals('t', chunked.read()); chunked.close(); assertEquals(-1, chunked.read()); input = write(data); chunked = new ChunkedInputStream(null, input); chunked.close(); assertEquals(-1, chunked.read()); } public void testRead() throws IOException { String data = "test data"; InputStream input = write(data); InputStream chunked = new ChunkedInputStream(null, input); assertEquals(data, read(chunked)); input = new ByteArrayInputStream( "1a; ignore-stuff-here\r\nabcdefghijklmnopqrstuvwxyz\r\n10; other stuff\r\n1234567890abcdef\r\n0\r\n\r\n" .getBytes()); chunked = new ChunkedInputStream(null, input); assertEquals("abcdefghijklmnopqrstuvwxyz1234567890abcdef", read(chunked)); input = new ByteArrayInputStream( "\r\n1a; ignore-stuff-here\r\nabcdefghijklmnopqrstuvwxyz\r\n10; other stuff\r\n1234567890abcdef\r\n0\r\n\r\n" .getBytes()); chunked = new ChunkedInputStream(null, input); assertEquals("abcdefghijklmnopqrstuvwxyz1234567890abcdef", read(chunked)); data = ""; input = write(data); chunked = new ChunkedInputStream(null, input); assertEquals(data, read(chunked)); data = "\r\n"; input = write(data); chunked = new ChunkedInputStream(null, input); assertEquals(data, read(chunked)); } public void testReadWithChunkSizeComments() throws IOException { InputStream input = new ByteArrayInputStream( "9; comment\r\ntest data\r\n0\r\n\r\n".getBytes()); InputStream chunked = new ChunkedInputStream(null, input); assertEquals("test data", read(chunked)); input = new ByteArrayInputStream( "9 ; comment\r\ntest data\r\n0\r\n\r\n".getBytes()); chunked = new ChunkedInputStream(null, input); assertEquals("test data", read(chunked)); input = new ByteArrayInputStream( "4; comment\r\ntest\r\n5; another comment\r\n data\r\n0\r\n\r\n" .getBytes()); chunked = new ChunkedInputStream(null, input); assertEquals("test data", read(chunked)); } private InputStream write(String data) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream chunked = new ChunkedOutputStream(out, 2); chunked.write(data.getBytes()); chunked.close(); return new ByteArrayInputStream(out.toByteArray()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/GetChunkedTestCase.java0000664000175000017500000001037011757206354031001 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.ext.xml.TransformRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * Test that a simple get works for all the connectors. * * @author Kevin Conaway */ public class GetChunkedTestCase extends BaseConnectorsTestCase { public static class GetChunkedTestResource extends ServerResource { public GetChunkedTestResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); } @Override public Representation get(Variant variant) { // Get the source XML final Representation source = new StringRepresentation( "Hello world", MediaType.APPLICATION_XML); final StringBuilder builder = new StringBuilder(); builder .append(""); builder.append(""); builder.append(""); builder.append(""); builder.append(""); builder.append(""); final Representation transformSheet = new StringRepresentation( builder.toString(), MediaType.TEXT_XML); // Instantiates the representation with both source and stylesheet. final Representation representation = new TransformRepresentation( getContext(), source, transformSheet); // Set the right media-type representation.setMediaType(variant.getMediaType()); return representation; } } @Override protected void call(String uri) throws Exception { final Request request = new Request(Method.GET, uri); Client c = new Client(Protocol.HTTP); final Response r = c.handle(request); assertEquals(r.getStatus().getDescription(), Status.SUCCESS_OK, r .getStatus()); assertEquals("Hello world", r.getEntity().getText()); c.stop(); } @Override protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", GetChunkedTestResource.class); return router; } }; return application; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/BaseConnectorsTestCase.java0000664000175000017500000001746211757206352031677 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.ConnectorHelper; import org.restlet.engine.Engine; import org.restlet.engine.http.connector.HttpClientHelper; import org.restlet.engine.http.connector.HttpServerHelper; import org.restlet.test.RestletTestCase; /** * Base test case that will call an abstract method for several client/server * connectors configurations. * * @author Kevin Conaway */ public abstract class BaseConnectorsTestCase extends RestletTestCase { private Component component; private final boolean enabledClientApache = true; private final boolean enabledClientDefault = true; private final boolean enabledClientJdkNet = true; private final boolean enabledServerDefault = true; private final boolean enabledServerGrizzly = true; private final boolean enabledServerJetty = true; private final boolean enabledServerNetty = false; private final boolean enabledServerSimple = true; protected abstract void call(String uri) throws Exception; protected abstract Application createApplication(Component component); // Helper methods private void runTest(ConnectorHelper server, ConnectorHelper client) throws Exception { Engine nre = new Engine(false); nre.getRegisteredServers().add(server); nre.getRegisteredClients().add(client); nre.registerDefaultAuthentications(); nre.registerDefaultConverters(); org.restlet.engine.Engine.setInstance(nre); String uri = start(); try { call(uri); } finally { stop(); } } private String start() throws Exception { this.component = new Component(); final Server server = this.component.getServers().add(Protocol.HTTP, 0); // server.getContext().getParameters().add("tracing", "true"); final Application application = createApplication(this.component); this.component.getDefaultHost().attach(application); this.component.start(); return "http://localhost:" + server.getEphemeralPort() + "/test"; } private void stop() throws Exception { if ((this.component != null) && this.component.isStarted()) { this.component.stop(); } this.component = null; } @Override protected void tearDown() throws Exception { super.tearDown(); // Restore a clean engine org.restlet.engine.Engine.register(); } public void testDefaultAndApache() throws Exception { if (this.enabledServerDefault && this.enabledClientApache) { runTest(new HttpServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testDefaultAndDefault() throws Exception { if (this.enabledServerDefault && this.enabledClientDefault) { runTest(new HttpServerHelper(null), new HttpClientHelper(null)); } } public void testDefaultAndJdkNet() throws Exception { if (this.enabledServerDefault && this.enabledClientJdkNet) { runTest(new HttpServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } public void testGrizzlyAndApache() throws Exception { if (this.enabledServerGrizzly && this.enabledClientApache) { runTest(new org.restlet.ext.grizzly.HttpServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testGrizzlyAndDefault() throws Exception { if (this.enabledServerGrizzly && this.enabledClientDefault) { runTest(new org.restlet.ext.grizzly.HttpServerHelper(null), new HttpClientHelper(null)); } } public void testGrizzlyAndJdkNet() throws Exception { if (this.enabledServerGrizzly && this.enabledClientJdkNet) { runTest(new org.restlet.ext.grizzly.HttpServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } public void testJettyAndApache() throws Exception { if (this.enabledServerJetty && this.enabledClientApache) { runTest(new org.restlet.ext.jetty.HttpServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testJettyAndDefault() throws Exception { if (this.enabledServerJetty && this.enabledClientDefault) { runTest(new org.restlet.ext.jetty.HttpServerHelper(null), new HttpClientHelper(null)); } } public void testJettyAndJdkNet() throws Exception { if (this.enabledServerJetty && this.enabledClientJdkNet) { runTest(new org.restlet.ext.jetty.HttpServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } public void testNettyAndApache() throws Exception { if (this.enabledServerNetty && this.enabledClientApache) { runTest(new org.restlet.ext.netty.HttpServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testNettyAndDefault() throws Exception { if (this.enabledServerNetty && this.enabledClientDefault) { runTest(new org.restlet.ext.netty.HttpServerHelper(null), new HttpClientHelper(null)); } } public void testNettyAndJdkNet() throws Exception { if (this.enabledServerNetty && this.enabledClientJdkNet) { runTest(new org.restlet.ext.netty.HttpServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } public void testSimpleAndApache() throws Exception { if (this.enabledServerSimple && this.enabledClientApache) { runTest(new org.restlet.ext.simple.HttpServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testSimpleAndDefault() throws Exception { if (this.enabledServerSimple && this.enabledClientDefault) { runTest(new org.restlet.ext.simple.HttpServerHelper(null), new HttpClientHelper(null)); } } public void testSimpleAndJdkNet() throws Exception { if (this.enabledServerSimple && this.enabledClientJdkNet) { runTest(new org.restlet.ext.simple.HttpServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/ChunkedEncodingPutTestCase.java0000664000175000017500000001076411757206354032510 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * This tests the ability of the connectors to handle chunked encoding. * * The test uses each connector to PUT an entity that will be sent chunked and * also to receive a chunked response. */ public class ChunkedEncodingPutTestCase extends BaseConnectorsTestCase { private static int LOOP_NUMBER = 20; /** * Test resource that answers to PUT requests by sending back the received * entity. */ public static class PutTestResource extends ServerResource { public PutTestResource() { getVariants().add(new Variant(MediaType.TEXT_XML)); setNegotiated(false); } @Override public Representation put(Representation entity) { return entity; } } /** * Returns a StringRepresentation which size depends on the given argument. * * @param size * the size of the representation * @return A DomRepresentation. */ private static Representation createChunckedRepresentation(int size) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < size; i++) { builder.append("a"); } final Representation rep = new StringRepresentation(builder.toString(), MediaType.TEXT_PLAIN); rep.setSize(Representation.UNKNOWN_SIZE); return rep; } @Override protected void call(String uri) throws Exception { for (int i = 0; i < LOOP_NUMBER; i++) { sendPut(uri, 10); } for (int i = 0; i < LOOP_NUMBER; i++) { sendPut(uri, 1024); } for (int i = 0; i < LOOP_NUMBER; i++) { sendPut(uri, 10240); } sendPut(uri, 10); } @Override protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", PutTestResource.class); return router; } }; return application; } private void sendPut(String uri, int size) throws Exception { Request request = new Request(Method.PUT, uri, createChunckedRepresentation(size)); Client c = new Client(Protocol.HTTP); Response r = c.handle(request); try { if (!r.getStatus().isSuccess()) { System.out.println(r.getStatus()); } assertNotNull(r.getEntity()); assertEquals(createChunckedRepresentation(size).getText(), r .getEntity().getText()); } finally { r.release(); c.stop(); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/UserAgentTestResource.java0000664000175000017500000000444611757206352031576 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Simple resource that returns at least text/html and text/xml representations. */ public class UserAgentTestResource extends ServerResource { public UserAgentTestResource() { getVariants().add(new Variant(MediaType.TEXT_XML)); getVariants().add(new Variant(MediaType.TEXT_HTML)); } @Override public Representation get(Variant variant) throws ResourceException { final MediaType mediaType = variant.getMediaType(); if (mediaType.equals(MediaType.TEXT_XML)) { return new StringRepresentation("b", mediaType); } else if (mediaType.equals(MediaType.TEXT_HTML)) { return new StringRepresentation("a", mediaType); } return null; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/InputEntityStreamTestCase.java0000664000175000017500000000556511757206354032442 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.restlet.engine.http.io.InputEntityStream; import org.restlet.engine.http.io.SizedInputStream; import org.restlet.engine.io.BioUtils; import org.restlet.test.RestletTestCase; /** * Test cases for the input entity stream. * * @author Kevin Conaway * @author Jerome Louvel */ public class InputEntityStreamTestCase extends RestletTestCase { public void testRead() { String data = "test data"; InputStream input = new ByteArrayInputStream(data.getBytes()); assertEquals("test", BioUtils .toString(new SizedInputStream(null, input, 4))); } public void testReset() throws IOException { String data = "12345678"; InputStream input = new ByteArrayInputStream(data.getBytes()); InputEntityStream ies = new SizedInputStream(null, input, 4); assertEquals(true, ies.markSupported()); ies.mark(10); assertEquals('1', (char) ies.read()); assertEquals('2', (char) ies.read()); assertEquals('3', (char) ies.read()); assertEquals('4', (char) ies.read()); assertEquals(-1, ies.read()); assertEquals(-1, ies.read()); ies.reset(); assertEquals('1', (char) ies.read()); assertEquals('2', (char) ies.read()); ies.mark(10); assertEquals('3', (char) ies.read()); assertEquals('4', (char) ies.read()); ies.reset(); assertEquals('3', (char) ies.read()); assertEquals('4', (char) ies.read()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/PreferencesTestCase.java0000664000175000017500000000624211757206352031222 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.http.header.PreferenceReader; import org.restlet.engine.http.header.PreferenceWriter; import org.restlet.test.RestletTestCase; /** * Unit tests for the Preference related classes. * * @author Jerome Louvel */ public class PreferencesTestCase extends RestletTestCase { /** * Tests the parsing of a single preference header. * * @param headerValue * The preference header. */ private void testMediaType(String headerValue, boolean testEquals) throws IOException { PreferenceReader pr = new PreferenceReader( PreferenceReader.TYPE_MEDIA_TYPE, headerValue); List> prefs = new ArrayList>(); pr.addValues(prefs); // Rewrite the header String newHeaderValue = PreferenceWriter.write(prefs); // Reread and rewrite the header (prevent formatting issues) pr = new PreferenceReader(PreferenceReader.TYPE_MEDIA_TYPE, headerValue); prefs = new ArrayList>(); pr.addValues(prefs); String newHeaderValue2 = PreferenceWriter.write(prefs); if (testEquals) { // Compare initial and new headers assertEquals(newHeaderValue, newHeaderValue2); } } /** * Tests the preferences parsing. */ public void testParsing() throws IOException { testMediaType( "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;LEVEL=2;q=0.4;ext1, */*;q=0.5", true); testMediaType( "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5", false); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/Base64TestCase.java0000664000175000017500000000547211757206352030011 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.util.Arrays; import org.restlet.engine.util.Base64; import org.restlet.test.RestletTestCase; /** * Base64 test case. * * @author Ray Waldin. */ public class Base64TestCase extends RestletTestCase { public void roundTrip(byte[] bytes, boolean newlines) throws Exception { assert (Arrays.equals(Base64.decode(Base64.encode(bytes, newlines)), bytes)); } public void test() throws Exception { final byte[] b = ("Man is distinguished, not only by his reason, but by this singular passion from " + "other animals, which is a lust of the mind, that by a perseverance of delight " + "in the continued and indefatigable generation of knowledge, exceeds the short " + "vehemence of any carnal pleasure.").getBytes(); final String s = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz\n" + "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg\n" + "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu\n" + "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo\n" + "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; final String base64 = Base64.encode(b, true); assertEquals(s, base64); roundTrip(b, true); assertEquals(new String(b), new String(Base64.decode(base64))); assertEquals("scott:tiger", new String(Base64 .decode("c2NvdHQ6dGlnZXI="))); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/AlphaNumericComparatorTestCase.java0000664000175000017500000000471111757206352033360 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import junit.framework.Assert; import org.restlet.data.Reference; import org.restlet.engine.util.AlphaNumericComparator; import org.restlet.resource.Directory; import org.restlet.test.RestletTestCase; /** * Test case for the alphanum algorithm used by {@link Directory}. * * @author Davide Angelocola */ public class AlphaNumericComparatorTestCase extends RestletTestCase { private static List refs(String... uris) { List result = new LinkedList(); for (String uri : uris) { result.add(new Reference(uri)); } return result; } private static List unsorted = refs("1", "2", "3", "1.0", "1.1", "1.1.1", "2.0", "2.2", "2.2.2", "3.0", "3.3"); private static List expected = refs("1", "1.0", "1.1", "1.1.1", "2", "2.0", "2.2", "2.2.2", "3", "3.0", "3.3"); public void testBug() { List result = new ArrayList(unsorted); Collections.sort(result, new AlphaNumericComparator()); Assert.assertEquals(expected, result); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/CookiesTestCase.java0000664000175000017500000001636611757206352030365 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.restlet.data.Cookie; import org.restlet.data.CookieSetting; import org.restlet.engine.http.header.CookieReader; import org.restlet.engine.http.header.CookieSettingReader; import org.restlet.engine.http.header.CookieSettingWriter; import org.restlet.engine.http.header.CookieWriter; import org.restlet.engine.util.DateUtils; import org.restlet.test.RestletTestCase; /** * Unit tests for the Cookie related classes. * * @author Jerome Louvel */ public class CookiesTestCase extends RestletTestCase { /** * Test one cookie header. * * @param headerValue * The cookie header value. * @throws IOException */ private void testCookie(String headerValue) throws IOException { CookieReader cr = new CookieReader(headerValue); List cookies = new ArrayList(); Cookie cookie = cr.readValue(); while (cookie != null) { cookies.add(cookie); cookie = cr.readValue(); } // Rewrite the header String newHeaderValue = CookieWriter.write(cookies); // Compare initial and new headers assertEquals(headerValue, newHeaderValue); } /** * Test one cookie header. * * @param headerValue * The cookie header value. * @throws IOException */ private void testCookieValues(String headerValue) throws IOException { CookieReader cr = new CookieReader(headerValue); List cookies = new ArrayList(); Cookie cookie = cr.readValue(); while (cookie != null) { cookies.add(cookie); cookie = cr.readValue(); } // Rewrite the header String newHeaderValue = CookieWriter.write(cookies); // Reparse List cookies2 = new ArrayList(); cr = new CookieReader(newHeaderValue); cookie = cr.readValue(); while (cookie != null) { cookies2.add(cookie); cookie = cr.readValue(); } // Compare initial and new cookies assertEquals(cookies.size(), cookies2.size()); for (int i = 0; i < cookies.size(); i++) { assertEquals(cookies.get(i).getName(), cookies2.get(i).getName()); assertEquals(cookies.get(i).getValue(), cookies2.get(i).getValue()); } } /** * Test a cookie date value. * * @param headerValue * The cookie date value. */ private void testCookieDate(String dateValue) { final Date date = DateUtils.parse(dateValue, DateUtils.FORMAT_RFC_1036); // Rewrite the date final String newDateValue = DateUtils.format(date, DateUtils.FORMAT_RFC_1036.get(0)); // Compare initial and new headers assertEquals(dateValue, newDateValue); } /** * Test one set cookie header. * * @param headerValue * The set cookie header value. * @param compare * Indicates if the new header should be compared with the old * one. * @throws IOException */ private void testCookieSetting(String headerValue, boolean compare) throws IOException { CookieSettingReader cr = new CookieSettingReader(headerValue); CookieSetting cookie = cr.readValue(); // Rewrite the header String newHeaderValue = CookieSettingWriter.write(cookie); // Compare initial and new headers if (compare) { boolean result = newHeaderValue.toLowerCase().startsWith( headerValue.toLowerCase()); assertTrue(result); } } /** * Tests the parsing of cookies. */ public void testParsing() throws IOException { // Netscape speficiation testCookie("CUSTOMER=WILE_E_COYOTE"); testCookie("CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001"); testCookie("CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX"); testCookie("NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001"); testCookieSetting("CUSTOMER=WILE_E_COYOTE; path=/", true); testCookieSetting("PART_NUMBER=ROCKET_LAUNCHER_0001; path=/", true); testCookieSetting("SHIPPING=FEDEX; path=/foo", true); testCookieSetting("NUMBER=RIDING_ROCKET_0023; path=/ammo", true); testCookieDate("Tuesday, 09-Nov-99 23:12:40 GMT"); // RFC 2109 testCookie("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\""); testCookie("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""); testCookie("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"; Shipping=\"FedEx\"; $Path=\"/acme\""); testCookie("$Version=\"1\"; Part_Number=\"Riding_Rocket_0023\"; $Path=\"/acme/ammo\"; Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""); testCookieSetting( "Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\"", true); testCookieSetting( "Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\"", true); testCookieSetting("Shipping=\"FedEx\"; Version=\"1\"; Path=\"/acme\"", true); testCookieSetting( "Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\"", true); testCookieSetting( "Part_Number=\"Riding_Rocket_0023\"; Version=\"1\"; Path=\"/acme/ammo\"", true); // Bug #49 testCookieSetting( "RMS_ADMETA_VISITOR_RMS=27756847%3A240105; expires=Thu, 02 Mar 2006 21:09:00 GMT; path=/; domain=.admeta.com", false); testCookieValues("Cookie 1=One; Cookie 2=Two; Cookie 3=Three; Cookie 4=Four; Cookie 5=\"Five\"; Cookie 6=\"Six\""); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/FormTestCase.java0000664000175000017500000000570011757206352027662 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.engine.util.FormReader; import org.restlet.test.RestletTestCase; /** * Unit tests for the {@link Form} class. * * @author Jerome Louvel */ public class FormTestCase extends RestletTestCase { public void testParsing() throws IOException { final Form form = new Form(); form.add("name", "John D. Mitchell"); form.add("email", "john@bob.net"); form.add("email2", "joe@bob.net"); final String query = form.encode(CharacterSet.UTF_8); final Form newForm = new FormReader(query, CharacterSet.UTF_8, '&') .read(); final String newQuery = newForm.encode(CharacterSet.UTF_8); assertEquals(query, newQuery); } public void testEmptyParameter() throws IOException { // Manual construction of form Form form = new Form(); form.add("normalParam", "abcd"); form.add("emptyParam", ""); form.add("nullParam", null); assertEquals(3, form.size()); assertEquals("abcd", form.getFirstValue("normalParam")); assertEquals("", form.getFirstValue("emptyParam")); assertNull(form.getFirstValue("nullParam")); assertNull(form.getFirstValue("unknownParam")); // Construction of form via URI query parsing form = new Form("normalParam=abcd&emptyParam=&nullParam"); assertEquals(3, form.size()); assertEquals("abcd", form.getFirstValue("normalParam")); assertEquals("", form.getFirstValue("emptyParam")); assertNull(form.getFirstValue("nullParam")); assertNull(form.getFirstValue("unknownParam")); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/HeaderTestCase.java0000664000175000017500000001742611757206352030157 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.restlet.data.ClientInfo; import org.restlet.data.Encoding; import org.restlet.data.MediaType; import org.restlet.engine.http.header.EncodingReader; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.http.header.PreferenceReader; import org.restlet.engine.http.header.TokenReader; import org.restlet.engine.util.DateUtils; import org.restlet.test.RestletTestCase; /** * Unit tests for the header. * * @author Jerome Louvel */ public class HeaderTestCase extends RestletTestCase { /** * Test the {@link HeaderReader#addValues(java.util.Collection)} method. */ public void testAddValues() { List list = new ArrayList(); new EncodingReader("gzip,deflate").addValues(list); assertEquals(list.size(), 2); assertEquals(list.get(0), Encoding.GZIP); assertEquals(list.get(1), Encoding.DEFLATE); list = new ArrayList(); new EncodingReader("gzip,identity, deflate").addValues(list); assertEquals(list.size(), 2); assertEquals(list.get(0), Encoding.GZIP); assertEquals(list.get(1), Encoding.DEFLATE); list = new ArrayList(); new EncodingReader("identity").addValues(list); assertTrue(list.isEmpty()); list = new ArrayList(); new EncodingReader("identity,").addValues(list); assertTrue(list.isEmpty()); list = new ArrayList(); new EncodingReader("").addValues(list); assertTrue(list.isEmpty()); list = new ArrayList(); new EncodingReader(null).addValues(list); assertTrue(list.isEmpty()); TokenReader tr = new TokenReader("bytes"); List l = tr.readValues(); assertTrue(l.contains("bytes")); tr = new TokenReader("bytes,"); l = tr.readValues(); assertTrue(l.contains("bytes")); assertEquals(l.size(), 1); tr = new TokenReader(""); l = tr.readValues(); assertEquals(l.size(), 1); } public void testInvalidDate() { final String headerValue = "-1"; final Date date = DateUtils.parse(headerValue, DateUtils.FORMAT_RFC_1123); assertNull(date); final Date unmodifiableDate = DateUtils.unmodifiable(date); assertNull(unmodifiableDate); } /** * Tests the parsing. */ public void testParsing() { String header1 = "Accept-Encoding,User-Agent"; String header2 = "Accept-Encoding , User-Agent"; final String header3 = "Accept-Encoding,\r\tUser-Agent"; final String header4 = "Accept-Encoding,\r User-Agent"; final String header5 = "Accept-Encoding, \r \t User-Agent"; String[] values = new String[] { "Accept-Encoding", "User-Agent" }; testValues(header1, values); testValues(header2, values); testValues(header3, values); testValues(header4, values); testValues(header5, values); header1 = "Accept-Encoding, Accept-Language, Accept"; header2 = "Accept-Encoding,Accept-Language,Accept"; values = new String[] { "Accept-Encoding", "Accept-Language", "Accept" }; testValues(header1, values); testValues(header2, values); // Test the parsing of a "Accept-encoding" header header1 = "gzip;q=1.0, identity;q=0.5 , *;q=0"; ClientInfo clientInfo = new ClientInfo(); PreferenceReader.addEncodings(header1, clientInfo); assertEquals(clientInfo.getAcceptedEncodings().get(0).getMetadata(), Encoding.GZIP); assertEquals(clientInfo.getAcceptedEncodings().get(0).getQuality(), 1.0F); assertEquals(clientInfo.getAcceptedEncodings().get(1).getMetadata(), Encoding.IDENTITY); assertEquals(clientInfo.getAcceptedEncodings().get(1).getQuality(), 0.5F); assertEquals(clientInfo.getAcceptedEncodings().get(2).getMetadata(), Encoding.ALL); assertEquals(clientInfo.getAcceptedEncodings().get(2).getQuality(), 0F); // Test the parsing of a "Accept" header header1 = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"; clientInfo = new ClientInfo(); PreferenceReader.addMediaTypes(header1, clientInfo); assertEquals(clientInfo.getAcceptedMediaTypes().get(0).getMetadata(), MediaType.TEXT_HTML); assertEquals(clientInfo.getAcceptedMediaTypes().get(0).getQuality(), 1.0F); assertEquals(clientInfo.getAcceptedMediaTypes().get(1).getMetadata(), MediaType.IMAGE_GIF); assertEquals(clientInfo.getAcceptedMediaTypes().get(1).getQuality(), 1.0F); assertEquals(clientInfo.getAcceptedMediaTypes().get(2).getMetadata(), MediaType.IMAGE_JPEG); assertEquals(clientInfo.getAcceptedMediaTypes().get(2).getQuality(), 1.0F); assertEquals(clientInfo.getAcceptedMediaTypes().get(3).getMetadata(), new MediaType("*")); assertEquals(clientInfo.getAcceptedMediaTypes().get(3).getQuality(), 0.2F); assertEquals(clientInfo.getAcceptedMediaTypes().get(4).getMetadata(), MediaType.ALL); assertEquals(clientInfo.getAcceptedMediaTypes().get(4).getQuality(), 0.2F); // Test a more complex header header1 = "text/html, application/vnd.wap.xhtml+xml, " + "application/xhtml+xml; profile=\"http://www.wapforum.org/xhtml\", " + "image/gif, image/jpeg, image/pjpeg, audio/amr, */*"; clientInfo = new ClientInfo(); PreferenceReader.addMediaTypes(header1, clientInfo); assertEquals(clientInfo.getAcceptedMediaTypes().get(0).getMetadata(), MediaType.TEXT_HTML); assertEquals(clientInfo.getAcceptedMediaTypes().get(0).getQuality(), 1.0F); } /** * Test that the parsing of a header returns the given array of values. * * @param header * The header value to parse. * @param values * The parsed values. */ public void testValues(String header, String[] values) { HeaderReader hr = new HeaderReader(header); String value = hr.readRawValue(); int index = 0; while (value != null) { assertEquals(value, values[index]); index++; value = hr.readRawValue(); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/SslClientContextGetTestCase.java0000664000175000017500000000663411757206352032673 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; 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.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * Test that a simple get using SSL works for all the connectors. * * @author Kevin Conaway * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) */ public class SslClientContextGetTestCase extends SslBaseConnectorsTestCase { public static class GetTestResource extends ServerResource { public GetTestResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); } @Override public Representation get(Variant variant) { return new StringRepresentation("Hello world", MediaType.TEXT_PLAIN); } } @Override protected void call(String uri) throws Exception { final Request request = new Request(Method.GET, uri); final Client client = new Client(Protocol.HTTPS); if (client.getContext() == null) { client.setContext(new Context()); } configureSslServerParameters(client.getContext()); final Response r = client.handle(request); assertEquals(r.getStatus().getDescription(), Status.SUCCESS_OK, r .getStatus()); assertEquals("Hello world", r.getEntity().getText()); Thread.sleep(200); client.stop(); } @Override protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", GetTestResource.class); return router; } }; return application; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/package.html0000664000175000017500000000007211757206354026740 0ustar jamespagejamespage JUnit tests. @since 1.0 restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/BioUtilsTestCase.java0000664000175000017500000000451411757206352030513 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.restlet.data.MediaType; import org.restlet.representation.OutputRepresentation; import org.restlet.test.RestletTestCase; /** * Test case for the ByteUtils class. * * @author Kevin Conaway */ public class BioUtilsTestCase extends RestletTestCase { public void testPipe() throws IOException { final byte[] content = new byte[] { 1, 2, 3, -1, -2, -3, 4, 5, 6 }; ByteArrayInputStream bais = new ByteArrayInputStream(content); OutputRepresentation or = new OutputRepresentation( MediaType.APPLICATION_OCTET_STREAM) { @Override public void write(OutputStream outputStream) throws IOException { outputStream.write(content); } }; InputStream is = or.getStream(); int result = 0; while (result != -1) { result = is.read(); assertEquals(bais.read(), result); System.out.println(result); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/HttpCallTestCase.java0000664000175000017500000001152011757206352030467 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import org.restlet.data.Disposition; import org.restlet.engine.http.header.DispositionReader; import org.restlet.engine.http.header.DispositionWriter; import org.restlet.test.RestletTestCase; /** * Unit tests for the HTTP calls. * * @author Kevin Conaway */ public class HttpCallTestCase extends RestletTestCase { public void testFormatContentDisposition() { Disposition disposition = new Disposition(); assertEquals("", DispositionWriter.write(disposition)); disposition = new Disposition(Disposition.TYPE_ATTACHMENT); assertEquals("attachment", DispositionWriter.write(disposition)); disposition.setFilename(""); assertEquals("attachment; filename=", DispositionWriter .write(disposition)); disposition.setFilename("test.txt"); assertEquals("attachment; filename=test.txt", DispositionWriter .write(disposition)); disposition.setFilename("file with space.txt"); assertEquals("attachment; filename=\"file with space.txt\"", DispositionWriter.write(disposition)); disposition.setType(Disposition.TYPE_INLINE); assertEquals("inline; filename=\"file with space.txt\"", DispositionWriter.write(disposition)); disposition.getParameters().clear(); Calendar c = new GregorianCalendar(Locale.ENGLISH); c.set(Calendar.YEAR, 2009); c.set(Calendar.MONTH, 10); c.set(Calendar.DAY_OF_MONTH, 11); c.set(Calendar.AM_PM, Calendar.AM); c.set(Calendar.HOUR, 10); c.set(Calendar.MINUTE, 11); c.set(Calendar.SECOND, 12); c.set(Calendar.MILLISECOND, 13); c.setTimeZone(TimeZone.getTimeZone("GMT")); disposition.setCreationDate(c.getTime()); assertEquals("inline; creation-date=\"Wed, 11 Nov 09 10:11:12 GMT\"", DispositionWriter.write(disposition)); } public void testParseContentDisposition() throws IOException { Disposition disposition = new DispositionReader( "attachment; fileName=\"file.txt\"").readValue(); assertEquals("file.txt", disposition.getParameters().getFirstValue( "fileName")); disposition = new DispositionReader("attachment; fileName=file.txt") .readValue(); assertEquals("file.txt", disposition.getParameters().getFirstValue( "fileName")); disposition = new DispositionReader( "attachment; filename=\"file with space.txt\"").readValue(); assertEquals("file with space.txt", disposition.getParameters() .getFirstValue("filename")); disposition = new DispositionReader("attachment; filename=\"\"") .readValue(); assertEquals("", disposition.getParameters().getFirstValue("filename")); disposition = new DispositionReader("attachment; filename=") .readValue(); assertNull(disposition.getParameters().getFirstValue("filename")); disposition = new DispositionReader("attachment; filenam").readValue(); assertNull(disposition.getParameters().getFirstValue("filename")); disposition = new DispositionReader( "attachment; modification-date=\"Wed, 11 Nov 09 22:11:12 GMT\"") .readValue(); String str = disposition.getParameters().getFirstValue( "modification-date"); assertEquals("Wed, 11 Nov 09 22:11:12 GMT", str); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/TunnelFilterTestCase.java0000664000175000017500000003460611757206354031403 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.Application; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.data.Encoding; import org.restlet.data.Form; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Preference; import org.restlet.data.Reference; import org.restlet.engine.application.TunnelFilter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.test.RestletTestCase; import org.restlet.util.Series; /** * Tests cases for the tunnel filter. */ public class TunnelFilterTestCase extends RestletTestCase { /** . */ private static final String EFFECTED = "http://example.org/adf.asdf/af.html"; /** . */ private static final String START_REF_FOR_PATH_TEST = "http://www.example.com/abc/def/"; /** . */ private static final String UNEFFECTED = "http://example.org/abc.def/af.ab"; private List> accCharsets; private List> accEncodings; private List> accLanguages; private List> accMediaTypes; private String lastCreatedReference; private Request request; private Response response; private TunnelFilter tunnelFilter; private String userAgent; void assertCharSets(CharacterSet... characterSets) { assertEqualSet(this.accCharsets, characterSets); } void assertEncodings(Encoding... encodings) { assertEqualSet(this.accEncodings, encodings); } A assertEqualSet(List> actual, A... expected) { if (actual.size() != expected.length) { System.out.println("Is: " + actual); System.out.println("Should: " + Arrays.asList(expected)); } assertEquals(actual.size(), expected.length); boolean contained = false; for (final Metadata exp : expected) { for (final Preference act : actual) { if (exp.equals(act.getMetadata())) { contained = true; break; } } if (!contained) { final String message = exp + " should be in, but is missing in " + actual; fail(message); } } return null; } void assertLanguages(Language... languages) { assertEqualSet(this.accLanguages, languages); } void assertMediaTypes(MediaType... mediaTypes) { assertEqualSet(this.accMediaTypes, mediaTypes); } void assertMethod(Method method) { assertEquals(this.request.getMethod(), method); } void assertNotSameMethod(Method method) { assertNotSame(this.request.getMethod(), method); } /** * @param expectedCut * @param expectedExtensions */ private void check(String expectedCut, String expectedExtensions) { final Reference resourceRef = this.request.getResourceRef(); assertEquals(expectedCut, resourceRef.toString()); final Reference originalRef = this.request.getOriginalRef(); assertEquals(originalRef, new Reference(this.lastCreatedReference)); assertEquals(expectedCut, resourceRef.toString()); assertEquals(expectedExtensions, resourceRef.getExtensions()); } /** * * @param expectedSubPathCut * if null, the same as subPathOrig * @param expectedExtension * if null, then same as "" for this test */ private void checkFromPath(String expectedSubPathCut, String expectedExtension) { if (expectedSubPathCut == null) { check(this.lastCreatedReference, expectedExtension); } else { check(START_REF_FOR_PATH_TEST + expectedSubPathCut, expectedExtension); } } /** * @see #createGetFromPath(String) * @see #createRequest(Method, String) */ void createGet(String reference) { createRequest(Method.GET, reference); } /** * * @param subPathToCheck * @see #createGet(String) * @see #createRequest(Method, String) */ private void createGetFromPath(String subPathToCheck) { createGet(START_REF_FOR_PATH_TEST + subPathToCheck); } /** * */ void createPost(String reference) { createRequest(Method.POST, reference); } /** * Creates a {@link Request} and put it into {@link #request}.
* To use the methods provided by the test case class use ever the provided * create methods to create a request. * * @param method * @param reference * @see #createPost(String) * @see #createGet(String) * @see #createGetFromPath(String) */ void createRequest(Method method, String reference) { this.request = new Request(method, reference); this.request.setOriginalRef(new Reference(reference)); this.response = new Response(this.request); this.lastCreatedReference = reference; setPrefs(); this.request.getClientInfo().setAgent(this.userAgent); } private void extensionTunnelOff() { final Application application = this.tunnelFilter.getApplication(); application.getTunnelService().setExtensionsTunnel(false); } /** * Call this method to filter the current request */ private void filter() { this.tunnelFilter.beforeHandle(this.request, this.response); setPrefs(); } private void setPrefs() { this.accMediaTypes = this.request.getClientInfo() .getAcceptedMediaTypes(); this.accLanguages = this.request.getClientInfo().getAcceptedLanguages(); this.accCharsets = this.request.getClientInfo() .getAcceptedCharacterSets(); this.accEncodings = this.request.getClientInfo().getAcceptedEncodings(); } @Override public void setUp() throws Exception { super.setUp(); final Application app = new Application(new Context()); Application.setCurrent(app); this.tunnelFilter = new TunnelFilter(app.getContext()); this.tunnelFilter.getApplication().getTunnelService() .setExtensionsTunnel(true); } @Override protected void tearDown() throws Exception { this.tunnelFilter = null; this.request = null; this.response = null; super.tearDown(); } public void testExtMappingOff1() { extensionTunnelOff(); createGet(UNEFFECTED); this.accLanguages .add(new Preference(Language.valueOf("ajh"))); this.accMediaTypes.add(new Preference( MediaType.APPLICATION_STUFFIT)); filter(); assertEquals(UNEFFECTED, this.request.getResourceRef().toString()); assertLanguages(Language.valueOf("ajh")); assertMediaTypes(MediaType.APPLICATION_STUFFIT); assertCharSets(); assertEncodings(); } public void testExtMappingOff2() { extensionTunnelOff(); createGet(EFFECTED); this.accLanguages .add(new Preference(Language.valueOf("ajh"))); this.accMediaTypes.add(new Preference( MediaType.APPLICATION_STUFFIT)); filter(); assertEquals(EFFECTED, this.request.getResourceRef().toString()); assertLanguages(Language.valueOf("ajh")); assertMediaTypes(MediaType.APPLICATION_STUFFIT); assertCharSets(); assertEncodings(); } public void testExtMappingOn() { createGet(UNEFFECTED); filter(); check(UNEFFECTED, "ab"); assertLanguages(); assertCharSets(); assertCharSets(); assertMediaTypes(); createGet(EFFECTED); filter(); check("http://example.org/adf.asdf/af", null); assertMediaTypes(MediaType.TEXT_HTML); assertLanguages(); assertCharSets(); assertCharSets(); createGetFromPath("afhhh"); filter(); checkFromPath(null, null); assertEqualSet(this.accMediaTypes); assertLanguages(); assertEncodings(); assertCharSets(); createGetFromPath("hksf.afsdf"); filter(); checkFromPath(null, "afsdf"); assertMediaTypes(); assertLanguages(); assertEncodings(); assertCharSets(); createGetFromPath("hksf.afsdf.html"); filter(); checkFromPath("hksf.afsdf", "afsdf"); assertMediaTypes(MediaType.TEXT_HTML); assertLanguages(); assertEncodings(); assertCharSets(); createGetFromPath("hksf.afsdf.html.txt"); filter(); checkFromPath("hksf.afsdf.html", "afsdf.html"); assertMediaTypes(MediaType.TEXT_PLAIN); assertLanguages(); assertEncodings(); assertCharSets(); createGetFromPath("hksf.html.afsdf.txt"); filter(); checkFromPath("hksf.html.afsdf", "html.afsdf"); assertMediaTypes(MediaType.TEXT_PLAIN); assertLanguages(); assertEncodings(); assertCharSets(); createGetFromPath("hksf.html.afsdf.txt.en.fr"); filter(); checkFromPath("hksf.html.afsdf.txt.en", "html.afsdf.txt.en"); // Take care about the fact that only one extension per metadata "type" // is allowed: ie only one Language, one encoding, one media type, etc. // assertMediaTypes(MediaType.TEXT_PLAIN); assertMediaTypes(); assertLanguages(Language.FRENCH); assertEncodings(); assertCharSets(); createGetFromPath("hksf.html.afsdf.txt.en"); filter(); checkFromPath("hksf.html.afsdf", "html.afsdf"); assertMediaTypes(MediaType.TEXT_PLAIN); assertLanguages(Language.ENGLISH); assertEncodings(); assertCharSets(); createGet(START_REF_FOR_PATH_TEST); filter(); checkFromPath(null, null); assertMediaTypes(); assertLanguages(); assertEncodings(); assertCharSets(); } public void testMethodTunnelingViaHeader() { tunnelFilter.getTunnelService().setMethodTunnel(true); Map attributesHeader = new HashMap(); Series headers = new Form(); headers.add(HeaderConstants.HEADER_X_HTTP_METHOD_OVERRIDE, Method.GET.getName()); headers.add(HeaderConstants.HEADER_X_FORWARDED_FOR, "TEST"); attributesHeader.put(HeaderConstants.ATTRIBUTE_HEADERS, headers); createGet(UNEFFECTED); this.request.setAttributes(attributesHeader); filter(); assertMethod(Method.GET); createPost(UNEFFECTED); filter(); assertMethod(Method.POST); createPost(UNEFFECTED); tunnelFilter.getTunnelService().setMethodHeader( HeaderConstants.HEADER_X_FORWARDED_FOR); this.request.setAttributes(attributesHeader); filter(); assertNotSameMethod(Method.PUT); createPost(UNEFFECTED); tunnelFilter.getTunnelService().setMethodHeader( HeaderConstants.HEADER_X_FORWARDED_FOR); tunnelFilter.getTunnelService().setHeaderTunnel(false); this.request.setAttributes(attributesHeader); filter(); assertMethod(Method.POST); } public void testWithMatrixParam() { createGet(EFFECTED + ";abcdef"); filter(); check("http://example.org/adf.asdf/af;abcdef", null); assertMediaTypes(MediaType.TEXT_HTML); assertLanguages(); assertCharSets(); assertCharSets(); } public void testMethodTunnelingViaUserAgent() { tunnelFilter.getTunnelService().setExtensionsTunnel(false); tunnelFilter.getTunnelService().setHeaderTunnel(false); tunnelFilter.getTunnelService().setMethodTunnel(false); tunnelFilter.getTunnelService().setPreferencesTunnel(false); tunnelFilter.getTunnelService().setQueryTunnel(false); tunnelFilter.getTunnelService().setUserAgentTunnel(true); createGet(UNEFFECTED); this.accMediaTypes.add(new Preference( MediaType.APPLICATION_ZIP)); filter(); assertEquals(UNEFFECTED, this.request.getResourceRef().toString()); assertMediaTypes(MediaType.APPLICATION_ZIP); assertCharSets(); assertEncodings(); this.userAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)"; createGet(UNEFFECTED); this.accMediaTypes.add(new Preference( MediaType.APPLICATION_ZIP)); filter(); assertEquals(UNEFFECTED, this.request.getResourceRef().toString()); assertMediaTypes(MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML, MediaType.APPLICATION_XML, MediaType.ALL); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/AuthenticationTestCase.java0000664000175000017500000001531711757206352031743 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import java.util.List; import org.restlet.Request; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Digest; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.security.AuthenticatorUtils; import org.restlet.ext.crypto.internal.HttpAwsS3Helper; import org.restlet.test.RestletTestCase; /** * Unit tests for the SecurityData related classes. * * @author Jerome Louvel */ public class AuthenticationTestCase extends RestletTestCase { @Override protected void setUp() throws Exception { super.setUp(); org.restlet.engine.Engine.setInstance(null); } /** * Test Amazon S3 authentication. */ public void testAwsS3() { HttpAwsS3Helper helper = new HttpAwsS3Helper(); // Example Object GET ChallengeWriter cw = new ChallengeWriter(); ChallengeResponse challenge = new ChallengeResponse( ChallengeScheme.HTTP_AWS_S3, "0PN5J17HBGZHT7JJ3X82", "uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o"); Request request = new Request(Method.GET, "http://johnsmith.s3.amazonaws.com/photos/puppy.jpg"); Form httpHeaders = new Form(); httpHeaders.add(HeaderConstants.HEADER_DATE, "Tue, 27 Mar 2007 19:36:42 +0000"); helper.formatRawResponse(cw, challenge, request, httpHeaders); assertEquals("0PN5J17HBGZHT7JJ3X82:xXjDGYUmKxnwqr5KXNPGldn5LbA=", cw.toString()); // Example Object PUT cw = new ChallengeWriter(); request.setMethod(Method.PUT); httpHeaders.set(HeaderConstants.HEADER_DATE, "Tue, 27 Mar 2007 21:15:45 +0000", true); httpHeaders.add(HeaderConstants.HEADER_CONTENT_LENGTH, "94328"); httpHeaders.add(HeaderConstants.HEADER_CONTENT_TYPE, "image/jpeg"); helper.formatRawResponse(cw, challenge, request, httpHeaders); assertEquals("0PN5J17HBGZHT7JJ3X82:hcicpDDvL9SsO6AkvxqmIWkmOuQ=", cw.toString()); } /** * Tests the authentication parsing for HTTP BASIC. * * @throws IOException */ public void testParsingBasic() throws IOException { String authenticate1 = "Basic realm=\"Restlet tutorial\""; String authorization1 = "Basic c2NvdHQ6dGlnZXI="; assertEquals(authorization1, AuthenticatorUtils.formatResponse( AuthenticatorUtils.parseResponse(null, authorization1, null), null, null)); List creq = AuthenticatorUtils.parseRequest(null, authenticate1, null); assertEquals(creq.size(), 1); assertEquals(authenticate1, AuthenticatorUtils.formatRequest(creq.get(0), null, null)); } /** * Tests the authentication parsing for HTTP DIGEST. * * @throws IOException */ public void testParsingDigest() throws IOException { ChallengeResponse cres1 = new ChallengeResponse( ChallengeScheme.HTTP_DIGEST, "admin", "12345".toCharArray()); cres1.setDigestAlgorithm(Digest.ALGORITHM_NONE); cres1.setQuality("qop"); cres1.setDigestRef(new Reference("/protected/asdass")); cres1.setClientNonce("MTE3NzEwMzIwMjkwMDoxNmMzODFiYzRjNWRjMmMyOTVkMWFhNDdkMTQ4OGFlMw=="); cres1.setServerNonce("MTE3NzEwMzIwMjkwMDoxNmMzODFiYzRjNWRjMmMyOTVkMWFhNDdkMTQ4OGFlMw=="); cres1.setServerNounceCount(1); Request request = new Request(Method.GET, "http://remote.com/protected/asdass"); String authorization1 = AuthenticatorUtils.formatResponse(cres1, request, null); String authenticate1 = "Digest realm=realm, domain=\"/protected/ /alsoProtected/\", qop=auth, algorithm=MD5, nonce=\"MTE3NzEwMzIwMjg0Mjo2NzFjODQyMjAyOWRlNWQ1YjFjNmEzYzJmOWRlZmE2Mw==\""; ChallengeResponse cres = AuthenticatorUtils.parseResponse(null, authorization1, null); cres.setRawValue(null); assertEquals(authorization1, AuthenticatorUtils.formatResponse(cres, request, null)); List creq = AuthenticatorUtils.parseRequest(null, authenticate1, null); assertEquals(creq.size(), 1); assertEquals(authenticate1, AuthenticatorUtils.formatRequest(creq.get(0), null, null)); } /** * Tests the authentication parsing for HTTP DIGEST. * * @throws IOException */ public void testParsingMultiValuedAuthenticate() throws IOException { String authenticate0 = "Basic realm=\"Restlet tutorial\""; String authenticate1 = "Digest realm=realm, domain=\"/protected/ /alsoProtected/\", qop=auth, algorithm=MD5, nonce=\"MTE3NzEwMzIwMjg0Mjo2NzFjODQyMjAyOWRlNWQ1YjFjNmEzYzJmOWRlZmE2Mw==\""; String authenticate = authenticate0 + "," + authenticate1; List creq = AuthenticatorUtils.parseRequest(null, authenticate, null); assertEquals(creq.size(), 2); assertEquals(authenticate0, AuthenticatorUtils.formatRequest(creq.get(0), null, null)); assertEquals(authenticate1, AuthenticatorUtils.formatRequest(creq.get(1), null, null)); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/SslBaseConnectorsTestCase.java0000664000175000017500000002067011757206352032354 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; 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.Server; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.engine.ClientHelper; import org.restlet.engine.Engine; import org.restlet.engine.ServerHelper; import org.restlet.engine.io.BioUtils; import org.restlet.engine.local.ClapClientHelper; import org.restlet.test.RestletTestCase; import org.restlet.util.Series; /** * Base test case that will call an abstract method for several client/server * connectors configurations. (Modified for SSL support.) * * @author Kevin Conaway * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) */ public abstract class SslBaseConnectorsTestCase extends RestletTestCase { private Component component; private final boolean enableApacheClient = true; private final boolean enableGrizzlyServer = true; private final boolean enableNettyServer = true; private final boolean enableJdkNetClient = true; private final boolean enableJettyServer = true; private final boolean enableSimpleServer = true; private final File testDir = new File(System.getProperty("java.io.tmpdir"), "SslBaseConnectorsTestCase"); protected final File testKeystoreFile = new File(testDir, "dummy.jks"); protected abstract void call(String uri) throws Exception; protected void configureSslServerParameters(Context context) { Series parameters = context.getParameters(); parameters.add("keystorePath", testKeystoreFile.getPath()); parameters.add("keystorePassword", "testtest"); parameters.add("keyPassword", "testtest"); parameters.add("truststorePath", testKeystoreFile.getPath()); parameters.add("truststorePassword", "testtest"); } protected void configureSslClientParameters(Context context) { Series parameters = context.getParameters(); parameters.add("truststorePath", testKeystoreFile.getPath()); parameters.add("truststorePassword", "testtest"); } protected abstract Application createApplication(Component component); // Helper methods private void runTest(ServerHelper server, ClientHelper client) throws Exception { final Engine nre = new Engine(false); nre.getRegisteredClients().add(new ClapClientHelper(null)); nre.getRegisteredServers().add(server); nre.getRegisteredClients().add(client); org.restlet.engine.Engine.setInstance(nre); final String uri = start(); try { call(uri); } finally { stop(); } } @Override public void setUp() { // Restore a clean engine org.restlet.engine.Engine.setInstance(new Engine()); try { if (!testKeystoreFile.exists()) { // Prepare a temporary directory for the tests BioUtils.delete(this.testDir, true); this.testDir.mkdir(); // Copy the keystore into the test directory Response response = new Client(Protocol.CLAP) .handle(new Request(Method.GET, "clap://class/org/restlet/test/engine/dummy.jks")); if (response.getEntity() != null) { OutputStream outputStream = new FileOutputStream( testKeystoreFile); response.getEntity().write(outputStream); outputStream.flush(); outputStream.close(); } else { throw new Exception( "Unable to find the dummy.jks file in the classpath."); } } } catch (Exception e) { e.printStackTrace(); } } private String start() throws Exception { this.component = new Component(); final Server server = this.component.getServers() .add(Protocol.HTTPS, 0); configureSslServerParameters(server.getContext()); final Application application = createApplication(this.component); this.component.getDefaultHost().attach(application); this.component.start(); return "https://localhost:" + server.getEphemeralPort() + "/test"; } private void stop() throws Exception { if ((this.component != null) && this.component.isStarted()) { this.component.stop(); } this.component = null; } @Override protected void tearDown() throws Exception { super.tearDown(); BioUtils.delete(this.testKeystoreFile); BioUtils.delete(this.testDir, true); // Restore a clean engine org.restlet.engine.Engine.setInstance(new Engine()); } public void testSslGrizzlyAndApache() throws Exception { if (this.enableGrizzlyServer && this.enableApacheClient) { runTest(new org.restlet.ext.grizzly.HttpsServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testSslGrizzlyAndJdkNet() throws Exception { if (this.enableGrizzlyServer && this.enableJdkNetClient) { runTest(new org.restlet.ext.grizzly.HttpsServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } public void testSslNettyAndApache() throws Exception { if (this.enableNettyServer && this.enableApacheClient) { runTest(new org.restlet.ext.netty.HttpsServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testSslNettyAndJdkNet() throws Exception { if (this.enableNettyServer && this.enableJdkNetClient) { runTest(new org.restlet.ext.netty.HttpsServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } public void testSslJettyAndApache() throws Exception { if (this.enableJettyServer && this.enableApacheClient) { runTest(new org.restlet.ext.jetty.HttpsServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testSslJettyAndJdkNet() throws Exception { if (this.enableJettyServer && this.enableJdkNetClient) { runTest(new org.restlet.ext.jetty.HttpsServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } public void testSslSimpleAndApache() throws Exception { if (this.enableSimpleServer && this.enableApacheClient) { runTest(new org.restlet.ext.simple.HttpsServerHelper(null), new org.restlet.ext.httpclient.HttpClientHelper(null)); } } public void testSslSimpleAndJdkNet() throws Exception { if (this.enableSimpleServer && this.enableJdkNetClient) { runTest(new org.restlet.ext.simple.HttpsServerHelper(null), new org.restlet.ext.net.HttpClientHelper(null)); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/JavaMailTestCase.java0000664000175000017500000002011011757206352030433 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.File; import java.io.IOException; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.ext.xml.DomRepresentation; import org.restlet.test.RestletTestCase; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Unit test for the JavaMail connector. * * @author Jerome Louvel */ public class JavaMailTestCase extends RestletTestCase { private static final String _TRUSTSTORE = "d:/temp/certificats/myClientKeystore"; private static final String DEBUG = "false"; private static final String GMAIL_ID = "XXX"; private static final String GMAIL_LOGIN = GMAIL_ID + "@gmail.com"; private static final String GMAIL_PASSWORD = "XXX"; private static final String GMAIL_SMTPS = "smtps://smtp.gmail.com"; private static final String MAIL = "" + "" + "" + "Test message" + "restlet.testfr@yahoo.fr" + "restlet.testfr@yahoo.fr" + "restlet.testfr@yahoo.fr" + "" + "" + ""; private static final String MAIL_LOGIN = "XXX"; private static final String MAIL_PASSWORD = "XXX"; private static final String MAIL_POPS = "pops://alaska.restlet.com"; private static final String MAIL_SMTP = "smtp://alaska.restlet.com"; private static final String YAHOO_ID = "XXX"; private static final String YAHOO_PASSWORD = "XXX"; private static final String YAHOO_POP = "pop://pop.mail.yahoo.fr"; private static final String YAHOO_SMTP = "smtp://smtp.mail.yahoo.com"; private void printMail(Client client, String baseUri, String href) throws IOException { final Request request = new Request(Method.GET, baseUri + href); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.POP_BASIC, MAIL_LOGIN, MAIL_PASSWORD)); final Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response.getEntity().write(System.out); System.out.println(); } private void sendMail(Protocol protocol, Request request, boolean startTls) throws Exception { final Client client = new Client(protocol); client.getContext().getParameters().add("debug", DEBUG); client.getContext().getParameters().add("startTls", Boolean.toString(startTls).toLowerCase()); request.setEntity(MAIL, MediaType.APPLICATION_XML); final Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); client.stop(); } @Override protected void setUp() throws Exception { super.setUp(); final File keyStoreFile = new File(_TRUSTSTORE); if (keyStoreFile.exists()) { System.setProperty("javax.net.ssl.trustStore", keyStoreFile .getCanonicalPath()); } } public void testPop() throws Exception { final Client client = new Client(Protocol.POP); client.getContext().getParameters().add("debug", DEBUG); Request request = new Request(Method.GET, YAHOO_POP); final ChallengeResponse challengeResponse = new ChallengeResponse( ChallengeScheme.POP_BASIC, YAHOO_ID, YAHOO_PASSWORD); request.setChallengeResponse(challengeResponse); Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); // Send a new mail. testSmtp(); // Try to get then delete the first message, if it exists. if (response.isEntityAvailable()) { final DomRepresentation representation = new DomRepresentation( response.getEntity()); final NodeList nodes = representation.getNodes("/emails/email"); if (nodes.getLength() > 0) { final Node node = representation .getNode("/emails/email[1]/@href"); final String mailUrl = YAHOO_POP + node.getNodeValue(); request = new Request(Method.GET, mailUrl); request.setChallengeResponse(challengeResponse); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); request = new Request(Method.DELETE, mailUrl); request.setChallengeResponse(challengeResponse); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); } } client.stop(); } public void testPops() throws Exception { final Client client = new Client(Protocol.POPS); client.getContext().getParameters().add("debug", DEBUG); final String baseUri = MAIL_POPS; final Request request = new Request(Method.GET, baseUri); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.POP_BASIC, MAIL_LOGIN, MAIL_PASSWORD)); final Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response.getEntity().write(System.out); System.out.println(); final DomRepresentation dom = new DomRepresentation(response .getEntity()); for (final Node node : dom.getNodes("/emails/email")) { final NamedNodeMap attrs = node.getAttributes(); final String href = attrs.getNamedItem("href").getNodeValue(); printMail(client, baseUri, href); } client.stop(); } public void testSmtp() throws Exception { final Request request = new Request(Method.POST, YAHOO_SMTP); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.SMTP_PLAIN, YAHOO_ID, YAHOO_PASSWORD)); sendMail(Protocol.SMTP, request, false); } public void testSmtps() throws Exception { final Request request = new Request(Method.POST, GMAIL_SMTPS); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.SMTP_PLAIN, GMAIL_LOGIN, GMAIL_PASSWORD)); sendMail(Protocol.SMTPS, request, false); } public void testSmtpStartTls() throws Exception { final Request request = new Request(Method.POST, MAIL_SMTP); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.SMTP_PLAIN, MAIL_LOGIN, MAIL_PASSWORD)); sendMail(Protocol.SMTP, request, true); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/ContentTypeTestCase.java0000664000175000017500000000457611757206352031245 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.engine.http.header.ContentType; import org.restlet.test.RestletTestCase; /** * Test {@link ContentType} * * @author Jerome Louvel */ public class ContentTypeTestCase extends RestletTestCase { public void testParsingInvalid() { String h1 = "application/docbook+xml; version='my version 1.0'"; try { new ContentType(h1); fail("Shouldn't reach this point"); } catch (IllegalArgumentException iae) { // OK } } public void testParsing() { String h1 = "application/docbook+xml; version=\"my version 1.0\""; String h2 = "application/docbook+xml; version='my%20version%201.0'"; ContentType ct1 = new ContentType(h1); ContentType ct2 = new ContentType(h2); assertEquals(h1, ct1.getMediaType().getName()); assertEquals("my version 1.0", ct1.getMediaType().getParameters() .getFirstValue("version")); assertEquals(h2, ct2.getMediaType().getName()); assertEquals("'my%20version%201.0'", ct2.getMediaType().getParameters() .getFirstValue("version")); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/ImmutableDateTestCase.java0000664000175000017500000000453011757206352031474 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.restlet.engine.util.DateUtils; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.engine.util.DateUtils}. * * @author Thierry Boileau */ public class ImmutableDateTestCase extends RestletTestCase { public void test() { Date now = new Date(); Calendar yesterdayCal = new GregorianCalendar(); yesterdayCal.add(Calendar.DAY_OF_MONTH, -1); Date yesterday = yesterdayCal.getTime(); assertTrue(now.after(yesterday)); assertTrue(now.after(DateUtils.unmodifiable(yesterday))); assertTrue(DateUtils.unmodifiable(now).after(yesterday)); assertTrue(DateUtils.unmodifiable(now).after( DateUtils.unmodifiable(yesterday))); assertTrue(yesterday.before(now)); assertTrue(yesterday.before(DateUtils.unmodifiable(now))); assertTrue(DateUtils.unmodifiable(yesterday).before( DateUtils.unmodifiable(now))); assertTrue(DateUtils.unmodifiable(yesterday).before(now)); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/DateTestCase.java0000664000175000017500000001136311757206352027636 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.util.Date; import org.restlet.engine.util.DateUtils; import org.restlet.test.RestletTestCase; /** * Test {@link DateUtils} * * @author Jerome Louvel */ public class DateTestCase extends RestletTestCase { private String DATE_RFC3339_1 = "1985-04-12T23:20:50.52Z"; private String DATE_RFC3339_2 = "1996-12-19T16:39:57-08:00"; private String DATE_RFC3339_3 = "1990-12-31T23:59:60Z"; private String DATE_RFC3339_4 = "1990-12-31T15:59:60-08:00"; private String DATE_RFC3339_5 = "1937-01-01T12:00:27.87+00:20"; private String DATE_ASC_1 = "Fri Apr 12 23:20:50 1985"; private String DATE_RFC1036_1 = "Friday, 12-Apr-85 23:20:50 GMT"; private String DATE_RFC1123_1 = "Fri, 12 Apr 1985 23:20:50 GMT"; private String DATE_RFC822_1 = "Fri, 12 Apr 85 23:20:50 GMT"; /** * Tests for dates in the RFC 822 format. */ public void testRfc822() throws Exception { Date date1 = DateUtils.parse(DATE_RFC822_1, DateUtils.FORMAT_RFC_822); String dateFormat1 = DateUtils.format(date1, DateUtils.FORMAT_RFC_822 .get(0)); assertEquals(DATE_RFC822_1, dateFormat1); } /** * Tests for dates in the RFC 1123 format. */ public void testRfc1123() throws Exception { Date date1 = DateUtils.parse(DATE_RFC1123_1, DateUtils.FORMAT_RFC_1123); String dateFormat1 = DateUtils.format(date1, DateUtils.FORMAT_RFC_1123 .get(0)); assertEquals(DATE_RFC1123_1, dateFormat1); } /** * Tests for dates in the RFC 1036 format. */ public void testRfc1036() throws Exception { Date date1 = DateUtils.parse(DATE_RFC1036_1, DateUtils.FORMAT_RFC_1036); String dateFormat1 = DateUtils.format(date1, DateUtils.FORMAT_RFC_1036 .get(0)); assertEquals(DATE_RFC1036_1, dateFormat1); } /** * Tests for dates in the RFC 3339 format. */ public void testAsc() throws Exception { Date date1 = DateUtils.parse(DATE_ASC_1, DateUtils.FORMAT_ASC_TIME); String dateFormat1 = DateUtils.format(date1, DateUtils.FORMAT_ASC_TIME .get(0)); assertEquals(DATE_ASC_1, dateFormat1); } /** * Tests for dates in the RFC 3339 format. */ public void testRfc3339() throws Exception { Date date1 = DateUtils.parse(DATE_RFC3339_1, DateUtils.FORMAT_RFC_3339); Date date2 = DateUtils.parse(DATE_RFC3339_2, DateUtils.FORMAT_RFC_3339); Date date3 = DateUtils.parse(DATE_RFC3339_3, DateUtils.FORMAT_RFC_3339); Date date4 = DateUtils.parse(DATE_RFC3339_4, DateUtils.FORMAT_RFC_3339); Date date5 = DateUtils.parse(DATE_RFC3339_5, DateUtils.FORMAT_RFC_3339); String dateFormat1 = DateUtils.format(date1, DateUtils.FORMAT_RFC_3339 .get(0)); String dateFormat2 = DateUtils.format(date2, DateUtils.FORMAT_RFC_3339 .get(0)); String dateFormat3 = DateUtils.format(date3, DateUtils.FORMAT_RFC_3339 .get(0)); String dateFormat4 = DateUtils.format(date4, DateUtils.FORMAT_RFC_3339 .get(0)); String dateFormat5 = DateUtils.format(date5, DateUtils.FORMAT_RFC_3339 .get(0)); assertEquals(DATE_RFC3339_1, dateFormat1); assertEquals("1996-12-20T00:39:57Z", dateFormat2); assertEquals("1991-01-01T00:00:00Z", dateFormat3); assertEquals("1991-01-01T00:00:00Z", dateFormat4); assertEquals("1937-01-01T11:40:27.87Z", dateFormat5); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/UnclosableInputStreamTestCase.java0000664000175000017500000000421211757206352033237 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import java.io.InputStream; import org.restlet.engine.http.io.UnclosableInputStream; import org.restlet.test.RestletTestCase; /** * Unit tests for the HTTP KeepAlive. * * @author Kevin Conaway */ public class UnclosableInputStreamTestCase extends RestletTestCase { static class MockInputStream extends InputStream { boolean closed = false; @Override public void close() throws IOException { this.closed = true; } @Override public int read() throws IOException { return -1; } } public void testClose() throws IOException { final MockInputStream mock = new MockInputStream(); final InputStream keepalive = new UnclosableInputStream(mock); keepalive.close(); assertFalse(mock.closed); mock.close(); assertTrue(mock.closed); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/PostPutTestCase.java0000664000175000017500000000662511757206352030404 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.representation.Representation; /** * Unit tests for POST and PUT requests. * * @author Jerome Louvel */ public class PostPutTestCase extends BaseConnectorsTestCase { @Override protected void call(String uri) throws Exception { Client client = new Client(Protocol.HTTP); testCall(client, Method.POST, uri); testCall(client, Method.PUT, uri); client.stop(); } @Override protected Application createApplication(final Component component) { Application application = new Application() { @Override public Restlet createInboundRoot() { final Restlet trace = new Restlet(getContext()) { @Override public void handle(Request request, Response response) { Representation entity = request.getEntity(); if (entity != null) { Form form = new Form(entity); response.setEntity(form.getWebRepresentation()); } } }; return trace; } }; return application; } private void testCall(Client client, Method method, String uri) throws Exception { Form inputForm = new Form(); inputForm.add("a", "a"); inputForm.add("b", "b"); Request request = new Request(method, uri); request.setEntity(inputForm.getWebRepresentation()); Response response = client.handle(request); assertNotNull(response.getEntity()); Representation entity = response.getEntity(); Form outputForm = new Form(entity); assertEquals(2, outputForm.size()); assertEquals("a", outputForm.getFirstValue("a")); assertEquals("b", outputForm.getFirstValue("b")); entity.release(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/ChunkedOutputStreamTestCase.java0000664000175000017500000001023011757206352032727 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.restlet.engine.http.io.ChunkedOutputStream; import org.restlet.test.RestletTestCase; /** * Test cases for the chunked encoding. * * @author
Kevin Conaway */ public class ChunkedOutputStreamTestCase extends RestletTestCase { public void testCallCloseTwice() throws IOException { final String data = "test data"; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream chunked = new ChunkedOutputStream(out); chunked.write(data.getBytes()); chunked.close(); chunked.close(); final String result = new String(out.toByteArray()); assertEquals("9\r\ntest data\r\n0\r\n\r\n", result); } public void testCallFlushAndClose() throws IOException { final String data = "test data"; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream chunked = new ChunkedOutputStream(out); chunked.write(data.getBytes()); chunked.flush(); chunked.close(); final String result = new String(out.toByteArray()); assertEquals("9\r\ntest data\r\n0\r\n\r\n", result); } public void testEmptyWrite() throws IOException { final String data = ""; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream chunked = new ChunkedOutputStream(out); chunked.write(data.getBytes()); chunked.close(); final String result = new String(out.toByteArray()); assertEquals("0\r\n\r\n", result); } public void testNoWrite() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream chunked = new ChunkedOutputStream(out); chunked.close(); final String result = new String(out.toByteArray()); assertEquals("0\r\n\r\n", result); } public void testWrite() throws IOException { final String data = "test data"; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream chunked = new ChunkedOutputStream(out); chunked.write(data.getBytes()); chunked.close(); final String result = new String(out.toByteArray()); assertEquals("9\r\ntest data\r\n0\r\n\r\n", result); } public void testWriteSmallBuffer() throws IOException { final String data = "test data"; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream chunked = new ChunkedOutputStream(out, 2); chunked.write(data.getBytes()); chunked.close(); final String result = new String(out.toByteArray()); assertEquals( "2\r\nte\r\n2\r\nst\r\n2\r\n d\r\n2\r\nat\r\n1\r\na\r\n0\r\n\r\n", result); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/UnclosableOutputStreamTestCase.java0000664000175000017500000000526011757206352033444 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.restlet.engine.http.io.UnclosableOutputStream; import org.restlet.test.RestletTestCase; /** * Unit tests for the HTTP KeepAlive. * * @author Kevin Conaway */ public class UnclosableOutputStreamTestCase extends RestletTestCase { static class MockOutputStream extends OutputStream { boolean closed = false; @Override public void close() throws IOException { this.closed = true; } @Override public void write(int b) throws IOException { } } public void testClose() throws IOException { final MockOutputStream stream = new MockOutputStream(); final OutputStream out = new UnclosableOutputStream(stream); out.close(); assertFalse(stream.closed); stream.close(); assertTrue(stream.closed); } public void testWrite() throws IOException { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final OutputStream out = new UnclosableOutputStream(stream); out.write('a'); assertEquals("a", new String(stream.toByteArray())); out.write(new byte[] { 'b', 'c' }); assertEquals("abc", new String(stream.toByteArray())); out.write(new byte[] { 'd', 'e', 'f', 'g' }, 0, 2); assertEquals("abcde", new String(stream.toByteArray())); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/UserAgentTunnelFilterTestCase.java0000664000175000017500000000712311757206352033211 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Status; import org.restlet.routing.Router; import org.restlet.test.RestletTestCase; /** * Tests cases for the tunneling of preferences based on user agent. */ public class UserAgentTunnelFilterTestCase extends RestletTestCase { /** . */ private static final String URL = "http://localhost:" + TEST_PORT + "/test"; private Application application; /** * Creates a new Request object. * * @return A new Request object. */ private Request createRequest() { final Request request = new Request(); request.setMethod(Method.GET); request.getClientInfo().setAgent("msie/1.1"); request.setResourceRef(URL); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_XML)); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); return request; } @Override public void setUp() throws Exception { super.setUp(); this.application = new Application() { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attachDefault(UserAgentTestResource.class); return router; } }; } public void testTunnelOff() { this.application.getTunnelService().setUserAgentTunnel(false); Request request = createRequest(); Response response = new Response(request); this.application.handle(request, response); assertEquals(response.getStatus(), Status.SUCCESS_OK); assertEquals(MediaType.TEXT_XML, response.getEntity().getMediaType()); } public void testTunnelOn() { this.application.getTunnelService().setUserAgentTunnel(true); Request request = createRequest(); Response response = new Response(request); this.application.handle(request, response); assertEquals(response.getStatus(), Status.SUCCESS_OK); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/AnnotationUtilsTestCase.java0000664000175000017500000000640511757206352032115 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.util.List; import junit.framework.Assert; import org.restlet.data.Method; import org.restlet.engine.resource.AnnotationInfo; import org.restlet.engine.resource.AnnotationUtils; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.test.RestletTestCase; /** * Test case for generic interfaces. * * @author Valdis Rigdon */ public class AnnotationUtilsTestCase extends RestletTestCase { public static interface IChild extends IParent { } public static interface IParent { @Get T getType(); @Put void update(T generic); } public void testGetAnnotationsWithGenericParameterType() { List infos = AnnotationUtils .getAnnotations(IChild.class); Assert.assertEquals("Wrong count: " + infos, 4, infos.size()); boolean found = false; for (AnnotationInfo ai : infos) { if (ai.getResourceClass().equals(IChild.class) && ai.getRestletMethod().equals(Method.PUT)) { found = true; Assert.assertEquals(String.class, ai.getJavaInputTypes()[0]); } } Assert.assertEquals( "Didn't find a method with IChild as the declaring class.", true, found); } public void testGetAnnotationsWithGenericReturnType() { List infos = AnnotationUtils .getAnnotations(IChild.class); Assert.assertEquals("Wrong count: " + infos, 4, infos.size()); boolean found = false; for (AnnotationInfo ai : infos) { if (ai.getResourceClass().equals(IChild.class) && ai.getRestletMethod().equals(Method.GET)) { found = true; Assert.assertEquals(String.class, ai.getJavaOutputType()); } } Assert.assertEquals( "Didn't find a method with IChild as the declaring class.", true, found); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/ChunkedEncodingTestCase.java0000664000175000017500000002136111757206352032010 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Message; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This tests the ability of the connectors to handle chunked encoding. * * The test uses each connector to PUT an entity that will be sent chunked and * also to receive a chunked response. */ public class ChunkedEncodingTestCase extends BaseConnectorsTestCase { public static class PutTestResource extends ServerResource { public PutTestResource() { getVariants().add(new Variant(MediaType.TEXT_XML)); setNegotiated(false); } @Override public Representation get() { return createTestXml(); } @Override public Representation put(Representation entity) { checkForChunkedHeader(getRequest()); final DomRepresentation dom = new DomRepresentation(entity); DomRepresentation rep = null; try { final Document doc = dom.getDocument(); assertXML(dom); rep = new DomRepresentation(MediaType.TEXT_XML, doc); getResponse().setEntity(rep); } catch (IOException ex) { ex.printStackTrace(); fail(ex.getMessage()); } return rep; } } private static int LOOP_NUMBER = 50; static void assertXML(DomRepresentation entity) { try { final Document document = entity.getDocument(); final Node root = document.getDocumentElement(); final NodeList children = root.getChildNodes(); assertEquals("root", root.getNodeName()); assertEquals(2, children.getLength()); assertEquals("child-0", children.item(0).getNodeName()); assertEquals("name-0", children.item(0).getAttributes() .getNamedItem("name").getNodeValue()); assertEquals("child-1", children.item(1).getNodeName()); assertEquals("name-1", children.item(1).getAttributes() .getNamedItem("name").getNodeValue()); } catch (IOException ex) { fail(ex.getMessage()); } finally { entity.release(); } } static void checkForChunkedHeader(Message message) { final Form parameters = (Form) message.getAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); final Parameter p = parameters .getFirst(HeaderConstants.HEADER_TRANSFER_ENCODING); assertFalse(p == null); assertEquals("chunked", p.getValue()); } private static Document createDocument() { try { return DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } } private static Representation createTestXml() { final Document doc = createDocument(); final Element root = doc.createElement("root"); doc.appendChild(root); for (int i = 0; i < 2; i++) { final Element e = doc.createElement("child-" + i); e.setAttribute("name", "name-" + i); root.appendChild(e); } Representation rep = null; try { rep = new StringRepresentation(new DomRepresentation( MediaType.TEXT_XML, doc).getText()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } rep.setSize(-1); return rep; } boolean checkedForChunkedResponse; @Override protected void call(String uri) throws Exception { for (int i = 0; i < LOOP_NUMBER; i++) { sendGet(uri); sendPut(uri); } } @Override protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", PutTestResource.class); return router; } }; return application; } private void sendGet(String uri) throws Exception { final Request request = new Request(Method.GET, uri); Client c = new Client(Protocol.HTTP); final Response r = c.handle(request); try { assertEquals(r.getStatus().getDescription(), Status.SUCCESS_OK, r .getStatus()); assertXML(new DomRepresentation(r.getEntity())); } finally { r.release(); c.stop(); } } private void sendPut(String uri) throws Exception { final Request request = new Request(Method.PUT, uri, createTestXml()); Client c = new Client(Protocol.HTTP); final Response r = c.handle(request); try { if (this.checkedForChunkedResponse) { checkForChunkedHeader(r); } assertEquals(r.getStatus().getDescription(), Status.SUCCESS_OK, r .getStatus()); assertXML(new DomRepresentation(r.getEntity())); } finally { r.release(); c.stop(); } } @Override public void setUp() { this.checkedForChunkedResponse = true; } @Override public void testJettyAndApache() throws Exception { super.testJettyAndApache(); } @Override public void testJettyAndDefault() throws Exception { // Jetty will not send a chunked response when a client sends // Connection: close, which the default client helper does this.checkedForChunkedResponse = false; super.testJettyAndDefault(); } @Override public void testNettyAndApache() throws Exception { this.checkedForChunkedResponse = false; super.testNettyAndApache(); } @Override public void testNettyAndDefault() throws Exception { this.checkedForChunkedResponse = false; super.testNettyAndDefault(); } @Override public void testNettyAndJdkNet() throws Exception { this.checkedForChunkedResponse = false; super.testNettyAndJdkNet(); } @Override public void testSimpleAndDefault() throws Exception { // Simple will not send a chunked response when a client sends // Connection: close, which the default client helper does this.checkedForChunkedResponse = false; super.testSimpleAndDefault(); } @Override public void testSimpleAndJdkNet() throws Exception { super.testSimpleAndJdkNet(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/GetTestCase.java0000664000175000017500000000541111757206352027475 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * Test that a simple get works for all the connectors. * * @author Kevin Conaway */ public class GetTestCase extends BaseConnectorsTestCase { public static class GetTestResource extends ServerResource { @Get public String toString() { return "Hello world"; } } @Override protected void call(String uri) throws Exception { final Request request = new Request(Method.GET, uri); Client c = new Client(Protocol.HTTP); final Response r = c.handle(request); assertEquals(r.getStatus().getDescription(), Status.SUCCESS_OK, r .getStatus()); assertEquals("Hello world", r.getEntity().getText()); c.stop(); } @Override protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", GetTestResource.class); return router; } }; return application; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/SslGetTestCase.java0000664000175000017500000000652711757206352030170 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; 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.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * Test that a simple get using SSL works for all the connectors. * * @author Kevin Conaway * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) */ public class SslGetTestCase extends SslBaseConnectorsTestCase { public static class GetTestResource extends ServerResource { public GetTestResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); } @Override public Representation get(Variant variant) { return new StringRepresentation("Hello world", MediaType.TEXT_PLAIN); } } @Override protected void call(String uri) throws Exception { final Request request = new Request(Method.GET, uri); final Client client = new Client(Protocol.HTTPS); client.setContext(new Context()); configureSslClientParameters(client.getContext()); final Response r = client.handle(request); assertEquals(r.getStatus().getDescription(), Status.SUCCESS_OK, r .getStatus()); assertEquals("Hello world", r.getEntity().getText()); Thread.sleep(200); client.stop(); } @Override protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", GetTestResource.class); return router; } }; return application; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/RemoteClientAddressTestCase.java0000664000175000017500000000633511757206352032664 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import org.junit.Assert; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * Test that the client address is available for all the connectors * * @author Kevin Conaway */ public class RemoteClientAddressTestCase extends BaseConnectorsTestCase { public static class RemoteClientAddressResource extends ServerResource { public RemoteClientAddressResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); } @Override public Representation get(Variant variant) { Assert.assertEquals("127.0.0.1", getRequest().getClientInfo() .getAddress()); Assert.assertTrue(getRequest().getClientInfo().getPort() > 0); return new StringRepresentation("OK"); } } @Override protected void call(String uri) throws Exception { final Request request = new Request(Method.GET, uri); Client c = new Client(Protocol.HTTP); final Response r = c.handle(request); assertEquals(Status.SUCCESS_OK, r.getStatus()); c.stop(); } @Override protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", RemoteClientAddressResource.class); return router; } }; return application; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/engine/ByteUtilsTestCase.java0000664000175000017500000000353711757206352030711 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.engine; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import org.restlet.engine.io.BioUtils; import org.restlet.test.RestletTestCase; /** * Test case for the ByteUtils class. * * @author Kevin Conaway */ public class ByteUtilsTestCase extends RestletTestCase { public void testGetStream() throws IOException { final StringWriter writer = new StringWriter(); final OutputStream out = BioUtils.getStream(writer); out.write("test".getBytes()); out.flush(); out.close(); assertEquals("test", writer.toString()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/routing/0000775000175000017500000000000011757206354024702 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/routing/RedirectTestCase.java0000664000175000017500000001160511757206354030745 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.routing; import org.restlet.Component; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.representation.StringRepresentation; import org.restlet.routing.Redirector; import org.restlet.test.RestletTestCase; /** * Unit tests for the RedirectRestlet. * * @author Jerome Louvel */ public class RedirectTestCase extends RestletTestCase { private void testCall(Context context, Method method, String uri) throws Exception { final Response response = context.getClientDispatcher().handle( new Request(method, uri)); assertNotNull(response.getEntity()); response.getEntity().write(System.out); } /** * Tests the cookies parsing. */ public void testRedirect() throws Exception { // Create components final Component clientComponent = new Component(); final Component proxyComponent = new Component(); final Component originComponent = new Component(); // Create the client connectors clientComponent.getClients().add(Protocol.HTTP); proxyComponent.getClients().add(Protocol.HTTP); // Create the proxy Restlet final String target = "http://localhost:" + (TEST_PORT + 1) + "{rr}"; final Redirector proxy = new Redirector(proxyComponent.getContext() .createChildContext(), target, Redirector.MODE_SERVER_OUTBOUND); // Create a new Restlet that will display some path information. final Restlet trace = new Restlet(originComponent.getContext() .createChildContext()) { @Override public void handle(Request request, Response response) { // Print the requested URI path final String message = "Resource URI: " + request.getResourceRef() + '\n' + "Base URI: " + request.getResourceRef().getBaseRef() + '\n' + "Remaining part: " + request.getResourceRef().getRemainingPart() + '\n' + "Method name: " + request.getMethod() + '\n'; response.setEntity(new StringRepresentation(message, MediaType.TEXT_PLAIN)); } }; // Set the component roots proxyComponent.getDefaultHost().attach("", proxy); originComponent.getDefaultHost().attach("", trace); // Create the server connectors proxyComponent.getServers().add(Protocol.HTTP, TEST_PORT); originComponent.getServers().add(Protocol.HTTP, TEST_PORT + 1); // Now, let's start the components! originComponent.start(); proxyComponent.start(); clientComponent.start(); // Tests final Context context = clientComponent.getContext(); String uri = "http://localhost:" + TEST_PORT + "/?foo=bar"; testCall(context, Method.GET, uri); testCall(context, Method.DELETE, uri); uri = "http://localhost:" + TEST_PORT + "/abcd/efgh/ijkl?foo=bar&foo=beer"; testCall(context, Method.GET, uri); testCall(context, Method.DELETE, uri); uri = "http://localhost:" + TEST_PORT + "/v1/client/kwse/CnJlNUQV9%252BNNqbUf7Lhs2BYEK2Y%253D" + "/user/johnm/uVGYTDK4kK4zsu96VHGeTCzfwso%253D/"; testCall(context, Method.GET, uri); // Stop the components clientComponent.stop(); originComponent.stop(); proxyComponent.stop(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/routing/ValidatorTestCase.java0000664000175000017500000000632011757206352031125 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.routing; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.routing.Validator; import org.restlet.test.RestletTestCase; import org.restlet.test.TraceRestlet; /** * Test {@link org.restlet.routing.Validator}. * * @author Jerome Louvel */ public class ValidatorTestCase extends RestletTestCase { public void testRequired() { // Create mock call Request rq = new Request(); Response rs = new Response(rq); // Prepare the validator to test Validator validator = new Validator(); validator.setNext(new TraceRestlet(null)); validator.validatePresence("a"); validator.handle(rq, rs); // Test if the absence of "a" is detected assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, rs.getStatus()); // Test if the presence of "a" is ignored rq.getAttributes().put("a", "123"); rs.setStatus(Status.SUCCESS_OK); validator.handle(rq, rs); assertEquals(Status.SUCCESS_OK, rs.getStatus()); } public void testFormat() { // Create mock call Request rq = new Request(); Response rs = new Response(rq); // Prepare the validator to test Validator validator = new Validator(); validator.setNext(new TraceRestlet(null)); validator.validateFormat("a", "\\d*"); validator.handle(rq, rs); // Test if the absence of "a" is ignored assertEquals(Status.SUCCESS_OK, rs.getStatus()); // Test if a wrong format of "a" is detected rq.getAttributes().put("a", "abc"); rs.setStatus(Status.SUCCESS_OK); validator.handle(rq, rs); assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, rs.getStatus()); // Test if a correct format of "a" is ignored rq.getAttributes().put("a", "123"); rs.setStatus(Status.SUCCESS_OK); validator.handle(rq, rs); assertEquals(Status.SUCCESS_OK, rs.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/routing/RouteListTestCase.java0000664000175000017500000000704011757206352031132 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.routing; import org.restlet.Request; import org.restlet.Response; import org.restlet.routing.Route; import org.restlet.test.RestletTestCase; import org.restlet.util.RouteList; /** * Test case for RouteList class. * * @author Kevin Conaway */ @SuppressWarnings("deprecation") public class RouteListTestCase extends RestletTestCase { static class MockScoringRoute extends Route { int score; public MockScoringRoute(int score) { super(null); this.score = score; } @Override public float score(Request request, Response response) { return this.score; } } public void testGetLast() { final RouteList list = new RouteList(); assertNull(list.getLast(null, null, 1f)); final Route last = new MockScoringRoute(5); list.add(new MockScoringRoute(5)); list.add(new MockScoringRoute(5)); list.add(last); assertSame(last, list.getLast(null, null, 1f)); assertNull(list.getLast(null, null, 6f)); } public void testGetNext() { final RouteList list = new RouteList(); assertNull(list.getNext(null, null, 1f)); final Route first = new MockScoringRoute(5); final Route second = new MockScoringRoute(5); final Route third = new MockScoringRoute(5); list.add(first); list.add(second); list.add(third); assertSame(first, list.getNext(null, null, 1f)); assertSame(second, list.getNext(null, null, 1f)); assertSame(third, list.getNext(null, null, 1f)); assertSame(first, list.getNext(null, null, 1f)); } public void testGetRandom() { final RouteList list = new RouteList(); assertNull(list.getRandom(null, null, 1f)); list.add(new MockScoringRoute(2)); list.add(new MockScoringRoute(3)); list.add(new MockScoringRoute(4)); assertNull(list.getRandom(null, null, 9f)); list.add(new MockScoringRoute(6)); list.add(new MockScoringRoute(7)); list.add(new MockScoringRoute(8)); final MockScoringRoute r = (MockScoringRoute) list.getRandom(null, null, 5f); assertFalse(r == null); assertTrue(r.score > 5); assertNull(list.getRandom(null, null, 9f)); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/routing/FilterTestCase.java0000664000175000017500000000426411757206354030434 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.routing; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.routing.Filter; import org.restlet.test.AbstractFilterTestCase; import org.restlet.test.MockFilter; import org.restlet.test.MockRestlet; /** * Test {@link org.restlet.routing.Filter}. * * @author Lars Heuer (heuer[at]semagia.com) Semagia */ public class FilterTestCase extends AbstractFilterTestCase { @Override protected Filter getFilter() { return new MockFilter(null); } @Override protected Request getRequest() { return new Request(); } @Override protected Response getResponse(Request request) { return new Response(request); } @Override protected Restlet getRestlet() { return new MockRestlet(null); } @Override protected Class getRestletClass() { return MockRestlet.class; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/HeaderTestCase.java0000664000175000017500000001253611757206354026711 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.representation.StringRepresentation; public class HeaderTestCase extends RestletTestCase { /** * Restlet that returns as a new Representation the list of values of * "testHeader" header. * */ public static class TestHeaderRestlet extends Restlet { @Override public void handle(Request request, Response response) { final StringBuilder stb = new StringBuilder(); final Form headers = getHttpHeaders(request); for (final Parameter header : headers) { if (header.getName().equals(TEST_HEADER)) { stb.append(header.getValue()); stb.append('\n'); } } response.setEntity(new StringRepresentation(stb, MediaType.TEXT_PLAIN)); } } private static final String HTTP_HEADERS = "org.restlet.http.headers"; /** * Name of a test header field */ private static final String TEST_HEADER = "testHeader"; /** * Returns the list of http headers of a request as a Form. * * @param request * The request. * @return The list of headers as a Form object. */ private static Form getHttpHeaders(Request request) { Form headers = (Form) request.getAttributes().get(HTTP_HEADERS); if (headers == null) { headers = new Form(); request.getAttributes().put(HTTP_HEADERS, headers); } return headers; } private Component component; /** * Handle a new request built according to the parameters and return the * response object. * * @param parameters * The list of parameters used to build the request. * @return The response of the request. * @throws Exception */ private Response getWithParams(Parameter... parameters) throws Exception { final Client client = new Client(Protocol.HTTP); final Request request = new Request(Method.GET, "http://localhost:" + TEST_PORT); final Form headers = getHttpHeaders(request); for (final Parameter p : parameters) { headers.add(p); } Response result = client.handle(request); client.stop(); return result; } @Override public void setUp() throws Exception { super.setUp(); if (this.component == null) { this.component = new Component(); this.component.getServers().add(Protocol.HTTP, TEST_PORT); this.component.getDefaultHost().attachDefault( new TestHeaderRestlet()); } if (!this.component.isStarted()) { this.component.start(); } } @Override public void tearDown() throws Exception { this.component.stop(); this.component = null; super.tearDown(); } /** test with no test header */ public void test0() throws Exception { final Response response = getWithParams(); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals(null, response.getEntity().getText()); } /** test with one test header */ public void test1() throws Exception { final Response response = getWithParams(new Parameter(TEST_HEADER, "a")); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a\n", response.getEntity().getText()); } /** test with two test headers */ public void test2() throws Exception { final Response response = getWithParams( new Parameter(TEST_HEADER, "a"), new Parameter(TEST_HEADER, "b")); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("a\nb\n", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/representation/0000775000175000017500000000000011757206354026255 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/representation/AppendableRepresentationTestCase.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/representation/AppendableRepresentationTestCase0000664000175000017500000000340311757206354034612 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.representation; import org.restlet.representation.AppendableRepresentation; import org.restlet.test.RestletTestCase; /** * Unit test case for the {@link AppendableRepresentation} class. * * @author Jerome Louvel */ public class AppendableRepresentationTestCase extends RestletTestCase { public void testAppendable() throws Exception { AppendableRepresentation ar = new AppendableRepresentation(); ar.append("abcd"); ar.append("efgh"); assertEquals("abcdefgh", ar.getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/representation/RangeRepresentationTestCase.java0000664000175000017500000000406411757206354034537 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.representation; import org.restlet.data.Range; import org.restlet.engine.application.RangeRepresentation; import org.restlet.representation.StringRepresentation; import org.restlet.test.RestletTestCase; /** * Unit test case for the {@link RangeRepresentation} class. * * @author Jerome Louvel */ public class RangeRepresentationTestCase extends RestletTestCase { public void testAppendable() throws Exception { StringRepresentation sr = new StringRepresentation("1234567890"); RangeRepresentation rr = new RangeRepresentation(sr); rr.setRange(new Range(2, 5)); assertNull(sr.getRange()); assertEquals(10, sr.getAvailableSize()); assertEquals(5, rr.getAvailableSize()); assertEquals("1234567890", sr.getText()); assertEquals("34567", rr.getText()); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/representation/DigesterRepresentationTestCase.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/representation/DigesterRepresentationTestCase.j0000664000175000017500000001245711757206352034564 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.representation; import java.io.IOException; import java.security.NoSuchAlgorithmException; import org.junit.Test; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.representation.DigesterRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.engine.util.DateUtils}. * * @author Thierry Boileau */ public class DigesterRepresentationTestCase extends RestletTestCase { /** Component used for the tests. */ private Component component; /** * Internal class used for test purpose. * */ private static class TestDigestApplication extends Application { @Override public Restlet createInboundRoot() { Restlet restlet = new Restlet() { @Override public void handle(Request request, Response response) { Representation rep = request.getEntity(); try { // Such representation computes the digest while // consuming the wrapped representation. DigesterRepresentation digester = new DigesterRepresentation( rep); digester.exhaust(); if (digester.checkDigest()) { response.setStatus(Status.SUCCESS_OK); StringRepresentation f = new StringRepresentation( "9876543210"); digester = new DigesterRepresentation(f); // Consume first digester.exhaust(); // Set the digest digester.setDigest(digester.computeDigest()); response.setEntity(digester); } else { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } } catch (Exception e1) { } } }; return restlet; } } @Override protected void setUp() throws Exception { super.setUp(); component = new Component(); component.getServers().add(Protocol.HTTP, TEST_PORT); component.getDefaultHost().attach(new TestDigestApplication()); component.start(); } @Override protected void tearDown() throws Exception { component.stop(); component = null; super.tearDown(); } /** * Tests partial Get requests. * * @throws IOException * @throws NoSuchAlgorithmException */ @Test public void testGet() throws IOException, NoSuchAlgorithmException { Client client = new Client(Protocol.HTTP); // Test partial Get. Request request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/"); StringRepresentation rep = new StringRepresentation("0123456789"); try { DigesterRepresentation digester = new DigesterRepresentation(rep); // Such representation computes the digest while // consuming the wrapped representation. digester.exhaust(); // Set the digest with the computed one digester.setDigest(digester.computeDigest()); request.setEntity(digester); Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); digester = new DigesterRepresentation(response.getEntity()); digester.exhaust(); assertTrue(digester.checkDigest()); client.stop(); } catch (Exception e) { fail(e.getMessage()); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/RestletTestCase.java0000664000175000017500000000454511757206352027142 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import junit.framework.TestCase; import org.restlet.engine.Engine; /** * Marker class. All Restlet tests should be derived from this class. * * @author Lars Heuer (heuer[at]semagia.com) */ public abstract class RestletTestCase extends TestCase { public static final int DEFAULT_TEST_PORT = 1337; public static int TEST_PORT = getTestPort(); private static final String PROPERTY_TEST_PORT = "org.restlet.test.port"; private static int getTestPort() { if (System.getProperties().containsKey(PROPERTY_TEST_PORT)) { return Integer.parseInt(System.getProperty(PROPERTY_TEST_PORT)); } return DEFAULT_TEST_PORT; } @Override protected void setUp() throws Exception { super.setUp(); Engine.clearThreadLocalVariables(); System.out.println("Setting up test " + getClass().getName() + "#" + getName()); // Restore a clean engine org.restlet.engine.Engine.register(); } @Override protected void tearDown() throws Exception { super.tearDown(); Engine.clearThreadLocalVariables(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/xslt/0000775000175000017500000000000011757206354024205 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/xslt/one/0000775000175000017500000000000011757206354024766 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/xslt/one/1st.xsl0000664000175000017500000000126511757206354026231 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/xslt/one/1st.xml0000664000175000017500000000007411757206354026220 0ustar jamespagejamespage 1st restlet-2.0.14/org.restlet.test/src/org/restlet/test/xslt/two/0000775000175000017500000000000011757206354025016 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/xslt/two/2nd.xml0000664000175000017500000000007411757206354026224 0ustar jamespagejamespage 2nd restlet-2.0.14/org.restlet.test/src/org/restlet/test/xslt/two/2nd.xsl0000664000175000017500000000062411757206354026233 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/0000775000175000017500000000000011757206354025042 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource11TestCase.java0000664000175000017500000000722111757206352033130 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.resource.ResourceException; import org.restlet.routing.Router; import org.restlet.test.RestletTestCase; /** * Test annotated resource that reimplements of one the annotated method from * its abstract super class that implements several annotated interfaces. * * @author Thierry Boileau */ public class AnnotatedResource11TestCase extends RestletTestCase { private static class TestApplication extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/test", MyResource11.class); return router; } } private Component c; private Client client; protected void setUp() throws Exception { super.setUp(); Engine.getInstance().getRegisteredConverters().clear(); Engine.getInstance().registerDefaultConverters(); c = new Component(); c.getServers().add(Protocol.HTTP, 8111); c.getDefaultHost().attach(new TestApplication()); c.start(); client = new Client(Protocol.HTTP); } @Override protected void tearDown() throws Exception { c.stop(); c = null; client.stop(); client = null; super.tearDown(); } /** * Test annotated methods. * * @throws IOException * @throws ResourceException */ public void test() throws IOException, ResourceException { client = new Client(Protocol.HTTP); Request request = new Request(Method.GET, "http://localhost:8111/test"); Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("asText-txt", response.getEntity().getText()); response.getEntity().release(); request = new Request(Method.POST, "http://localhost:8111/test"); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("accept", response.getEntity().getText()); response.getEntity().release(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedInterface1.java0000664000175000017500000000272711757206352031532 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Get; /** * Annotated interface that declares a single "Get" method. * * @author Thierry Boileau * */ public interface AnnotatedInterface1 { @Get public String asText(); } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource8TestCase.java0000664000175000017500000000757711757206354033076 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource8TestCase extends RestletTestCase { private ClientResource clientResource; protected void setUp() throws Exception { super.setUp(); Finder finder = new Finder(); finder.setTargetClass(MyResource8.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); } @Override protected void tearDown() throws Exception { clientResource = null; super.tearDown(); } public void testGet() throws IOException, ResourceException { Representation input = new StringRepresentation("", MediaType.APPLICATION_XML); Representation result = clientResource.post(input, MediaType.APPLICATION_XML); assertNotNull(result); assertEquals("1", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); input = new StringRepresentation("", MediaType.APPLICATION_XML); result = clientResource.post(input, MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("2", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); input = new StringRepresentation("root=true", MediaType.APPLICATION_WWW_FORM); result = clientResource.post(input, MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("root=true3", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); Form inputForm = new Form(); inputForm.add("root", "true"); result = clientResource.post(inputForm, MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("root=true3", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); input = new StringRepresentation("[root]", MediaType.APPLICATION_JSON); result = clientResource.post(input, MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("[root]2", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource5.java0000664000175000017500000000310211757206352030061 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; public class MyResource5 extends ServerResource { @Post("txt:xml") public String storeXml(String entity) { return entity; } @Post("txt:json") public String storeJson(String entity) { return entity; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyBean.java0000664000175000017500000000562211757206352027063 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.Serializable; /** * Test bean to be serialized. * * @author Jerome Louvel */ public class MyBean implements Serializable { private static final long serialVersionUID = 1L; private String name; private String description; public MyBean() { } public MyBean(String name, String description) { super(); this.name = name; this.description = description; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MyBean other = (MyBean) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String getDescription() { return description; } public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public void setDescription(String description) { this.description = description; } public void setName(String name) { this.name = name; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource1.java0000664000175000017500000000340111757206352030057 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Options; import org.restlet.resource.Post; import org.restlet.resource.Put; /** * Sample annotated interface. * * @author Jerome Louvel */ public interface MyResource1 { @Get public MyBean represent(); @Put public String store(MyBean bean); @Post public boolean accept(MyBean bean); @Delete("txt") public String remove(); @Options("txt") public String describe(); } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource10TestCase.java0000664000175000017500000000714011757206354033131 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.resource.ResourceException; import org.restlet.routing.Router; import org.restlet.test.RestletTestCase; /** * Test annotated resource inheriting abstract super class that implements * several annotated interfaces. * * @author Thierry Boileau */ public class AnnotatedResource10TestCase extends RestletTestCase { private static class TestApplication extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/test", MyResource10.class); return router; } } private Component c; private Client client; protected void setUp() throws Exception { super.setUp(); Engine.getInstance().getRegisteredConverters().clear(); Engine.getInstance().registerDefaultConverters(); c = new Component(); c.getServers().add(Protocol.HTTP, 8111); c.getDefaultHost().attach(new TestApplication()); c.start(); client = new Client(Protocol.HTTP); } @Override protected void tearDown() throws Exception { c.stop(); c = null; client.stop(); client = null; super.tearDown(); } /** * Test annotated methods. * * @throws IOException * @throws ResourceException */ public void test() throws IOException, ResourceException { client = new Client(Protocol.HTTP); Request request = new Request(Method.GET, "http://localhost:8111/test"); Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("asText", response.getEntity().getText()); response.getEntity().release(); request = new Request(Method.POST, "http://localhost:8111/test"); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("accept", response.getEntity().getText()); response.getEntity().release(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource2.java0000664000175000017500000000322111757206354030062 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class MyResource2 extends ServerResource { @Get public Representation represent() { return new StringRepresentation("", MediaType.TEXT_XML); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource7.java0000664000175000017500000000311611757206352030070 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; public class MyResource7 extends ServerResource { @Post("json:xml") public String storeJson(String entity) { return entity + "1"; } @Post("xml:xml") public String storeXml(String entity) { return entity + "2"; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource1TestCase.java0000664000175000017500000001252011757206352033045 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.ext.jackson.JacksonConverter; import org.restlet.ext.xstream.XstreamConverter; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource1TestCase extends RestletTestCase { private ClientResource clientResource; private MyResource1 myResource; protected void setUp() throws Exception { super.setUp(); Engine.getInstance().getRegisteredConverters().clear(); Engine.getInstance().getRegisteredConverters().add(new JacksonConverter()); Engine.getInstance().getRegisteredConverters().add(new XstreamConverter()); Engine.getInstance().registerDefaultConverters(); Finder finder = new Finder(); finder.setTargetClass(MyServerResource1.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); this.myResource = clientResource.wrap(MyResource1.class); } @Override protected void tearDown() throws Exception { clientResource = null; myResource = null; super.tearDown(); } public void testDelete() { assertEquals("Done", myResource.remove()); } public void testGet() throws IOException, ResourceException { MyBean myBean = myResource.represent(); assertNotNull(myBean); assertEquals("myName", myBean.getName()); assertEquals("myDescription", myBean.getDescription()); String result = clientResource.get(MediaType.TEXT_XML).getText(); assertEquals( "\n\n myName\n myDescription\n", result); result = clientResource.get(MediaType.APPLICATION_XML).getText(); assertEquals( "\n\n myName\n myDescription\n", result); result = clientResource.get(MediaType.APPLICATION_ALL_XML).getText(); assertEquals( "\n\n myName\n myDescription\n", result); result = clientResource.get(MediaType.APPLICATION_JSON).getText(); assertEquals("{\"name\":\"myName\",\"description\":\"myDescription\"}", result); result = clientResource.get(MediaType.APPLICATION_JAVA_OBJECT_XML) .getText(); assertTrue(result .startsWith(" \n", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); result = clientResource.get(MediaType.TEXT_HTML); assertNotNull(result); assertEquals("root", result.getText()); assertEquals(MediaType.TEXT_HTML, result.getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedInterface3.java0000664000175000017500000000276011757206352031531 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; /** * Annotated interface that extends {@link AnnotatedInterface1} and * {@link AnnotatedInterface2}. * * @author Thierry Boileau * */ public interface AnnotatedInterface3 extends AnnotatedInterface1, AnnotatedInterface2 { } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedInterface2.java0000664000175000017500000000273211757206352031527 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Post; /** * Annotated interface that declares a single "Post" method. * * @author Thierry Boileau * */ public interface AnnotatedInterface2 { @Post public String accept(); } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource10.java0000664000175000017500000000263511757206354030151 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; /** * Resource that inherits annotated methods. * * @author Thierry Boileau * */ public class MyResource10 extends AbstractAnnotatedServerResource { } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AbstractAnnotatedServerResource.java0000664000175000017500000000322611757206352034206 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.ServerResource; /** * Abstract {@link ServerResource} that implements several annotated interfaces. * * @author Thierry Boileau */ public abstract class AbstractAnnotatedServerResource extends ServerResource implements AnnotatedInterface3 { public String accept() { return "accept"; } public String asText() { return "asText"; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource8.java0000664000175000017500000000331211757206352030067 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; public class MyResource8 extends ServerResource { @Post("xml|json:xml") public String storeForm(String entity) { return entity + "1"; } @Post("xml|json:json|html") public String store1(String entity) { return entity + "2"; } @Post("form|json:json|html") public String store2(String entity) { return entity + "3"; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/SIMethod.java0000664000175000017500000000320511757206354027361 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("SI") public @interface SIMethod { String value() default ""; } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/ResourceTestCase.java0000664000175000017500000000553511757206352031136 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Resource; import org.restlet.test.RestletTestCase; /** * Resource test case. * * @author Kevin Conaway * @author Konstantin Laufer (laufer@cs.luc.edu) * @author Jerome Louvel */ @SuppressWarnings("deprecation") public class ResourceTestCase extends RestletTestCase { public class AutoDetectResource extends Resource { public Representation representXml() { return new StringRepresentation("test", MediaType.TEXT_XML); } public Representation representHtmlEn() { return new StringRepresentation("test EN", MediaType.TEXT_HTML); } public Representation representHtmlFr() { return new StringRepresentation("test FR", MediaType.TEXT_HTML); } } public void testIsAvailable() { Resource r = new Resource(); assertTrue(r.isAvailable()); r.init(null, null, null); assertTrue(r.isAvailable()); r = new Resource(null, null, null); assertTrue(r.isAvailable()); } public void testIsModifiable() { Resource r = new Resource(); assertFalse(r.isModifiable()); r.setModifiable(true); assertTrue(r.isModifiable()); r.init(null, null, null); assertTrue(r.isModifiable()); r = new Resource(null, null, null); assertFalse(r.isModifiable()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/USIMethod.java0000664000175000017500000000320711757206352027506 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("USI") public @interface USIMethod { String value() default ""; } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/DirectoryTestCase.java0000664000175000017500000005772411757206352031322 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.File; import java.io.IOException; import java.util.Date; import org.restlet.Application; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Language; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.io.BioUtils; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Directory; import org.restlet.test.RestletTestCase; /** * Unit tests for the Directory class. * * @author Thierry Boileau */ public class DirectoryTestCase extends RestletTestCase { /** * Internal class used for test purpose * * @author Thierry Boileau */ private static class MyApplication extends Application { Directory directory; /** * Constructor. * * @param testDirectory * The test directory. */ public MyApplication(File testDirectory) { // Create a DirectoryHandler that manages a local Directory this.directory = new Directory(getContext(), LocalReference .createFileReference(testDirectory)); this.directory.setNegotiatingContent(true); } @Override public Restlet createInboundRoot() { return this.directory; } public Directory getDirectory() { return this.directory; } public void setTestDirectory(File testDirectory) { final String rootIdentifier = LocalReference.createFileReference( testDirectory).getIdentifier(); if (rootIdentifier.endsWith("/")) { this.directory.setRootRef(new Reference(rootIdentifier)); } else { this.directory.setRootRef(new Reference(rootIdentifier + "/")); } } } public static void main(String[] args) throws Exception { new DirectoryTestCase().testDirectory(); } String webSiteURL = "http://myapplication/"; String baseFileUrl = this.webSiteURL.concat("fichier.txt"); String baseFileUrlEn = this.webSiteURL.concat("fichier.txt.en"); String baseFileUrlFr = this.webSiteURL.concat("fichier.txt.fr"); String baseFileUrlFrBis = this.webSiteURL.concat("fichier.fr.txt"); String percentEncodedFileUrl = this.webSiteURL.concat(Reference .encode("a new %file.txt.fr")); String percentEncodedFileUrlBis = this.webSiteURL .concat("a+new%20%25file.txt.fr"); /** Tests the creation of directory with unknown parent directories. */ String testCreationDirectory = webSiteURL.concat("dir/does/not/exist"); /** Tests the creation of file with unknown parent directories. */ String testCreationFile = webSiteURL.concat("file/does/not/exist"); /** Tests the creation of text file with unknown parent directories. */ String testCreationTextFile = webSiteURL .concat("text/file/does/not/exist.txt"); File testDir; /** * Helper for the test * * @param directory * @param baseRef * @param resourceRef * @param method * @param entity * @return */ private Response handle(Application application, String baseRef, String resourceRef, Method method, Representation entity, String testCode) { final Request request = new Request(); final Response response = new Response(request); request.setResourceRef(resourceRef); request.setOriginalRef(request.getResourceRef().getTargetRef()); request.getResourceRef().setBaseRef(baseRef); request.setMethod(method); if (Method.PUT.equals(method)) { request.setEntity(entity); } application.handle(request, response); System.out.println("[test, status]=[" + testCode + ", " + response.getStatus() + "]"); return response; } public void testDirectory() throws Exception { // Create a temporary directory for the tests this.testDir = new File(System.getProperty("java.io.tmpdir"), "DirectoryTestCase/tests1" + new Date().getTime()); // Create a new Restlet component final Component clientComponent = new Component(); clientComponent.getClients().add(Protocol.FILE); // Create an application final MyApplication application = new MyApplication(this.testDir); // Attach the application to the component and start it clientComponent.getDefaultHost().attach("", application); // Now, let's start the component! clientComponent.start(); // Allow extensions tunneling application.getTunnelService().setExtensionsTunnel(true); BioUtils.delete(this.testDir, true); this.testDir = new File(System.getProperty("java.io.tmpdir"), "DirectoryTestCase/tests2" + new Date().getTime()); this.testDir.mkdirs(); application.setTestDirectory(testDir); // Test the directory Restlet with an index name testDirectory(application, application.getDirectory(), "index"); BioUtils.delete(this.testDir, true); this.testDir = new File(System.getProperty("java.io.tmpdir"), "DirectoryTestCase/tests3" + new Date().getTime()); this.testDir.mkdirs(); application.setTestDirectory(testDir); // Test the directory Restlet with no index name testDirectory(application, application.getDirectory(), ""); // Avoid extensions tunneling application.getTunnelService().setExtensionsTunnel(false); BioUtils.delete(this.testDir, true); this.testDir = new File(System.getProperty("java.io.tmpdir"), "DirectoryTestCase/tests4" + new Date().getTime()); this.testDir.mkdirs(); application.setTestDirectory(testDir); // Test the directory Restlet with an index name testDirectory(application, application.getDirectory(), "index"); BioUtils.delete(this.testDir, true); this.testDir = new File(System.getProperty("java.io.tmpdir"), "DirectoryTestCase/tests5" + new Date().getTime()); this.testDir.mkdirs(); application.setTestDirectory(testDir); // Test the directory Restlet with no index name testDirectory(application, application.getDirectory(), ""); BioUtils.delete(this.testDir, true); this.testDir = new File(System.getProperty("java.io.tmpdir"), "DirectoryTestCase/tests6" + new Date().getTime()); this.testDir.mkdirs(); application.setTestDirectory(testDir); // Test the access to the sub directories. testDirectoryDeeplyAccessible(application, application.getDirectory()); // Now, let's stop the component! clientComponent.stop(); } /** * Helper * * @param application * @param directory * @throws IOException */ private void testDirectoryDeeplyAccessible(MyApplication application, Directory directory) throws IOException { final File testDirectory = new File(this.testDir, "dir/subDir"); testDirectory.mkdirs(); final File testFile = File .createTempFile("test", ".txt", testDirectory); directory.setDeeplyAccessible(true); Response response = handle(application, this.webSiteURL, this.webSiteURL.concat("dir/subDir/"), Method.GET, null, "deep access 1"); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = handle(application, this.webSiteURL, this.webSiteURL.concat( "dir/subDir/").concat(testFile.getName()), Method.GET, null, "deep access 2"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); directory.setDeeplyAccessible(false); response = handle(application, this.webSiteURL, this.webSiteURL .concat("dir/subDir/"), Method.GET, null, "deep access 3"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); response = handle(application, this.webSiteURL, this.webSiteURL.concat( "dir/subDir/").concat(testFile.getName()), Method.GET, null, "deep access 4"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } /** * Helper * * @param application * @param directory * @param indexName * @throws IOException */ private void testDirectory(MyApplication application, Directory directory, String indexName) throws IOException { // Create a temporary file for the tests (the tests directory is not // empty) final File testFile = File.createTempFile("test", ".txt", this.testDir); // Create a temporary directory final File testDirectory = new File(this.testDir, "try"); testDirectory.mkdir(); final String testFileUrl = this.webSiteURL.concat(testFile.getName()); final String testDirectoryUrl = this.webSiteURL.concat(testDirectory .getName()); directory.setIndexName(indexName); // Test 1a : directory does not allow to GET its content directory.setListingAllowed(false); Response response = handle(application, this.webSiteURL, this.webSiteURL, Method.GET, null, "1a"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); // Test 1b : directory allows to GET its content directory.setListingAllowed(true); response = handle(application, this.webSiteURL, this.webSiteURL, Method.GET, null, "1b"); assertEquals(Status.SUCCESS_OK, response.getStatus()); if (response.getStatus().equals(Status.SUCCESS_OK)) { // should list all files in the directory (at least the temporary // file generated before) response.getEntity().write(System.out); } // Test 2a : tests the HEAD method response = handle(application, this.webSiteURL, testFileUrl, Method.GET, null, "2a"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); response = handle(application, this.webSiteURL, testFileUrl, Method.HEAD, null, "2a"); assertEquals(Status.SUCCESS_OK, response.getStatus()); // Test 2b : try to GET a file that does not exist response = handle(application, this.webSiteURL, this.webSiteURL + "123456.txt", Method.GET, null, "2b"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); // Test 3a : try to put a new representation, but the directory is read // only directory.setModifiable(false); response = handle(application, this.webSiteURL, this.baseFileUrl, Method.PUT, new StringRepresentation("this is test 3a"), "3a"); assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, response .getStatus()); // Test 3b : try to put a new representation, the directory is no more // read only directory.setModifiable(true); Representation rep = new StringRepresentation("this is test 3b"); rep.getLanguages().add(Language.FRENCH); response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.PUT, rep, "3b"); assertEquals(Status.SUCCESS_CREATED, response.getStatus()); // Test 4 : Try to get the representation of the new file response = handle(application, this.webSiteURL, this.baseFileUrl, Method.GET, null, "4"); assertEquals(Status.SUCCESS_OK, response.getStatus()); if (response.getStatus().equals(Status.SUCCESS_OK)) { response.getEntity().write(System.out); System.out.println(""); } // Test 5 : add a new representation of the same base file response = handle(application, this.webSiteURL, this.baseFileUrlEn, Method.PUT, new StringRepresentation("this is a test - En"), "5a"); assertEquals(Status.SUCCESS_CREATED, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrl, Method.HEAD, null, "5b"); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlEn, Method.HEAD, null, "5c"); assertEquals(Status.SUCCESS_OK, response.getStatus()); // Test 6a : delete a file response = handle(application, this.webSiteURL, testFileUrl, Method.DELETE, null, "6a-1"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); response = handle(application, this.webSiteURL, testFileUrl, Method.HEAD, null, "6a-2"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); // Test 6b : delete a file that does not exist response = handle(application, this.webSiteURL, testFileUrl, Method.DELETE, null, "6b"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); // Test 6c : delete a directory (without and with trailing slash) // Distinct behaviors if an index has been defined or not if (indexName.length() == 0) { response = handle(application, this.webSiteURL, testDirectoryUrl, Method.DELETE, null, "6c-1"); assertEquals(Status.REDIRECTION_SEE_OTHER, response.getStatus()); response = handle(application, response.getLocationRef() .getIdentifier(), response.getLocationRef().getIdentifier(), Method.DELETE, null, "6c-2"); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, response.getStatus()); response = handle(application, this.webSiteURL, this.webSiteURL, Method.DELETE, null, "6c-3"); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, response.getStatus()); } else { // As there is no index file in the directory, the response must // return the status Status.CLIENT_ERROR_NOT_FOUND response = handle(application, this.webSiteURL, testDirectoryUrl + "/", Method.DELETE, null, "6c-2"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); response = handle(application, this.webSiteURL, this.webSiteURL, Method.DELETE, null, "6c-3"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } // Test 7a : put one representation of the base file (in French // language) response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.PUT, new StringRepresentation("message de test"), "7a"); assertTrue(response.getStatus().isSuccess()); // Test 7b : put another representation of the base file (in French // language) but the extensions are mixed // and there is no content negotiation directory.setNegotiatingContent(false); response = handle(application, this.webSiteURL, this.baseFileUrlFrBis, Method.PUT, new StringRepresentation("message de test"), "7b-1"); assertEquals(Status.SUCCESS_OK, response.getStatus()); // The 2 resources in French must be present (the same actually) response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.HEAD, null, "7b-2"); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlFrBis, Method.HEAD, null, "7b-3"); assertTrue(response.getStatus().equals(Status.SUCCESS_OK)); // Test 7c : delete the file representation of the resources with no // content negotiation // The 2 French resources are deleted (there were only one) response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.DELETE, null, "7c-1"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.HEAD, null, "7c-2"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlFrBis, Method.HEAD, null, "7c-3"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlFrBis, Method.DELETE, null, "7c-4"); assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); // Test 7d : put another representation of the base file (in French // language) but the extensions are mixed // and there is content negotiation directory.setNegotiatingContent(true); response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.PUT, new StringRepresentation("message de test"), "7d-1"); assertEquals(Status.SUCCESS_CREATED, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlFrBis, Method.PUT, new StringRepresentation("message de test Bis"), "7d-2"); assertEquals(Status.SUCCESS_OK, response.getStatus()); // only one resource in French must be present response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.HEAD, null, "7d-3"); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlFrBis, Method.HEAD, null, "7d-4"); assertEquals(Status.SUCCESS_OK, response.getStatus()); // TBOI : not sure this test is correct // Check if only one resource has been created directory.setNegotiatingContent(false); response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.HEAD, null, "7d-5"); assertEquals(Status.SUCCESS_OK, response.getStatus()); // Test 7e : delete the file representation of the resources with // content negotiation directory.setNegotiatingContent(true); response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.DELETE, null, "7e-1"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.HEAD, null, "7e-2"); if (application.getTunnelService().isExtensionsTunnel()) { assertEquals(Status.SUCCESS_OK, response.getStatus()); } else { assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } response = handle(application, this.webSiteURL, this.baseFileUrlFrBis, Method.HEAD, null, "7e-8"); if (application.getTunnelService().isExtensionsTunnel()) { assertEquals(Status.SUCCESS_OK, response.getStatus()); } else { assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus()); } // Test 8 : must delete the English representation response = handle(application, this.webSiteURL, this.baseFileUrlFr, Method.DELETE, null, "8a"); response = handle(application, this.webSiteURL, this.baseFileUrlEn, Method.DELETE, null, "8b"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); // Test 9a : put a new representation, the resource's URI contains // percent-encoded characters directory.setModifiable(true); rep = new StringRepresentation("this is test 9a"); rep.getLanguages().add(Language.FRENCH); response = handle(application, this.webSiteURL, this.percentEncodedFileUrl, Method.PUT, rep, "9a"); assertEquals(Status.SUCCESS_CREATED, response.getStatus()); // Test 9b : Try to get the representation of the new file response = handle(application, this.webSiteURL, this.percentEncodedFileUrl, Method.GET, null, "9b"); assertEquals(Status.SUCCESS_OK, response.getStatus()); if (response.getStatus().equals(Status.SUCCESS_OK)) { response.getEntity().write(System.out); System.out.println(""); } // Test 9c : Try to get the representation of the new file with an // equivalent URI response = handle(application, this.webSiteURL, this.percentEncodedFileUrlBis, Method.GET, null, "9c"); assertEquals(Status.SUCCESS_OK, response.getStatus()); if (response.getStatus().equals(Status.SUCCESS_OK)) { response.getEntity().write(System.out); System.out.println(""); } // Test 9d : Try to delete the file response = handle(application, this.webSiteURL, this.percentEncodedFileUrl, Method.DELETE, null, "9d"); assertEquals(Status.SUCCESS_NO_CONTENT, response.getStatus()); // Test 10a : Try to create a directory with an unknown hierarchy of // parent directories. response = handle(application, webSiteURL, testCreationDirectory, Method.PUT, new StringRepresentation("useless entity"), "10a"); assertTrue(response.getStatus().equals(Status.REDIRECTION_SEE_OTHER)); // Test 10b : Try to create a directory (with the trailing "/") with an // unkown hierarchy of parent directories. response = handle(application, webSiteURL, testCreationDirectory + "/", Method.PUT, new StringRepresentation("useless entity"), "10b"); assertTrue(response.getStatus().equals(Status.SUCCESS_NO_CONTENT)); // Test 10c : Try to create a file with an unknown hierarchy of // parent directories. The name and the metadata of the provided entity // don't match response = handle(application, webSiteURL, testCreationFile, Method.PUT, new StringRepresentation("file entity"), "10c"); assertTrue(response.getStatus().equals(Status.REDIRECTION_SEE_OTHER)); // Test 10d : Try to create a file with an unknown hierarchy of // parent directories. The name and the metadata of the provided entity // match response = handle(application, webSiteURL, testCreationTextFile, Method.PUT, new StringRepresentation("file entity"), "10d"); assertTrue(response.getStatus().equals(Status.SUCCESS_CREATED)); BioUtils.delete(testDirectory, true); System.out.println("End of tests*********************"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyServerResource12.java0000664000175000017500000000320211757206354031331 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.data.Form; import org.restlet.resource.ServerResource; /** * Sample server resource. * * @author Jerome Louvel */ public class MyServerResource12 extends ServerResource implements MyResource12 { private static Form myForm = null; public void store(Form form) { myForm = form; } public Form represent() { return myForm; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource4.java0000664000175000017500000000320611757206352030065 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class MyResource4 extends ServerResource { @Get("xml") public String toXml() { return ""; } @Get("json") public String toJson() { return "[\"root\"]"; } @Get("html") public String toHtml() { return "root"; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource9.java0000664000175000017500000000536311757206354030102 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.data.Form; import org.restlet.resource.ServerResource; public class MyResource9 extends ServerResource { @SIMethod("form:html") public String si1(Form form) { return "si-html+form"; } @SIMethod("txt:html") public String si2(String txt) { return "si-html+txt"; } @SIMethod("txt") public String si3(String txt) { return "si-string+" + txt; } @SIMethod("form:txt") public String si4(Form form) { return "si-string+form"; } @SNIMethod("form:html") public String sni1(Form form) { return "sni-html+form"; } @SNIMethod("txt:html") public String sni2(String txt) { return "sni-html+txt"; } @SNIMethod("txt") public String sni3(String txt) { return "sni-string+" + txt; } @USIMethod("txt") public String usi1() { return "usi-string"; } @USIMethod("html") public String usi2() { return "usi-html"; } @USIMethod("form:txt") public String usi3(Form form) { return "usi-string+form"; } @USIMethod("txt") public String usi3(String txt) { return "usi-string+" + txt; } @USNIMethod("form:html") public String usni1(Form form) { return "usni-html+form"; } @USNIMethod("txt:html") public String usni2(String txt) { return "usni-html+txt"; } @USNIMethod("txt") public String usni3(String txt) { return "usni-string+" + txt; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/SNIMethod.java0000664000175000017500000000320711757206352027477 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("SNI") public @interface SNIMethod { String value() default ""; } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource3TestCase.java0000664000175000017500000000464211757206352033055 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.Status; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource3TestCase extends RestletTestCase { private ClientResource clientResource; protected void setUp() throws Exception { super.setUp(); Finder finder = new Finder(); finder.setTargetClass(MyResource3.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); } @Override protected void tearDown() throws Exception { clientResource = null; super.tearDown(); } public void testGet() throws IOException, ResourceException { Status status = null; try { clientResource.get(); status = clientResource.getStatus(); } catch (ResourceException e) { status = e.getStatus(); } assertEquals(Status.CLIENT_ERROR_NOT_FOUND, status); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource2TestCase.java0000664000175000017500000000465311757206354033060 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource2TestCase extends RestletTestCase { private ClientResource clientResource; protected void setUp() throws Exception { super.setUp(); Finder finder = new Finder(); finder.setTargetClass(MyResource2.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); } @Override protected void tearDown() throws Exception { clientResource = null; super.tearDown(); } public void testGet() throws IOException, ResourceException { Representation result = clientResource.get(MediaType.APPLICATION_ATOM); assertNotNull(result); assertEquals("", result.getText()); assertEquals(MediaType.TEXT_XML, result.getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/ResourceTestSuite.java0000664000175000017500000000502611757206352031347 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import junit.framework.Test; import junit.framework.TestSuite; public class ResourceTestSuite { public static Test suite() { TestSuite suite = new TestSuite("Test for org.restlet.test.resource"); // $JUnit-BEGIN$ suite.addTestSuite(DirectoryTestCase.class); suite.addTestSuite(ResourceTestCase.class); suite.addTestSuite(AnnotatedResource1TestCase.class); suite.addTestSuite(AnnotatedResource2TestCase.class); suite.addTestSuite(AnnotatedResource3TestCase.class); suite.addTestSuite(AnnotatedResource4TestCase.class); suite.addTestSuite(AnnotatedResource5TestCase.class); suite.addTestSuite(AnnotatedResource6TestCase.class); suite.addTestSuite(AnnotatedResource7TestCase.class); suite.addTestSuite(AnnotatedResource8TestCase.class); suite.addTestSuite(AnnotatedResource9TestCase.class); suite.addTestSuite(AnnotatedResource10TestCase.class); suite.addTestSuite(AnnotatedResource11TestCase.class); suite.addTestSuite(AnnotatedResource12TestCase.class); // Tests based on HTTP client connectors are not supported by the GAE // edition. suite.addTestSuite(FileRepresentationTestCase.class); // $JUnit-END$ return suite; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource5TestCase.java0000664000175000017500000000527111757206354033060 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource5TestCase extends RestletTestCase { private ClientResource clientResource; protected void setUp() throws Exception { super.setUp(); Finder finder = new Finder(); finder.setTargetClass(MyResource5.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); } @Override protected void tearDown() throws Exception { clientResource = null; super.tearDown(); } public void testGet() throws IOException, ResourceException { Representation result = clientResource.post("[\"root\"]", MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("[\"root\"]", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); result = clientResource.post("", MediaType.APPLICATION_XML); assertNotNull(result); assertEquals("", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource12TestCase.java0000664000175000017500000000511611757206354033134 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.data.Form; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource12TestCase extends RestletTestCase { private ClientResource clientResource; private MyResource12 myResource; protected void setUp() throws Exception { super.setUp(); Finder finder = new Finder(); finder.setTargetClass(MyServerResource12.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); this.myResource = clientResource.wrap(MyResource12.class); } @Override protected void tearDown() throws Exception { clientResource = null; myResource = null; super.tearDown(); } public void testPutGet() { Form myForm = myResource.represent(); assertNull(myForm); myForm = new Form(); myForm.add("param1", "value1"); myForm.add("param2", "value2"); myResource.store(myForm); myForm = myResource.represent(); assertNotNull(myForm); assertEquals("value1", myForm.getFirstValue("param1")); assertEquals("value2", myForm.getFirstValue("param2")); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource9TestCase.java0000664000175000017500000003615011757206352033062 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Protocol; import org.restlet.engine.Engine; import org.restlet.resource.ResourceException; import org.restlet.routing.Router; import org.restlet.test.RestletTestCase; /** * Test annotated resources with extra annotations and methods. * * @author Thierry Boileau */ public class AnnotatedResource9TestCase extends RestletTestCase { private static class TestApplication extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/test", MyResource9.class); return router; } } public static final Method SI = new Method("SI", "What a method!", "http://www.restlet.org", true, true); public static final Method SNI = new Method("SNI", "What a method!", "http://www.restlet.org", true, false); public static final Method USI = new Method("USI", "What a method!", "http://www.restlet.org", false, true); public static final Method USNI = new Method("USNI", "What a method!", "http://www.restlet.org", false, false); private Component c; private Client client; protected void setUp() throws Exception { super.setUp(); Engine.getInstance().getRegisteredConverters().clear(); Engine.getInstance().registerDefaultConverters(); c = new Component(); c.getServers().add(Protocol.HTTP, 8111); c.getDefaultHost().attach(new TestApplication()); c.start(); client = new Client(Protocol.HTTP); } @Override protected void tearDown() throws Exception { c.stop(); c = null; client.stop(); client = null; // Restore default converters Engine.register(); } /** * Test safe and idempotent method. * * @throws IOException * @throws ResourceException */ public void testSI() throws IOException, ResourceException { Method method = AnnotatedResource9TestCase.SI; String text = "text"; Form form = new Form(); form.add("key", "value"); client = new Client(Protocol.HTTP); Request request = new Request(method, "http://localhost:8111/test"); Response response = client.handle(request); assertTrue(response.getStatus().isSuccess()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); assertEquals("si-html+txt", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(form.getWebRepresentation()); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("si-string+form", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("si-string+text", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(form.getWebRepresentation()); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); assertEquals("si-html+form", response.getEntity().getText()); } /** * Test safe and non-idempotent method. * * @throws IOException * @throws ResourceException */ public void testSNI() throws IOException, ResourceException { Method method = AnnotatedResource9TestCase.SNI; String text = "text"; Form form = new Form(); form.add("key", "value"); client = new Client(Protocol.HTTP); Request request = new Request(method, "http://localhost:8111/test"); Response response = client.handle(request); assertTrue(response.getStatus().isSuccess()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); assertEquals("sni-html+txt", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(form.getWebRepresentation()); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); assertEquals("sni-html+form", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("sni-string+text", response.getEntity().getText()); } /** * Test unsafe and idempotent method. * * @throws IOException * @throws ResourceException */ public void testUSI() throws IOException, ResourceException { Method method = AnnotatedResource9TestCase.USI; String text = "text"; Form form = new Form(); form.add("key", "value"); client = new Client(Protocol.HTTP); Request request = new Request(method, "http://localhost:8111/test"); Response response = client.handle(request); assertTrue(response.getStatus().isSuccess()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("usi-string+text", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(form.getWebRepresentation()); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("usi-string+form", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("usi-string+text", response.getEntity().getText()); request = new Request(AnnotatedResource9TestCase.USI, "http://localhost:8111/test"); request.setEntity(form.getWebRepresentation()); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("usi-string+form", response.getEntity().getText()); request = new Request(AnnotatedResource9TestCase.USI, "http://localhost:8111/test"); request.setEntity(form.getWebRepresentation()); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("usi-string+form", response.getEntity().getText()); } /** * Test unsafe and non-idempotent method. * * @throws IOException * @throws ResourceException */ public void testUSNI() throws IOException, ResourceException { Method method = AnnotatedResource9TestCase.USNI; String text = "text"; Form form = new Form(); form.add("key", "value"); client = new Client(Protocol.HTTP); Request request = new Request(method, "http://localhost:8111/test"); Response response = client.handle(request); assertTrue(response.getStatus().isSuccess()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); response.getEntity().release(); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); assertEquals("usni-html+txt", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(form.getWebRepresentation()); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_HTML)); response = client.handle(request); assertEquals(MediaType.TEXT_HTML, response.getEntity().getMediaType()); assertEquals("usni-html+form", response.getEntity().getText()); request = new Request(method, "http://localhost:8111/test"); request.setEntity(text, MediaType.TEXT_PLAIN); request.getClientInfo().getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_PLAIN)); response = client.handle(request); assertEquals(MediaType.TEXT_PLAIN, response.getEntity().getMediaType()); assertEquals("usni-string+text", response.getEntity().getText()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource11.java0000664000175000017500000000311011757206354030137 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.Get; /** * Resource that precises the media type of one of its inherited annotated * methods. * * @author Thierry Boileau * */ public class MyResource11 extends AbstractAnnotatedServerResource { @Get("txt") @Override public String asText() { return "asText-txt"; }; } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/FileRepresentationTestCase.java0000664000175000017500000001103211757206352033136 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.File; import java.io.FileOutputStream; 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.data.Disposition; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.io.BioUtils; import org.restlet.representation.FileRepresentation; import org.restlet.representation.Representation; import org.restlet.test.RestletTestCase; /** * Unit tests for the FileRepresentation class. * * @author Kevin Conaway */ public class FileRepresentationTestCase extends RestletTestCase { private Component component; private File file; private File testDir; private String uri; @Override public void setUp() throws Exception { super.setUp(); uri = "http://localhost:" + TEST_PORT + "/"; component = new Component(); component.getServers().add(Protocol.HTTP, TEST_PORT); component.start(); // Create a temporary directory for the tests this.testDir = new File(System.getProperty("java.io.tmpdir"), "FileRepresentationTestCase"); this.testDir.mkdirs(); this.file = new File(this.testDir, getClass().getName()); FileOutputStream os = new FileOutputStream(file); os.write("abc".getBytes()); os.close(); } @Override public void tearDown() throws Exception { super.tearDown(); component.stop(); BioUtils.delete(this.file); BioUtils.delete(this.testDir, true); component = null; this.file = null; this.testDir = null; } public void testConstructors() { final File file = new File("test.txt"); final FileRepresentation r = new FileRepresentation(file, MediaType.TEXT_PLAIN); assertEquals("test.txt", r.getDisposition().getFilename()); assertEquals(MediaType.TEXT_PLAIN, r.getMediaType()); assertNull(r.getExpirationDate()); } public void testFileName() throws Exception { Application application = new Application() { @Override public Restlet createInboundRoot() { return new Restlet() { @Override public void handle(Request request, Response response) { response.setEntity(new FileRepresentation(file, MediaType.TEXT_PLAIN)); response.getEntity().getDisposition().setType( Disposition.TYPE_ATTACHMENT); } }; } }; component.getDefaultHost().attach(application); Client client = new Client(new Context(), Protocol.HTTP); Request request = new Request(Method.GET, uri); Response response = client.handle(request); Representation entity = response.getEntity(); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("abc", entity.getText()); assertEquals(getClass().getName(), entity.getDisposition() .getFilename()); client.stop(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource3.java0000664000175000017500000000414011757206352030062 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Sample server resource that sets the "existing" flag to false. * * @author Jerome Louvel */ public class MyResource3 extends ServerResource implements MyResource1 { private volatile MyBean myBean = new MyBean("myName", "myDescription"); @Override protected void doInit() throws ResourceException { super.doInit(); setExisting(false); } public boolean accept(MyBean bean) { return bean.equals(myBean); } public String describe() { return "MyDescription"; } public String remove() { myBean = null; return "Done"; } public MyBean represent() { return myBean; } public String store(MyBean bean) { myBean = bean; return "Done"; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource6TestCase.java0000664000175000017500000000527311757206352033061 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource6TestCase extends RestletTestCase { private ClientResource clientResource; protected void setUp() throws Exception { super.setUp(); Finder finder = new Finder(); finder.setTargetClass(MyResource6.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); } @Override protected void tearDown() throws Exception { clientResource = null; super.tearDown(); } public void testGet() throws IOException, ResourceException { Representation result = clientResource.post("[\"root\"]", MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("[\"root\"]2", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); result = clientResource.post("", MediaType.APPLICATION_XML); assertNotNull(result); assertEquals("1", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/MyResource12.java0000664000175000017500000000303111757206352030140 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import org.restlet.data.Form; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * Sample annotated interface. * * @author Jerome Louvel */ public interface MyResource12 { @Get public Form represent(); @Put public void store(Form form); } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource7TestCase.java0000664000175000017500000000554311757206352033062 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource7TestCase extends RestletTestCase { private ClientResource clientResource; protected void setUp() throws Exception { super.setUp(); Finder finder = new Finder(); finder.setTargetClass(MyResource7.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); } @Override protected void tearDown() throws Exception { clientResource = null; super.tearDown(); } public void testGet() throws IOException, ResourceException { Representation input = new StringRepresentation("[\"root\"]", MediaType.APPLICATION_JSON); Representation result = clientResource.post(input); assertNotNull(result); assertEquals("[\"root\"]1", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); input = new StringRepresentation("", MediaType.APPLICATION_XML); result = clientResource.post(input); assertNotNull(result); assertEquals("2", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/resource/USNIMethod.java0000664000175000017500000000321111757206354027621 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("USNI") public @interface USNIMethod { String value() default ""; } restlet-2.0.14/org.restlet.test/src/org/restlet/test/connector/0000775000175000017500000000000011757206354025205 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/connector/ZipClientTestCase.java0000664000175000017500000000777211757206354031422 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.connector; import java.io.File; import java.io.IOException; import org.restlet.data.LocalReference; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.io.BioUtils; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.test.RestletTestCase; /** * Unit test case for the Zip client connector. * * @author Remi Dewitte */ public class ZipClientTestCase extends RestletTestCase { public void testFileClient() throws IOException, InterruptedException { File zipFile = File.createTempFile("Restlet", ".zip"); // We just wanted a valid writable path BioUtils.delete(zipFile); String text = "Test content\r\nLine 2\r\nLine2"; String text2 = "Test content\nLine 2"; LocalReference fr = LocalReference.createFileReference(zipFile); Reference zr = new Reference("zip:" + fr.toString()); String fzr = zr + "!/test.txt"; String fzd = zr + "!/dir/"; String fzr2 = fzd + "test2.txt"; // Write the text to file ClientResource r = new ClientResource(fzr); r.put(new StringRepresentation(text)); assertTrue(r.getStatus().equals(Status.SUCCESS_CREATED)); // Get the text and compare to the original r.get(); assertTrue(r.getStatus().equals(Status.SUCCESS_OK)); assertEquals(r.getResponseEntity().getText(), text); r.release(); // Write the text to file ClientResource r2 = new ClientResource(fzr2); r2.put(new StringRepresentation(text2)); assertTrue(r2.getStatus().equals(Status.SUCCESS_OK)); // Checking first one was not overwritten r.get(); assertTrue(r.getStatus().equals(Status.SUCCESS_OK)); assertEquals(r.getResponseEntity().getText(), text); r.release(); // Put a directory ClientResource rd = new ClientResource(fzd); rd.put(new EmptyRepresentation()); assertTrue(rd.getStatus().equals(Status.SUCCESS_OK)); rd.get(); assertTrue(rd.getStatus().equals(Status.SUCCESS_OK)); // Checking second one was output r2.get(); assertTrue("Could not get " + fzr2, r2.getStatus().equals( Status.SUCCESS_OK)); assertEquals(r2.getResponseEntity().getText(), text2); ClientResource rTest2 = new ClientResource(zr + "!test2"); rTest2.get(); assertFalse(rTest2.getStatus().equals(Status.SUCCESS_OK)); // Try to replace file by directory ClientResource r2d = new ClientResource(fzr2 + "/"); r2d.put(new EmptyRepresentation()); assertFalse(r2d.getStatus().equals(Status.SUCCESS_OK)); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/connector/RiapTestCase.java0000664000175000017500000001516411757206352030404 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.connector; import java.io.Serializable; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.representation.ObjectRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.test.RestletTestCase; /** * Unit test case for the RIAP Internal routing protocol. * * @author Marc Portier (mpo@outerthought.org) */ public class RiapTestCase extends RestletTestCase { private static final String DEFAULT_MSG = "no-default"; // Just Some Serializable dummy object handle... private static final Serializable JUST_SOME_OBJ = new Serializable() { private static final long serialVersionUID = 1L; }; private static final String ECHO_TEST_MSG = JUST_SOME_OBJ.toString(); private String buildAggregate(String echoMessage, String echoCopy) { return "ORIGINAL: " + echoMessage + "\n" + "ECHOCOPY: " + echoCopy + "\n"; } public void testRiap() throws Exception { final Component comp = new Component(); final Application localOnly = new Application() { @Override public Restlet createInboundRoot() { return new Restlet(getContext()) { @Override public void handle(Request request, Response response) { final String selfBase = "riap://application"; final Reference ref = request.getResourceRef(); final String remainder = ref.getRemainingPart(); Representation result = new StringRepresentation( DEFAULT_MSG); if (remainder.startsWith("/echo/")) { result = new StringRepresentation( remainder.substring(6)); } else if (remainder.equals("/object")) { result = new ObjectRepresentation( JUST_SOME_OBJ); } else if (remainder.equals("/null")) { result = new ObjectRepresentation( (Serializable) null); } else if (remainder.equals("/self-aggregated")) { final String echoMessage = ECHO_TEST_MSG; final Reference echoRef = new LocalReference( selfBase + "/echo/" + echoMessage); String echoCopy = null; try { ClientResource r = new ClientResource(echoRef); echoCopy = r.get().getText(); } catch (Exception e) { e.printStackTrace(); fail("Error getting internal reference to " + echoRef); } assertEquals("expected echoMessage back", echoMessage, echoCopy); result = new StringRepresentation(buildAggregate( echoMessage, echoCopy)); } response.setEntity(result); } }; } }; comp.getInternalRouter().attach("/local", localOnly); String localBase = "riap://component/local"; Client dispatcher = comp.getContext().getClientDispatcher(); String msg = "this%20message"; String echoURI = localBase + "/echo/" + msg; Representation echoRep = dispatcher.handle( new Request(Method.GET, echoURI)).getEntity(); assertEquals("expected echo of uri-remainder", msg, echoRep.getText()); final String objURI = localBase + "/object"; final Representation objRep = dispatcher.handle( new Request(Method.GET, objURI)).getEntity(); assertSame("expected specific test-object", JUST_SOME_OBJ, ((ObjectRepresentation) objRep).getObject()); final String nullURI = localBase + "/null"; final Representation nullRep = dispatcher.handle( new Request(Method.GET, nullURI)).getEntity(); assertNull("expected null", ((ObjectRepresentation) nullRep).getObject()); final String anyURI = localBase + "/whatever"; final Representation anyRep = dispatcher.handle( new Request(Method.GET, anyURI)).getEntity(); assertEquals("expected echo of uri-remainder", DEFAULT_MSG, anyRep.getText()); final String aggURI = localBase + "/self-aggregated"; final Representation aggRep = dispatcher.handle( new Request(Method.GET, aggURI)).getEntity(); final String expectedResult = buildAggregate(ECHO_TEST_MSG, ECHO_TEST_MSG); assertEquals("expected specific aggregated message", expectedResult, aggRep.getText()); dispatcher.stop(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/connector/RestartTestCase.java0000664000175000017500000000425611757206352031135 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.connector; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.test.RestletTestCase; /** * Test the ability of a connector to be restarted. * * @author Jerome Louvel */ public class RestartTestCase extends RestletTestCase { public void testRestart() throws Exception { final int waitTime = 100; final Server connector = new Server(Protocol.HTTP, TEST_PORT, (Restlet) null); System.out.print("Starting connector... "); connector.start(); System.out.println("done"); Thread.sleep(waitTime); System.out.print("Stopping connector... "); connector.stop(); System.out.println("done"); Thread.sleep(waitTime); System.out.print("Restarting connector... "); connector.start(); System.out.println("done"); Thread.sleep(waitTime); connector.stop(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/connector/RiapConnectorsTestCase.java0000664000175000017500000000731411757206352032440 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.connector; import org.restlet.Application; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.routing.Router; import org.restlet.test.RestletTestCase; /** * Unit test case for the RIAP Internal routing protocol. */ public class RiapConnectorsTestCase extends RestletTestCase { /** * Test the RIAP client and server connectors. */ public void testRiapConnectors() { Component component = new Component(); component.getServers().add(Protocol.RIAP); component.getClients().add(Protocol.RIAP); Application app = new Application() { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/testA", new Restlet(getContext()) { @Override public void handle(Request request, Response response) { response.setEntity("hello, world", MediaType.TEXT_PLAIN); } }); router.attach("/testB", new Restlet(getContext()) { public void handle(Request request, Response response) { ClientResource resource = new ClientResource( "riap://component/app/testA"); try { response.setEntity(resource.get().getText(), MediaType.TEXT_PLAIN); } catch (Exception e) { } } }); return router; } }; // Attach the private application component.getInternalRouter().attach("/app", app); try { component.start(); ClientResource res = new ClientResource( "riap://component/app/testA"); Representation rep = res.get(); assertEquals("hello, world", rep.getText()); rep = null; res = new ClientResource("riap://component/app/testB"); rep = res.get(); assertEquals("hello, world", rep.getText()); component.stop(); } catch (Exception e) { fail(e.getMessage()); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/connector/FileClientTestCase.java0000664000175000017500000000532711757206352031527 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.connector; import java.io.File; import java.io.IOException; import org.restlet.data.Language; import org.restlet.data.LocalReference; import org.restlet.data.Status; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Unit test case for the File client connector. * * @author Jerome Louvel */ public class FileClientTestCase extends RestletTestCase { public void testFileClient() throws IOException { String text = "Test content\r\nLine 2\r\nLine2"; LocalReference fr = LocalReference .createFileReference(File.createTempFile("Restlet", ".txt." + Language.DEFAULT.getName())); ClientResource resource = new ClientResource(fr); try { // Update the text of the temporary file resource.put(new StringRepresentation(text)); } catch (ResourceException e) { } assertEquals(Status.SUCCESS_CREATED, resource.getStatus()); try { // Get the text and compare to the original resource.get(); } catch (ResourceException e) { } assertEquals(Status.SUCCESS_OK, resource.getStatus()); try { // Delete the file resource.delete(); } catch (ResourceException e) { } assertEquals(Status.SUCCESS_NO_CONTENT, resource.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/MockFilter.java0000664000175000017500000000441111757206352026113 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.routing.Filter; /** * Thin layer around an AbstractFilter. Takes care about being started and * having a target when it should handle a call. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Lars Heuer (heuer[at]semagia.com) Semagia */ public class MockFilter extends Filter { public MockFilter(Context context) { super(context); } @Override protected int beforeHandle(Request request, Response response) { if (!super.isStarted()) { throw new IllegalStateException("Filter is not started"); } if (!super.hasNext()) { throw new IllegalStateException("Target is not set"); } return CONTINUE; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/TraceRestlet.java0000664000175000017500000000426511757206352026464 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; /** * Trace Restlet. * * @author Jerome Louvel */ public class TraceRestlet extends Restlet { public TraceRestlet(Context context) { super(context); } /** * Handles a uniform call. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { final String message = "Hello World!" + "\nYour IP address is " + request.getClientInfo().getAddress() + "\nYour request URI is: " + ((request.getResourceRef() == null) ? "?" : request .getResourceRef().toString()); response.setEntity(message, MediaType.TEXT_PLAIN); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/CallTestCase.java0000664000175000017500000002122711757206354026371 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import java.util.Arrays; import java.util.List; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ClientInfo; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.http.Call; /** * Test {@link org.restlet.Call}. * * @author Lars Heuer (heuer[at]semagia.com) */ public class CallTestCase extends RestletTestCase { /** * Returns a connector call. * * @return A connector call instance. */ protected Call getCall() { return new Call() { @Override protected boolean isClientKeepAlive() { return false; } @Override protected boolean isServerKeepAlive() { return false; } }; } /** * Returns a reference with the specified URI. * * @param uri * The URI. * @return Reference instance. */ protected Reference getReference(String uri) { return new Reference(uri); } /** * Returns a request. * * @return Request instance. */ protected Request getRequest() { return new Request(); } /** * Returns a response. * * @param request * The associated request. * @return Response instance. */ protected Response getResponse(Request request) { return new Response(request); } /** * Tests context's base reference getting/setting. */ public void testBaseRef() throws Exception { final Request request = getRequest(); final String resourceRefURI = "http://www.restlet.org/path/to/resource"; final Reference resourceRef = getReference(resourceRefURI); request.setResourceRef(resourceRefURI); assertEquals(resourceRef, request.getResourceRef()); String uri = "http://www.restlet.org/path"; Reference reference = getReference(uri); request.getResourceRef().setBaseRef(uri); assertEquals(uri, request.getResourceRef().getBaseRef().toString()); assertEquals(reference, request.getResourceRef().getBaseRef()); uri = "http://www.restlet.org/path/to"; reference = getReference(uri); request.getResourceRef().setBaseRef(uri); assertEquals(uri, request.getResourceRef().getBaseRef().toString()); assertEquals(reference, request.getResourceRef().getBaseRef()); } /** * Tests client address getting/setting. */ public void testClientAddress() throws Exception { final ClientInfo client = getRequest().getClientInfo(); String address = "127.0.0.1"; client.setAddress(address); assertEquals(address, client.getAddress()); assertEquals(0, client.getForwardedAddresses().size()); } /** * Tests client addresses getting/setting. */ public void testClientForwardedAddresses() throws Exception { final ClientInfo client = getRequest().getClientInfo(); String firstAddress = "127.0.0.1"; final String secondAddress = "192.168.99.10"; List addresses = Arrays.asList(new String[] { firstAddress, secondAddress }); client.getForwardedAddresses().addAll(addresses); assertEquals(addresses, client.getForwardedAddresses()); client.getForwardedAddresses().clear(); client.getForwardedAddresses().addAll(addresses); assertEquals(addresses, client.getForwardedAddresses()); } /** * Tests client agent getting/setting. */ public void testClientAgent() throws Exception { final ClientInfo client = getRequest().getClientInfo(); String name = "Restlet"; client.setAgent(name); assertEquals(name, client.getAgent()); name = "Restlet Client"; client.setAgent(name); assertEquals(name, client.getAgent()); } /** * Tests method getting/setting. */ public void testMethod() throws Exception { final Request request = getRequest(); request.setMethod(Method.GET); assertEquals(Method.GET, request.getMethod()); request.setMethod(Method.POST); assertEquals(Method.POST, request.getMethod()); } /** * Tests redirection reference getting/setting. */ public void testRedirectionRef() throws Exception { final Request request = getRequest(); final Response response = getResponse(request); String uri = "http://www.restlet.org/"; Reference reference = getReference(uri); response.setLocationRef(uri); assertEquals(reference, response.getLocationRef()); uri = "http://www.restlet.org/something"; reference = getReference(uri); response.setLocationRef(reference); assertEquals(reference, response.getLocationRef()); } /** * Tests referrer reference getting/setting. */ public void testReferrerRef() throws Exception { final Request request = getRequest(); String uri = "http://www.restlet.org/"; Reference reference = getReference(uri); request.setReferrerRef(uri); assertEquals(reference, request.getReferrerRef()); uri = "http://www.restlet.org/something"; reference = getReference(uri); request.setReferrerRef(reference); assertEquals(reference, request.getReferrerRef()); } /** * Tests resource reference getting/setting. */ public void testResourceRef() throws Exception { final Request request = getRequest(); String uri = "http://www.restlet.org/"; Reference reference = getReference(uri); request.setResourceRef(uri); assertEquals(reference, request.getResourceRef()); uri = "http://www.restlet.org/something"; reference = getReference(uri); request.setResourceRef(reference); assertEquals(reference, request.getResourceRef()); } /** * Tests server address getting/setting. */ public void testServerAddress() throws Exception { final Request request = getRequest(); final Response response = getResponse(request); String address = "127.0.0.1"; response.getServerInfo().setAddress(address); assertEquals(address, response.getServerInfo().getAddress()); address = "192.168.99.10"; response.getServerInfo().setAddress(address); assertEquals(address, response.getServerInfo().getAddress()); } /** * Tests server agent getting/setting. */ public void testServerAgent() throws Exception { final Request request = getRequest(); final Response response = getResponse(request); String name = "Restlet"; response.getServerInfo().setAgent(name); assertEquals(name, response.getServerInfo().getAgent()); name = "Restlet Server"; response.getServerInfo().setAgent(name); assertEquals(name, response.getServerInfo().getAgent()); } /** * Tests status getting/setting. */ public void testStatus() throws Exception { final Request request = getRequest(); final Response response = getResponse(request); response.setStatus(Status.SUCCESS_OK); assertEquals(Status.SUCCESS_OK, response.getStatus()); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, response.getStatus()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/0000775000175000017500000000000011757206354024124 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/CookieTestCase.java0000664000175000017500000000476411757206352027645 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import org.restlet.data.Cookie; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.Cookie}. * * @author Jerome Louvel */ public class CookieTestCase extends RestletTestCase { /** * Equality tests. */ public void testEquals() throws Exception { final Cookie c1 = new Cookie(1, "name1", "value1", "path1", "domain1"); final Cookie c2 = new Cookie(1, "name1", "value1", "path1", "domain1"); assertTrue(c1.equals(c2)); assertTrue(c1.hashCode() == c2.hashCode()); assertEquals(c1, c2); assertTrue(c1.equals(c1)); assertEquals(c1, c1); } /** * Unequality tests. */ public void testUnEquals() throws Exception { Cookie c1 = new Cookie(1, "name1", "value1", "path1", "domain1"); Cookie c2 = new Cookie(2, "name2", "value2", "path2", "domain2"); assertFalse(c1.equals(c2)); assertFalse(c1.hashCode() == c2.hashCode()); assertFalse(c1.equals(null)); assertFalse(c2.equals(null)); c1 = new Cookie(1, "name", "value", "path", "domain"); c2 = new Cookie(2, "name", "value", "path", "domain"); assertFalse(c1.equals(c2)); assertFalse(c1.hashCode() == c2.hashCode()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/AuthenticationInfoTestCase.java0000664000175000017500000001305511757206354032222 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import org.restlet.data.AuthenticationInfo; import org.restlet.engine.security.AuthenticatorUtils; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.Reference}. * * @author Kelly McLaughlin (mclaughlin77[at]gmail.com) */ public class AuthenticationInfoTestCase extends RestletTestCase { /** * Test parsing an Authorization-Info header string. */ public void testAuthenticationInfoHeaderParse() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo("00000002", 1, "MDAzMTAw1", "auth", null); String authInfoHeader = new String( "nc=00000001, qop=auth, cnonce=\"MDAzMTAw1\", nextnonce=00000002"); AuthenticationInfo parsedAuthInfo = AuthenticatorUtils .parseAuthenticationInfo(authInfoHeader); assertTrue(authInfo.equals(parsedAuthInfo)); assertTrue(parsedAuthInfo.equals(authInfo)); } /** * Test cnonce getting/setting. */ public void testCnonce() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo("testnonce", 1111111, "testcnonce", "auth", "FFFFFF"); assertEquals(authInfo.getClientNonce(), "testcnonce"); String newCnonce = new String("newcnonce"); authInfo.setClientNonce(newCnonce); assertEquals(authInfo.getClientNonce(), "newcnonce"); } /** * Equality tests. */ public void testEquals() throws Exception { final AuthenticationInfo authInfo1 = new AuthenticationInfo( "testnonce", 1111111, "testcnonce", "auth", "FFFFFF"); final AuthenticationInfo authInfo2 = new AuthenticationInfo( "testnonce", 1111111, "testcnonce", "auth", "FFFFFF"); assertEquals(authInfo1, authInfo2); assertTrue(authInfo1.equals(authInfo2)); } /** * Test nextnonce getting/setting. */ public void testNextNonce() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo("testnonce", 1111111, "testcnonce", "auth", "FFFFFF"); assertEquals(authInfo.getNextServerNonce(), "testnonce"); String newNonce = new String("newnonce"); authInfo.setNextServerNonce(newNonce); assertEquals(authInfo.getNextServerNonce(), "newnonce"); } /** * Test nonce-count getting/setting. */ public void testNonceCount() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo("testnonce", 1111111, "testcnonce", "auth", "FFFFFF"); assertEquals(authInfo.getNonceCount(), 1111111); int newNonceCount = 2222222; authInfo.setNonceCount(newNonceCount); assertEquals(authInfo.getNonceCount(), 2222222); } /** * Test message-qop getting/setting. */ public void testQop() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo("testnonce", 1111111, "testcnonce", "auth", "FFFFFF"); assertEquals(authInfo.getQuality(), "auth"); String newQop = new String("auth-int"); authInfo.setQuality(newQop); assertEquals(authInfo.getQuality(), "auth-int"); } /** * Test response-auth getting/setting. */ public void testResponseAuth() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo("testnonce", 1111111, "testcnonce", "auth", "FFFFFF"); assertEquals(authInfo.getResponseDigest(), "FFFFFF"); String newResponseAuth = new String("000000"); authInfo.setResponseDigest(newResponseAuth); assertEquals(authInfo.getResponseDigest(), "000000"); } public void testUnEquals() throws Exception { final AuthenticationInfo authInfo1 = new AuthenticationInfo( "testnonce1", 1111111, "testcnonce1", "auth", "FFFFFF"); final AuthenticationInfo authInfo2 = new AuthenticationInfo( "testnonce2", 1111111, "testcnonce2", "auth", "FFFFFF"); assertFalse(authInfo1.equals(authInfo2)); assertFalse(authInfo1.equals(null)); assertFalse(authInfo2.equals(null)); assertFalse(authInfo1.getNextServerNonce().equals( authInfo2.getNextServerNonce())); assertFalse(authInfo1.getClientNonce().equals( authInfo2.getClientNonce())); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/ConnegTestCase.java0000664000175000017500000001100711757206354027633 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import java.util.ArrayList; import java.util.List; import org.restlet.data.ClientInfo; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.representation.Variant; import org.restlet.service.MetadataService; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.ClientInfo} for content negotiation. * * @author Jerome Louvel */ public class ConnegTestCase extends RestletTestCase { MetadataService ms; @Override protected void setUp() throws Exception { super.setUp(); ms = new MetadataService(); } @Override protected void tearDown() throws Exception { ms = null; super.tearDown(); } /** * Conneg tests. */ public void testConneg() throws Exception { ClientInfo ci = new ClientInfo(); ci.getAcceptedLanguages().add( new Preference(Language.ENGLISH_US, 1.0F)); ci.getAcceptedLanguages().add( new Preference(Language.FRENCH_FRANCE, 0.9F)); ci.getAcceptedMediaTypes().add( new Preference(MediaType.TEXT_XML, 1.0F)); List variants = new ArrayList(); variants.add(new Variant(MediaType.TEXT_XML, Language.ENGLISH_US)); variants.add(new Variant(MediaType.TEXT_XML, Language.FRENCH_FRANCE)); Variant pv = ci.getPreferredVariant(variants, ms); assertEquals(MediaType.TEXT_XML, pv.getMediaType()); assertEquals(Language.ENGLISH_US, pv.getLanguages().get(0)); // Leveraging parent languages variants.clear(); variants.add(new Variant(MediaType.TEXT_XML, Language.ENGLISH)); variants.add(new Variant(MediaType.TEXT_XML, Language.FRENCH)); pv = ci.getPreferredVariant(variants, ms); assertEquals(MediaType.TEXT_XML, pv.getMediaType()); assertEquals(Language.ENGLISH, pv.getLanguages().get(0)); // Testing quality priority over parent metadata variants.clear(); variants.add(new Variant(MediaType.TEXT_PLAIN, Language.ENGLISH)); variants.add(new Variant(MediaType.TEXT_XML, Language.FRENCH_FRANCE)); pv = ci.getPreferredVariant(variants, ms); assertEquals(MediaType.TEXT_XML, pv.getMediaType()); assertEquals(Language.FRENCH_FRANCE, pv.getLanguages().get(0)); // Testing quality priority over parent metadata variants.clear(); variants .add(new Variant(MediaType.APPLICATION_XML, Language.ENGLISH_US)); variants.add(new Variant(MediaType.TEXT_XML, Language.FRENCH_FRANCE)); pv = ci.getPreferredVariant(variants, ms); assertEquals(MediaType.TEXT_XML, pv.getMediaType()); assertEquals(Language.FRENCH_FRANCE, pv.getLanguages().get(0)); // Leveraging parent media types variants.clear(); variants .add(new Variant(MediaType.APPLICATION_XML, Language.ENGLISH_US)); variants.add(new Variant(MediaType.APPLICATION_XML, Language.FRENCH_FRANCE)); pv = ci.getPreferredVariant(variants, ms); assertEquals(MediaType.APPLICATION_XML, pv.getMediaType()); assertEquals(Language.ENGLISH_US, pv.getLanguages().get(0)); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/RecipientInfoTestCase.java0000664000175000017500000000765511757206352031174 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import java.util.ArrayList; import java.util.List; import org.restlet.data.Parameter; import org.restlet.data.RecipientInfo; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.RecipientInfoReader; import org.restlet.engine.http.header.RecipientInfoWriter; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.RecipientInfo}. * * @author Jerome Louvel */ public class RecipientInfoTestCase extends RestletTestCase { public void testVia() { Parameter via1a = new Parameter(HeaderConstants.HEADER_VIA, "1.0 fred, 1.1 nowhere.com (Apache/1.1)"); Parameter via1b = new Parameter(HeaderConstants.HEADER_VIA, "HTTP/1.0 fred, HTTP/1.1 nowhere.com (Apache/1.1)"); Parameter via1c = new Parameter(HeaderConstants.HEADER_VIA, "HTTP/1.0 fred (Apache/1.1), HTTP/1.1 nowhere.com"); Parameter via1d = new Parameter(HeaderConstants.HEADER_VIA, "HTTP/1.0 fred (Apache/1.1), HTTP/1.1 nowhere.com:8111"); List recipients = new ArrayList(); RecipientInfoReader.addValues(via1a, recipients); assertEquals(2, recipients.size()); RecipientInfo recipient1 = recipients.get(0); RecipientInfo recipient2 = recipients.get(1); assertEquals("1.0", recipient1.getProtocol().getVersion()); assertEquals("1.1", recipient2.getProtocol().getVersion()); assertEquals("fred", recipient1.getName()); assertEquals("nowhere.com", recipient2.getName()); assertNull(recipient1.getComment()); assertEquals("Apache/1.1", recipient2.getComment()); String header = RecipientInfoWriter.write(recipients); assertEquals(via1b.getValue(), header); recipients = new ArrayList(); RecipientInfoReader.addValues(via1c, recipients); recipient1 = recipients.get(0); recipient2 = recipients.get(1); assertEquals("1.0", recipient1.getProtocol().getVersion()); assertEquals("1.1", recipient2.getProtocol().getVersion()); assertEquals("fred", recipient1.getName()); assertEquals("nowhere.com", recipient2.getName()); assertEquals("Apache/1.1", recipient1.getComment()); assertNull(recipient2.getComment()); recipients = new ArrayList(); RecipientInfoReader.addValues(via1d, recipients); recipient1 = recipients.get(0); recipient2 = recipients.get(1); assertEquals("1.0", recipient1.getProtocol().getVersion()); assertEquals("1.1", recipient2.getProtocol().getVersion()); assertEquals("fred", recipient1.getName()); assertEquals("nowhere.com:8111", recipient2.getName()); assertEquals("Apache/1.1", recipient1.getComment()); assertNull(recipient2.getComment()); header = RecipientInfoWriter.write(recipients); assertEquals(via1d.getValue(), header); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/LanguageTestCase.java0000664000175000017500000000370111757206354030147 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import org.restlet.data.Language; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.Language}. * * @author Jerome Louvel */ public class LanguageTestCase extends RestletTestCase { /** * Testing {@link Language#valueOf(String)} */ public void testValueOf() { assertSame(Language.FRENCH_FRANCE, Language.valueOf("fr-fr")); assertSame(Language.ALL, Language.valueOf("*")); } public void testUnmodifiable() { try { Language.FRENCH_FRANCE.getSubTags().add("foo"); fail("The subtags shouldn't be modifiable"); } catch (UnsupportedOperationException uoe) { // As expected } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/0000775000175000017500000000000011757206354024677 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-uris/0000775000175000017500000000000011757206354030045 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-uris/test001.rdf0000664000175000017500000000213111757206354031737 0ustar jamespagejamespage 2000 restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-uris/test001.nt0000664000175000017500000000100711757206354031606 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/04/29 09:46:57 dbeckett2 Exp $ # ##################################################################### "2000" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-uris/test002.rdf0000664000175000017500000000217611757206354031751 0ustar jamespagejamespage 2000 restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-uris/test002.nt0000664000175000017500000000101111757206354031602 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/04/29 09:46:57 dbeckett2 Exp $ # ##################################################################### "2000" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/0000775000175000017500000000000011757206354032602 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test004.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test004.0000664000175000017500000000114011757206354034002 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test004.nt,v 1.2 2001/10/10 13:10:05 barstow Exp $ # ##################################################################### _:j0 "some value" . _:j0 . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test005.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test005.0000664000175000017500000000142011757206354034004 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test003.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test003.0000664000175000017500000000103411757206354034003 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test003.nt,v 1.2 2001/10/10 13:10:05 barstow Exp $ # ##################################################################### _:j0 . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test001.0000664000175000017500000000151211757206354034002 0ustar jamespagejamespage property value ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test003.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test003.0000664000175000017500000000142011757206354034002 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test005.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test005.0000664000175000017500000000103411757206354034005 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test005.nt,v 1.2 2001/10/10 13:10:05 barstow Exp $ # ##################################################################### _:j0 . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test001.0000664000175000017500000000075011757206354034005 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.2 2001/10/10 13:10:05 barstow Exp $ # ##################################################################### _:j0 "property value" . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test004.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test004.0000664000175000017500000000147211757206354034012 0ustar jamespagejamespage some value ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test002.0000664000175000017500000000147011757206354034006 0ustar jamespagejamespage property value ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test002.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-identity-anon-resources/test002.0000664000175000017500000000107311757206354034005 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.2 2001/10/10 13:10:05 barstow Exp $ # ##################################################################### _:j0 "property value" . _:j0 . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/horst-01/0000775000175000017500000000000011757206354026254 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/horst-01/test001.rdf0000664000175000017500000000175611757206354030162 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/horst-01/test003.rdf0000664000175000017500000000206611757206354030157 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/horst-01/test004.rdf0000664000175000017500000000201711757206354030154 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/horst-01/test002.rdf0000664000175000017500000000200111757206354030143 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/0000775000175000017500000000000011757206354027452 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test004.nt0000664000175000017500000000076511757206354031230 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test004.nt,v 1.2 2002/12/13 11:32:46 jgrant Exp $ # ##################################################################### "chat"@fr . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test007b.nt0000664000175000017500000000076611757206354031376 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test007b.nt,v 1.1 2002/12/18 15:49:29 jgrant Exp $ # ##################################################################### "chat"@en . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test005.rdf0000664000175000017500000000140311757206354031351 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test006.nt0000664000175000017500000000076511757206354031232 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test006.nt,v 1.2 2002/12/13 11:32:46 jgrant Exp $ # ##################################################################### "chat"@fr . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test003.nt0000664000175000017500000000076211757206354031224 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test003.nt,v 1.1 2002/04/05 22:22:30 dajobe Exp $ # ##################################################################### "chat" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test001.rdf0000664000175000017500000000147711757206354031360 0ustar jamespagejamespage chat restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test007a.nt0000664000175000017500000000076611757206354031375 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test007a.nt,v 1.1 2002/12/18 15:49:29 jgrant Exp $ # ##################################################################### "chat"@fr . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test006.rdf0000664000175000017500000000144411757206354031357 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test007c.nt0000664000175000017500000000076311757206354031374 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test007c.nt,v 1.1 2002/12/18 15:49:29 jgrant Exp $ # ##################################################################### "chat" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test003.rdf0000664000175000017500000000142211757206354031350 0ustar jamespagejamespage chat restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test005.nt0000664000175000017500000000076211757206354031226 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test005.nt,v 1.1 2002/04/05 22:22:30 dajobe Exp $ # ##################################################################### "chat" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test001.nt0000664000175000017500000000105311757206354031214 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.2 2002/11/22 11:20:52 jgrant Exp $ # ##################################################################### "chat"^^ . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test004.rdf0000664000175000017500000000144011757206354031351 0ustar jamespagejamespage chat restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test002.rdf0000664000175000017500000000152611757206354031354 0ustar jamespagejamespage chat restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xmllang/test002.nt0000664000175000017500000000105511757206354031217 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.3 2003/07/24 15:51:08 jcarroll Exp $ # ##################################################################### "chat"^^ . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/0000775000175000017500000000000011757206354031364 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0009.rdf0000664000175000017500000000165211757206354033355 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0004.rdf0000664000175000017500000000167711757206354033357 0ustar jamespagejamespage bar restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0013.nt0000664000175000017500000000141211757206354033210 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0013.nt,v 1.3 2001/10/04 16:01:45 barstow Exp $ # ##################################################################### . "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0009.nt0000664000175000017500000000077011757206354033223 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0009.nt,v 1.2 2001/09/06 21:07:19 barstow Exp $ # ##################################################################### "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0001.rdf0000664000175000017500000000173411757206354033346 0ustar jamespagejamespage bar restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0011.nt0000664000175000017500000000141211757206354033206 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0011.nt,v 1.3 2001/10/04 16:01:45 barstow Exp $ # ##################################################################### . "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0005.nt0000664000175000017500000000105211757206354033211 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0005.nt,v 1.2 2001/09/06 21:07:19 barstow Exp $ # ##################################################################### _:genid . _:genid "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0001.nt0000664000175000017500000000077111757206354033214 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0001.nt,v 1.2 2001/09/06 21:07:19 barstow Exp $ # ##################################################################### "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0014.nt0000664000175000017500000000141211757206354033211 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0014.nt,v 1.3 2001/10/04 16:01:45 barstow Exp $ # ##################################################################### . "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0006.rdf0000664000175000017500000000171011757206354033345 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0011.rdf0000664000175000017500000000225711757206354033350 0ustar jamespagejamespage bar restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0014.rdf0000664000175000017500000000234511757206354033351 0ustar jamespagejamespage
  • bar
  • restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0006.nt0000664000175000017500000000104211757206354033211 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0006.nt,v 1.2 2001/09/06 21:07:19 barstow Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0004.nt0000664000175000017500000000106011757206354033207 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0004.nt,v 1.3 2001/10/04 16:01:45 barstow Exp $ # ##################################################################### "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0013.rdf0000664000175000017500000000226211757206354033346 0ustar jamespagejamespage bar restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0012.nt0000664000175000017500000000141211757206354033207 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0012.nt,v 1.3 2001/10/04 16:01:45 barstow Exp $ # ##################################################################### . "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0005.rdf0000664000175000017500000000221711757206354033347 0ustar jamespagejamespage bar restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0012.rdf0000664000175000017500000000225211757206354033344 0ustar jamespagejamespage bar restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0003.nt0000664000175000017500000000102311757206354033205 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0003.nt,v 1.2 2001/09/06 21:07:19 barstow Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0010.nt0000664000175000017500000000077011757206354033213 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test0010.nt,v 1.2 2001/09/06 21:07:19 barstow Exp $ # ##################################################################### "bar" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0010.rdf0000664000175000017500000000223711757206354033345 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-ns-prefix-confusion/test0003.rdf0000664000175000017500000000205111757206354033341 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/Manifest.rdf0000664000175000017500000070174111757206354027154 0ustar jamespagejamespage APPROVED APPROVED The claim that xsd:integer is a subClassOF xsd:decimal is not incompatible with using the intensional semantics for datatypes. APPROVED The claim that xsd:integer is a subClassOF xsd:string is incompatible with using the intensional semantics for datatypes. APPROVED A simple datatype production; a language+datatype production. Simply duplicate the constructs under http://www.w3.org/2000/10/rdf-tests/rdfcore/ntriples/test.nt APPROVED A parser is not required to know about well-formed datatyped literals. APPROVED Without datatype knowledge, a 'badly-formed' datatyped literal cannot be detected. APPROVED With appropriate datatype knowledge, a 'badly-formed' datatyped literal can be detected. APPROVED Demonstrating the semantic equivalence of two lexical forms of the same datatyped value. APPROVED As semantic-equivalence-within-type-1; the entailment works both ways. OBSOLETE This test used to claim: Language attributes on a datatyped literal make them distinct for the purposes of non-datatype-aware entailments. There are no longer language tags on datatyped literals. OBSOLETE This test used to claim: Language attributes on a datatyped literal make them distinct for the purposes of non-datatype-aware entailments. There are no longer language tags on datatyped literals. OBSOLETE Obsoleted: datatyped literals have no language tag. OBSOLETE Obsoleted: datatyped literals have no language tag. OBSOLETE Obsoleted: datatyped literals have no language tag. APPROVED Members of different datatypes may be semantically equivalent. APPROVED Where sufficient DT knowledge is available, a range clash may be detected; the document then contains a contradiction. OBSOLETE Language does not affect the denotation of rdf:XMLLiteral. NOTE that this is a change from previous versions of the spec. Langauge tags do not live on XMLLiterals. APPROVED From decisions listed in http://lists.w3.org/Archives/Public/w3c-rdfcore-wg/2002Oct/0098.html APPROVED From decisions listed in http://lists.w3.org/Archives/Public/w3c-rdfcore-wg/2002Oct/0098.html APPROVED From decisions listed in http://lists.w3.org/Archives/Public/w3c-rdfcore-wg/2002Oct/0098.html APPROVED A plain literal denotes the same thing as its corresponding xsd:string, where one exists. APPROVED rdfs:subClassOf has intensional semantics, not extensional. APPROVED rdfs:subPropertyOf has intensional semantics, not extensional. APPROVED Test that ICEXT(I(rdfs:Literal)) is a subset of LV. APPROVED Does the treatment of literals conform to charmod ? Test for success of legal Normal Form C literal WITHDRAWN Does the treatment of literals conform to charmod ? Test for failure for literal not in Normal Form C This test case has been WITHDRAWN in light of changes to NFC handling in concepts WITHDRAWN Does the treatment of literals conform to charmod ? Test for failure for literal not in Normal Form C This test case has been WITHDRAWN in light of changes to NFC handling in concepts APPROVED A uriref is allowed to match non-US ASCII forms conforming to Unicode Normal Form C. No escaping algorithm is applied. APPROVED A uriref which already has % escaping is permitted. No unescaping algorithm is applied. OBSOLETE Test for failure for uriref not in Normal Form C. APPROVED An international URI ref and its %-escaped form label different nodes in the graph. No model theoretic relationship holds between them. APPROVED An international URI ref and its %-escaped form label different nodes in the graph. No model theoretic relationship holds between them. APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED OBSOLETED APPROVED APPROVED APPROVED APPROVED A surrounding rdf:RDF element is no longer mandatory. OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF OBSOLETE This is again legal RDF APPROVED OBSOLETE APPROVED APPROVED APPROVED APPROVED OBSOLETE rdf:aboutEach no longer valid. OBSOLETE APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED This test shows the treatment of non-ASCII characters in the value of rdf:ID attribute. APPROVED This test shows the treatment of non-ASCII characters in the value of rdf:about attribute. APPROVED The question posed to the RDF WG was: should an RDF document containing multiple rdf:_n properties (with the same n) on an element be rejected as illegal? The WG decided that a parser should accept that case as legal RDF. APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED Like rdfms-empty-property-elements/test001.rdf but with a processing instruction as the only content of the otherwise empty element. APPROVED Like rdfms-empty-property-elements/test001.rdf but with a comment as the only content of the otherwise empty element. APPROVED APPROVED APPROVED APPROVED APPROVED NOT_APPROVED NOT_APPROVED NOT_APPROVED NOT_APPROVED NOT_APPROVED OBSOLETE OBSOLETE OBSOLETE OBSOLETE OBSOLETE OBSOLETE OBSOLETE rdf:bagID is forbidden on property element prop with an rdf:resource or rdf:parseType attribute: the following is in error. OBSOLETE OBSOLETE OBSOLETE Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. One of test010a and test010b SHOULD pass, at least. OBSOLETE Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. OBSOLETE Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. One of test011a and test011b SHOULD pass, at least. OBSOLETE Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. OBSOLETE Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. One of test012a and test012b SHOULD pass, at least. OBSOLETE Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. APPROVED APPROVED OBSOLETE APPROVED APPROVED APPROVED NOT_APPROVED NOT_APPROVED NOT_APPROVED APPROVED The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:bagID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:bagID must match the XML Name production, (as modified by XML Namespaces). APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED allowed with warnings APPROVED allowed with warnings APPROVED allowed with warnings APPROVED APPROVED APPROVED Statement of the MT closure rule. APPROVED Statement of the MT closure rule. APPROVED Statement of the MT closure rule. APPROVED rdf:nodeID can be used to label a blank node. APPROVED rdf:nodeID can be used to label a blank node. These have file scope and are distinct from any unlabelled blank nodes. APPROVED On an rdf:Description or typed node rdf:nodeID behaves similarly to an rdf:about. APPROVED On a property element rdf:nodeID behaves similarly to rdf:resource. APPROVED The value of rdf:nodeID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:nodeID must match the XML Name production, (as modified by XML Namespaces). APPROVED The value of rdf:nodeID must match the XML Name production, (as modified by XML Namespaces). APPROVED Cannot have rdf:nodeID and rdf:ID. APPROVED Cannot have rdf:nodeID and rdf:about. APPROVED Cannot have rdf:nodeID and rdf:resource. APPROVED APPROVED An RDF/XML serlializer is recommended to produce an exception if asked to serialize the following graph since there is no way to represent it in the RDF/XML syntax. An RDF/XML serlializer is recommended to produce an exception if asked to serialize the following graph since there is no way to represent it in the RDF/XML syntax. APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED Plain literals are distinguishable on the basis of language tags. APPROVED Plain literals are distinguishable on the basis of language tags. APPROVED Plain literals are distinguishable on the basis of language tags. APPROVED While it is a superproperty, _:a <rdfs:contains (@@member?)> _:b . does NOT entail _:a <rdf:_n> _:b . for any _n. APPROVED APPROVED NOT_APPROVED NOT_APPROVED NOT_APPROVED Should a property be allowed more than one rdfs:range property? What should the semantics of multiple domain and range properties be? -> Multiple domain and range constraints are permissable and will have conjunctive semantics. test001 describes a property with rdfs:domain the intersection of 2 domains test002 describes a property with rdfs:range the intersection of 2 ranges test003 sample statement test004 entailed description using test001, test002, test003 and the rules for RDF and RDFS entailment (see http://www.w3.org/2000/10/rdf-tests/rdfcore/entailment/ ) APPROVED RDF Semantics defines rdfs:range to have an intensional reading. However, semantic extensions may give an extensional reading to range. The premise/conclusion pair is a non-entailment for RDFS reasoning, but may hold in semantic extensions. APPROVED RDF Semantics defines rdfs:range to have an intensional reading of domain. However, semantic extensions may give an extensional reading to domain. The premise/conclusion pair is a non-entailment for RDFS reasoning, but may hold in semantic extensions. APPROVED Indicating a simple inconsistency drawn from RDFS. RDFS can only produce inconsistencies through badly-formed XMLLiteral datatypes. APPROVED From an inconsistent graph, any entailment can be drawn. This is an example. APPROVED Cycles are permitted in subClassOf; therefore, no error occurs and the following entailment holds trivially. APPROVED Cycles are permitted in subPropertyOf; therefore, no error occurs and the following entailment holds trivially. APPROVED an instance of the Property class may have an rdfs:subClassOf property. the meaning of such a property is defined by the model theory. The wording of the formal resolution is a bit bare, so let me add a few words of explanation. What this means is that a resource can be both a class and a property. This test is encoded as follows: a Property may have a subclass (that is, such an RDF graph is satisfiable) APPROVED The inheritance semantics of the subPropertyOf relationship needs to be clarified. => subProperties inherit conjunctively the domain and range of their superproperties APPROVED RDFCore WG RESOLVED that a reified statement was a stating, not a statement. The following entailment does not, therefore, hold. APPROVED RDFCore WG RESOLVED that a statement does NOT entail its reification. The following entailment does not, therefore, hold. APPROVED RDFCore WG RESOLVED that a reified statement was a stating, not a statement. The following entailment does not, therefore, hold. This is the same as test001, but using RDFS-entailment. APPROVED RDFCore WG RESOLVED that a statement does NOT entail its reification. The following entailment does not, therefore, hold. This is the same as test002, but using RDFS-entailment. APPROVED The case of the language tag is not significant. APPROVED The case of the language tag is not significant. APPROVED APPROVED APPROVED Demonstrating the canonicalisation of XMLLiterals. NOT_APPROVED This test case concerns URIs relative to a non-relative URI scheme base. It's beyond the scope of the WG to deal with this; it has therefore not been approved. APPROVED APPROVED APPROVED APPROVED OBSOLETE This is not valid rdf/xml. The embedding of RDF/XML in other XML formats is beyond the scope of these test cases. Test case withdrawn. APPROVED APPROVED APPROVED APPROVED APPROVED APPROVED WITHDRAWN Test case WITHDRAWN in light of 2396bis APPROVED APPROVED Test output corrected to use correct base URL. NOT_APPROVED This test case is deprecated. The use of mailto: URIs with xml:base is not within the scope of RDFCore's charter to sort out. NOT_APPROVED This test case is deprecated. The use of mailto: URIs with xml:base is not within the scope of RDFCore's charter to sort out. APPROVED A well-formed typed literal is not related to an ill-formed literal. Even if they only differ by whitespace. APPROVED A well-formed typed literal is not related to an ill-formed literal. Even if they only differ by whitespace. APPROVED A simple test for well-formedness of a typed literal. APPROVED An integer with whitespace is ill-formed. restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/0000775000175000017500000000000011757206354032537 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test004.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0040000664000175000017500000000230011757206354033660 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test004.nt,v 1.1 2002/03/08 10:55:13 dajobe Exp $ # ##################################################################### _:j88101 . . _:j88101 . . . ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test005.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0050000664000175000017500000000167411757206354033676 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0010000664000175000017500000000162011757206354033661 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test005.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0050000664000175000017500000000237711757206354033677 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test005.nt,v 1.1 2002/03/08 10:55:13 dajobe Exp $ # ##################################################################### "val" . _:j88106 . . _:j88106 . . . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0010000664000175000017500000000230611757206354033663 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/03/08 10:55:12 dajobe Exp $ # ##################################################################### _:j88091 "val" . _:j88090 _:j88091 . . _:j88090 . . _:j88091 . ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test004.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0040000664000175000017500000000165511757206354033674 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0020000664000175000017500000000170011757206354033661 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test002.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-not-id-and-resource-attr/test0020000664000175000017500000000110011757206354033653 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/03/08 10:55:13 dajobe Exp $ # ##################################################################### "val" . _:j88093 . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/test.xml0000664000175000017500000000000011757206354026366 0ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/0000775000175000017500000000000011757206354033025 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test008.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000101611757206354034065 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### "1" . "1-again" . ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/error001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/error00000664000175000017500000000144411757206354034164 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test004.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000435211757206354034073 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:bar . _:bar "1" . . _:bar . . "1" . _:bar "2"^^ . _:bar _:res . _:res . _:bar _:res2 . . _:bar . . _:res2 . _:res2 "foobar" . ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test006.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000317311757206354034073 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### . "3" . "foobar" . . "2" . "foobar" . "barfoo" . _:bag . ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test003.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000110511757206354034064 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:bar . _:bar "1" . _:bar "2" . ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000142411757206354034070 0ustar jamespagejamespage 1 2 ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test007.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000115711757206354034073 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:d1 _:d2 . _:d2 "1" . _:d2 "2" . _:d1 "2" . ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test006.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000160111757206354034065 0ustar jamespagejamespage barfoo ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test007.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000164211757206354034072 0ustar jamespagejamespage 1 2 2 ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test003.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000153211757206354034070 0ustar jamespagejamespage 1 2 ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000114311757206354034066 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:bag . _:bag "1" . _:bag "2" . ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test008.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000155711757206354034077 0ustar jamespagejamespage 1 1-again ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/error002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/error00000664000175000017500000000160111757206354034157 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test004.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000203211757206354034064 0ustar jamespagejamespage 1 2 ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000234211757206354034070 0ustar jamespagejamespage _1 1 _3 2 ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test002.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-containers-syntax-vs-schema/test000000664000175000017500000000127511757206354034074 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:bag . _:bag "_1" . _:bag "1" . _:bag "_3" . _:bag "2" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/0000775000175000017500000000000011757206354030456 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-023.rdf0000664000175000017500000000144411757206354032437 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-017.rdf0000664000175000017500000000143411757206354032441 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-035.nt0000664000175000017500000000013511757206354032304 0ustar jamespagejamespage "string" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-020.rdf0000664000175000017500000000145011757206354032431 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-015.rdf0000664000175000017500000000144311757206354032611 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-017.nt0000664000175000017500000000015111757206354032302 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-036.rdf0000664000175000017500000000136311757206354032443 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-037.rdf0000664000175000017500000000135311757206354032443 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-007.rdf0000664000175000017500000000125111757206354032607 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-028.nt0000664000175000017500000000015311757206354032306 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-011.nt0000664000175000017500000000020011757206354032267 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/warn-001.nt0000664000175000017500000000017711757206354032273 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-028.rdf0000664000175000017500000000144011757206354032440 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-019.rdf0000664000175000017500000000143411757206354032443 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-013.rdf0000664000175000017500000000131011757206354032426 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-005.rdf0000664000175000017500000000125711757206354032613 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-026.rdf0000664000175000017500000000143611757206354032443 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-011.rdf0000664000175000017500000000145711757206354032612 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-017.rdf0000664000175000017500000000145111757206354032612 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/warn-001.rdf0000664000175000017500000000132211757206354032416 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-016.rdf0000664000175000017500000000130411757206354032434 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-002.rdf0000664000175000017500000000124111757206354032601 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-030.nt0000664000175000017500000000015011757206354032274 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-006.rdf0000664000175000017500000000125511757206354032612 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-021.rdf0000664000175000017500000000144611757206354032437 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-018.nt0000664000175000017500000000015111757206354032303 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-008.rdf0000664000175000017500000000124111757206354032607 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-020.nt0000664000175000017500000000015711757206354032302 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-005.rdf0000664000175000017500000000132011757206354032430 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-012.rdf0000664000175000017500000000131011757206354032425 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-002.rdf0000664000175000017500000000130411757206354032427 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-011.rdf0000664000175000017500000000130611757206354032431 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-019.nt0000664000175000017500000000015111757206354032304 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-014.nt0000664000175000017500000000020011757206354032272 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-010.nt0000664000175000017500000000020211757206354032270 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-010.rdf0000664000175000017500000000131211757206354032425 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-007.rdf0000664000175000017500000000130611757206354032436 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-022.nt0000664000175000017500000000015211757206354032277 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-031.nt0000664000175000017500000000015011757206354032275 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-030.rdf0000664000175000017500000000143211757206354032432 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-009.rdf0000664000175000017500000000132011757206354032434 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-018.rdf0000664000175000017500000000144511757206354032616 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/warn-003.rdf0000664000175000017500000000136711757206354032431 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-015.rdf0000664000175000017500000000130211757206354032431 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/warn-002.rdf0000664000175000017500000000145211757206354032423 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-009.rdf0000664000175000017500000000125711757206354032617 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-004.rdf0000664000175000017500000000130411757206354032431 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-032.nt0000664000175000017500000000012711757206354032302 0ustar jamespagejamespage "string" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-026.nt0000664000175000017500000000015211757206354032303 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-007.nt0000664000175000017500000000020011757206354032274 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-009.nt0000664000175000017500000000020511757206354032303 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-003.rdf0000664000175000017500000000124711757206354032610 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-036.nt0000664000175000017500000000013411757206354032304 0ustar jamespagejamespage "string" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-025.rdf0000664000175000017500000000144211757206354032437 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-012.nt0000664000175000017500000000020111757206354032271 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-029.nt0000664000175000017500000000015211757206354032306 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-033.nt0000664000175000017500000000012711757206354032303 0ustar jamespagejamespage "string" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-034.nt0000664000175000017500000000012711757206354032304 0ustar jamespagejamespage "string" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-003.rdf0000664000175000017500000000130411757206354032430 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-008.rdf0000664000175000017500000000131411757206354032436 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-004.rdf0000664000175000017500000000124711757206354032611 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-027.nt0000664000175000017500000000015311757206354032305 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-022.rdf0000664000175000017500000000143611757206354032437 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-006.nt0000664000175000017500000000020411757206354032277 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-016.nt0000664000175000017500000000017711757206354032311 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-003.nt0000664000175000017500000000017711757206354032305 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-027.rdf0000664000175000017500000000144011757206354032437 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-005.nt0000664000175000017500000000020511757206354032277 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/warn-002.nt0000664000175000017500000000015111757206354032264 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-024.nt0000664000175000017500000000015711757206354032306 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-023.nt0000664000175000017500000000015511757206354032303 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-034.rdf0000664000175000017500000000135111757206354032436 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-001.nt0000664000175000017500000000004311757206354032273 0ustar jamespagejamespage# Empty - no triples are generated restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-016.rdf0000664000175000017500000000145311757206354032613 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-012.rdf0000664000175000017500000000143711757206354032611 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-024.rdf0000664000175000017500000000145011757206354032435 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-032.rdf0000664000175000017500000000135111757206354032434 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-031.rdf0000664000175000017500000000143211757206354032433 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-029.rdf0000664000175000017500000000143611757206354032446 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-019.rdf0000664000175000017500000000145311757206354032616 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-025.nt0000664000175000017500000000015411757206354032304 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-008.nt0000664000175000017500000000020311757206354032300 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-002.nt0000664000175000017500000000017711757206354032304 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-014.rdf0000664000175000017500000000144311757206354032610 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-001.rdf0000664000175000017500000000132411757206354032430 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-013.rdf0000664000175000017500000000143511757206354032610 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-010.rdf0000664000175000017500000000127311757206354032605 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-021.nt0000664000175000017500000000015611757206354032302 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-015.nt0000664000175000017500000000017611757206354032307 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-018.rdf0000664000175000017500000000143411757206354032442 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-013.nt0000664000175000017500000000020111757206354032272 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/warn-003.nt0000664000175000017500000000012711757206354032270 0ustar jamespagejamespage "string" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-001.rdf0000664000175000017500000000124311757206354032602 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-004.nt0000664000175000017500000000017711757206354032306 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-037.nt0000664000175000017500000000013011757206354032301 0ustar jamespagejamespage "string" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-014.rdf0000664000175000017500000000130611757206354032434 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-006.rdf0000664000175000017500000000131611757206354032436 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/error-020.rdf0000664000175000017500000000146711757206354032613 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-035.rdf0000664000175000017500000000136511757206354032444 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-names-use/test-033.rdf0000664000175000017500000000135111757206354032435 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/unrecognised-xml-attributes/0000775000175000017500000000000011757206354032346 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/unrecognised-xml-attributes/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/unrecognised-xml-attributes/test001.rd0000664000175000017500000000161311757206354034076 0ustar jamespagejamespage blah more restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/unrecognised-xml-attributes/test001.nt0000664000175000017500000000106711757206354034115 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/04/13 13:30:00 jgrant Exp $ ################################################################## "blah" . "more" . ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/unrecognised-xml-attributes/test002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/unrecognised-xml-attributes/test002.rd0000664000175000017500000000173611757206354034105 0ustar jamespagejamespage stuff restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/unrecognised-xml-attributes/test002.nt0000664000175000017500000000076211757206354034117 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/04/13 13:30:00 jgrant Exp $ ################################################################## "stuff" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/0000775000175000017500000000000011757206354031640 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/test004.nt0000664000175000017500000000110511757206354033403 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test004.nt,v 1.1 2002/12/13 16:48:04 jgrant Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/test001.rdf0000664000175000017500000000211411757206354033533 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/test003a.nt0000664000175000017500000000102111757206354033540 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test003a.nt,v 1.1 2002/12/13 16:48:03 jgrant Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/empty.nt0000664000175000017500000000065611757206354033350 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: empty.nt,v 1.1 2002/12/13 16:48:03 jgrant Exp $ # ##################################################################### restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/test001.nt0000664000175000017500000000162311757206354033405 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.2 2003/07/24 15:51:04 jcarroll Exp $ # ##################################################################### _:a0 . _:a0 _:a1 . _:a1 . _:a1 _:a2 . _:a2 . _:a2 . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/test003b.nt0000664000175000017500000000101711757206354033546 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test003b.nt,v 1.1 2002/12/13 16:48:03 jgrant Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-seq-representation/test002.nt0000664000175000017500000000112711757206354033405 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/12/13 16:48:03 jgrant Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/0000775000175000017500000000000011757206354027155 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/error001.rdf0000664000175000017500000000115411757206354031225 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/error005.rdf0000664000175000017500000000144211757206354031231 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/error003.rdf0000664000175000017500000000126011757206354031225 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/error004.rdf0000664000175000017500000000123211757206354031225 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/error002.rdf0000664000175000017500000000114511757206354031226 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/error006.rdf0000664000175000017500000000116211757206354031231 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-rdf-id/error007.rdf0000664000175000017500000000126611757206354031237 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/0000775000175000017500000000000011757206354032357 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test001.r0000664000175000017500000000175711757206354033754 0ustar jamespagejamespage John ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test001.n0000664000175000017500000000136711757206354033745 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/11/22 13:59:59 jcarroll Exp $ ################################################################## "\n \n John\n \n "^^ . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test002.r0000664000175000017500000000222111757206354033740 0ustar jamespagejamespage Ramifications of a b 2 to World Peace David Hume ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test002.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-xml-literal-namespaces/test002.n0000664000175000017500000000163711757206354033746 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/11/22 13:59:59 jcarroll Exp $ ################################################################## "\n Ramifications of\n \n \n \n\t\n\ta\n\tb\n \n 2\n \n to World Peace\n "^^ . "David Hume" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xml-canon/0000775000175000017500000000000011757206354026573 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xml-canon/test001.rdf0000664000175000017500000000127411757206354030474 0ustar jamespagejamespage
    restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xml-canon/test001.nt0000664000175000017500000000115511757206354030340 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # Semantic equivalence between members of different datatypes. # # $Id: test001.nt,v 1.1 2003/08/18 10:09:29 jgrant Exp $ # ##################################################################### "

    "^^ . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-duplicate-member-props/0000775000175000017500000000000011757206354032370 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-duplicate-member-props/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-duplicate-member-props/test001.r0000664000175000017500000000176311757206354033762 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-duplicate-member-props/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-duplicate-member-props/test001.n0000664000175000017500000000136411757206354033753 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/05/08 13:37:09 jgrant Exp $ # ##################################################################### . . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-uri-substructure/0000775000175000017500000000000011757206354031357 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-uri-substructure/test001.rdf0000664000175000017500000000124611757206354033257 0ustar jamespagejamespage 10 restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-uri-substructure/test001.nt0000664000175000017500000000100511757206354033116 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/03/29 15:09:58 bmcbride Exp $ # # Input file for a serialization test # ##################################################################### _:a "10" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-uri-substructure/error001.nt0000664000175000017500000000121311757206354033271 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: error001.nt,v 1.2 2002/04/08 13:21:38 bmcbride Exp $ # # An RDF/XML serlializer is recommended to produce an exception if # asked to serialize the following graph since there is no way # to represent it in the RDF/XML syntax. # ##################################################################### _:a "10" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/0000775000175000017500000000000011757206354031473 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/error001.rdf0000664000175000017500000000116411757206354033544 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test004.nt0000664000175000017500000000225111757206354033241 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test004.nt,v 1.1 2002/07/30 09:46:05 jcarroll Exp $ # ##################################################################### _:j0 _:j1A . . _:j0 . . _:j1A . _:j2 _:j1A . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test003.nt0000664000175000017500000000074511757206354033246 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test003.nt,v 1.2 2003/07/24 15:51:06 jcarroll Exp $ # ##################################################################### _:j0A "value" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/error005.rdf0000664000175000017500000000111611757206354033545 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test001.rdf0000664000175000017500000000122311757206354033366 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test003.rdf0000664000175000017500000000132111757206354033367 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test001.nt0000664000175000017500000000073511757206354033243 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/07/30 09:46:05 jcarroll Exp $ # ##################################################################### _:j0 _:j0 . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/error003.rdf0000664000175000017500000000127011757206354033544 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/error004.rdf0000664000175000017500000000106711757206354033551 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/error002.rdf0000664000175000017500000000116011757206354033541 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test004.rdf0000664000175000017500000000154411757206354033377 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test002.rdf0000664000175000017500000000170711757206354033376 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/error006.rdf0000664000175000017500000000124311757206354033547 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-syntax-incomplete/test002.nt0000664000175000017500000000107411757206354033241 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/07/30 09:46:05 jcarroll Exp $ # ##################################################################### _:j0A _:j0A . _:j2 _:j1B . _:j1B _:j0A . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-para196/0000775000175000017500000000000011757206354027173 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-para196/test001.rdf0000664000175000017500000000232511757206354031072 0ustar jamespagejamespage permitted also permitted this one also permitted restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-para196/test001.nt0000664000175000017500000000126711757206354030744 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/02/14 19:10:34 dajobe Exp $ # ##################################################################### "permitted" . "also permitted" . "this one also permitted" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-element-not-mandatory/0000775000175000017500000000000011757206354031673 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-element-not-mandatory/test001.rdf0000664000175000017500000000054111757206354033570 0ustar jamespagejamespage Dogs in Hats restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-element-not-mandatory/test001.nt0000664000175000017500000000057611757206354033446 0ustar jamespagejamespage# # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2003/10/08 13:00:58 jgrant Exp $ # ##################################################################### _:a . _:a "Dogs in Hats" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/statement-entailment/0000775000175000017500000000000011757206354031041 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/statement-entailment/test001a.nt0000664000175000017500000000200111757206354032736 0ustar jamespagejamespage . . . . . . . . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/statement-entailment/test001b.nt0000664000175000017500000000012511757206354032744 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/statement-entailment/test002a.nt0000664000175000017500000000012011757206354032737 0ustar jamespagejamespage . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/statement-entailment/test002b.nt0000664000175000017500000000055711757206354032756 0ustar jamespagejamespage_:r . _:r . _:r . _:r . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/pfps-10/0000775000175000017500000000000011757206354026065 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/pfps-10/test001a.nt0000664000175000017500000000075111757206354027774 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001a.nt,v 1.1 2003/08/18 09:40:01 jgrant Exp $ # ##################################################################### "a" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/pfps-10/test001b.nt0000664000175000017500000000112011757206354027764 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001b.nt,v 1.1 2003/08/18 09:40:01 jgrant Exp $ # ##################################################################### _:x . _:x . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-subPropertyOf-semantics/0000775000175000017500000000000011757206354032442 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-subPropertyOf-semantics/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-subPropertyOf-semantics/test001.n0000664000175000017500000000255511757206354034030 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # Issue rdfs-subPropertyOf-semantics: # The inheritance semantics of the subPropertyOf relationship needs to be clarified. # # => subProperties inherit conjunctively the domain and range of their superproperties # # $Id: test001.nt,v 1.4 2002/04/05 13:25:37 josderoo Exp $ ################################################################## . . . . . . . ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-subPropertyOf-semantics/test002.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-subPropertyOf-semantics/test002.n0000664000175000017500000000210511757206354034020 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # Issue rdfs-subPropertyOf-semantics: # The inheritance semantics of the subPropertyOf relationship needs to be clarified. # # => subProperties inherit conjunctively the domain and range of their superproperties # # $Id: test002.nt,v 1.2 2002/04/05 13:25:45 josderoo Exp $ ################################################################## . . . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-abouteach/0000775000175000017500000000000011757206354027743 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-abouteach/error001.rdf0000664000175000017500000000165611757206354032022 0ustar jamespagejamespage me restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-abouteach/error002.rdf0000664000175000017500000000173511757206354032021 0ustar jamespagejamespage foo me restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/tex-01/0000775000175000017500000000000011757206354025715 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/tex-01/test001.rdf0000664000175000017500000000136711757206354027621 0ustar jamespagejamespage a restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/tex-01/test002.rdf0000664000175000017500000000136411757206354027617 0ustar jamespagejamespage a restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/0000775000175000017500000000000011757206354026332 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test008.nt0000664000175000017500000000103511757206354030103 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test008.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test004.nt0000664000175000017500000000163011757206354030100 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test004.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### _:j0 "v" . . _:j0 . . "v" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test011.rdf0000664000175000017500000000136411757206354030234 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test006.nt0000664000175000017500000000114111757206354030077 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test006.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### "v" . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test003.nt0000664000175000017500000000104011757206354030072 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test003.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test013.rdf0000664000175000017500000000143311757206354030233 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test001.rdf0000664000175000017500000000134611757206354030233 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test013.nt0000664000175000017500000000117511757206354030104 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test013.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test010.rdf0000664000175000017500000000132211757206354030225 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test007.nt0000664000175000017500000000103411757206354030101 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test007.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test009.rdf0000664000175000017500000000130211757206354030233 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test006.rdf0000664000175000017500000000135611757206354030241 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test011.nt0000664000175000017500000000103411757206354030074 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test011.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test010.nt0000664000175000017500000000104411757206354030074 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test010.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test014.rdf0000664000175000017500000000147211757206354030237 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test007.rdf0000664000175000017500000000126011757206354030234 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test003.rdf0000664000175000017500000000126511757206354030235 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test014.nt0000664000175000017500000000113511757206354030101 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test014.nt,v 1.2 2002/11/15 11:45:42 jgrant Exp $ # ##################################################################### "v" . "v" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test001.nt0000664000175000017500000000076411757206354030104 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### "v" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test008.rdf0000664000175000017500000000126111757206354030236 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test004.rdf0000664000175000017500000000135311757206354030234 0ustar jamespagejamespage v restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test009.nt0000664000175000017500000000103411757206354030103 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test009.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test002.rdf0000664000175000017500000000134611757206354030234 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlbase/test002.nt0000664000175000017500000000076411757206354030105 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/03/08 12:21:41 dajobe Exp $ # ##################################################################### _:j0 . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subClassOf/0000775000175000017500000000000011757206354032175 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subClassOf/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subClassOf/test001.r0000664000175000017500000000256211757206354033565 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subClassOf/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subClassOf/test001.n0000664000175000017500000000206411757206354033556 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # Author: Dan Connolly # # $Id: test001.nt,v 1.3 2001/10/01 13:45:20 barstow Exp $ # . . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/datatypes/0000775000175000017500000000000011757206354026675 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/datatypes/test001.rdf0000664000175000017500000000165111757206354030575 0ustar jamespagejamespage 10 10 restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/datatypes/test001.nt0000664000175000017500000000117211757206354030441 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.3 2003/08/18 09:29:18 jgrant Exp $ # ##################################################################### "10"^^ . "10"^^ . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/datatypes/test002.rdf0000664000175000017500000000136411757206354030577 0ustar jamespagejamespage flargh restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/datatypes/test002.nt0000664000175000017500000000103111757206354030434 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2002/11/19 14:04:16 jgrant Exp $ # ##################################################################### "flargh"^^ . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/0000775000175000017500000000000011757206354030734 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/premises006.rdf0000664000175000017500000000164011757206354033507 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/test001.rdf0000664000175000017500000000152611757206354032635 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/premises005.rdf0000664000175000017500000000163611757206354033513 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/test001.nt0000664000175000017500000000142011757206354032474 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.5 2001/10/17 08:19:32 josderoo Exp $ ################################################################## . . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/test002.rdf0000664000175000017500000000152211757206354032632 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/nonconclusions006.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/nonconclusions000000664000175000017500000000153411757206354034074 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/nonconclusions005.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/nonconclusions000000664000175000017500000000153211757206354034072 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-domain-and-range/test002.nt0000664000175000017500000000141011757206354032474 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.5 2001/10/17 08:21:13 josderoo Exp $ ################################################################## . . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-entailment/0000775000175000017500000000000011757206354027773 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-entailment/test001.nt0000664000175000017500000000124511757206354031540 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2003/11/13 10:21:45 jgrant Exp $ # ##################################################################### . "<"^^ . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-entailment/test002.nt0000664000175000017500000000111211757206354031532 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test002.nt,v 1.1 2003/11/13 10:21:45 jgrant Exp $ # ##################################################################### . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-reification-required/0000775000175000017500000000000011757206354032122 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-reification-required/test001.rdf0000664000175000017500000000141211757206354034015 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-reification-required/test001.nt0000664000175000017500000000075311757206354033672 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.3 2002/04/05 11:32:03 bmcbride Exp $ # ##################################################################### "10" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000775000175000017500000000000011757206354033673 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/test2.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000664000175000017500000000126311757206354033677 0ustar jamespagejamespage abc ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/test1.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000664000175000017500000000120011757206354033666 0ustar jamespagejamespage abc ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/error1.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000664000175000017500000000140711757206354033677 0ustar jamespagejamespage abc abc ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/test2.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000664000175000017500000000112511757206354033674 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test2.nt,v 1.4 2002/07/26 04:06:56 jcarroll Exp $ # ##################################################################### "abc" . ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/test3.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000664000175000017500000000112511757206354033674 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test3.nt,v 1.1 2002/07/26 04:06:57 jcarroll Exp $ # ##################################################################### "abc" . ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/test3.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000664000175000017500000000127011757206354033675 0ustar jamespagejamespage abc ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/test1.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-difference-between-ID-and-about/0000664000175000017500000000111511757206354033673 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test1.nt,v 1.2 2001/09/06 21:07:20 barstow Exp $ # ##################################################################### "abc" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlsch-02/0000775000175000017500000000000011757206354026414 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlsch-02/test001.rdf0000664000175000017500000000157211757206354030316 0ustar jamespagejamespage 3 10 restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlsch-02/test003.rdf0000664000175000017500000000153211757206354030314 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlsch-02/test001.nt0000664000175000017500000000157211757206354030164 0ustar jamespagejamespage 3 10 restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/xmlsch-02/test002.rdf0000664000175000017500000000151611757206354030315 0ustar jamespagejamespage 3 restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subPropertyOf/0000775000175000017500000000000011757206354032754 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subPropertyOf/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subPropertyOf/test000000664000175000017500000000270611757206354034023 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subPropertyOf/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-no-cycles-in-subPropertyOf/test000000664000175000017500000000211311757206354034013 0ustar jamespagejamespage# Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # Author: Frank Manola # # $Id: test001.nt,v 1.3 2001/10/01 13:43:50 barstow Exp $ # . . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-subClassOf-a-Property/0000775000175000017500000000000011757206354031737 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-subClassOf-a-Property/test001.nt0000664000175000017500000000130011757206354033474 0ustar jamespagejamespage# Copyright World Wide Web Consortium (Massachusetts Institute of # Technology Institut National de Recherche en Informatique et en # Automatique Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # The following graph is legal (satisfiable) # # $Id: test001.nt,v 1.1 2002/12/18 15:44:22 jgrant Exp $ ################################################################## . . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/0000775000175000017500000000000011757206354032642 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test008.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test008.0000664000175000017500000000071311757206354034053 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### "" . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test015.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test015.0000664000175000017500000000206411757206354034052 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test016.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test016.0000664000175000017500000000152711757206354034056 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/error001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/error0010000664000175000017500000000164011757206354034140 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test004.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test004.0000664000175000017500000000071511757206354034051 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:a1 . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test011.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test011.0000664000175000017500000000137411757206354034051 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test005.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test005.0000664000175000017500000000142711757206354034053 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test006.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test006.0000664000175000017500000000223211757206354034047 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:a1 . . . . _:a1 . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test003.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test003.0000664000175000017500000000100411757206354034040 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### ""^^ . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test013.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test013.0000664000175000017500000000164311757206354034052 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test001.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test001.0000664000175000017500000000145211757206354034045 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test013.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test013.0000664000175000017500000000105711757206354034051 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### . "baz" . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test010.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test010.0000664000175000017500000000140411757206354034042 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test007.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test007.0000664000175000017500000000074711757206354034061 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test009.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test009.0000664000175000017500000000140411757206354034052 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test006.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test006.0000664000175000017500000000146611757206354034057 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test011.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test011.0000664000175000017500000000222611757206354034046 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### "" . . . . "" . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test010.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test010.0000664000175000017500000000071511757206354034046 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:a1 . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test014.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test014.0000664000175000017500000000155711757206354034057 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test007.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test007.0000664000175000017500000000143011757206354034047 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test003.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test003.0000664000175000017500000000143011757206354034043 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test014.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test014.0000664000175000017500000000077311757206354034056 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:a1 . _:a1 "baz" . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test005.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test005.0000664000175000017500000000222611757206354034051 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### "" . . . . "" . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test015.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test015.0000664000175000017500000000077311757206354034057 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:a1 . _:a1 "baz" . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test017.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test017.0000664000175000017500000000103311757206354034047 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test017.nt,v 1.1 2002/07/26 04:26:56 jcarroll Exp $ # ##################################################################### . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test001.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test001.0000664000175000017500000000074711757206354034053 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### . ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/error003.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/error0030000664000175000017500000000207111757206354034141 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test008.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test008.0000664000175000017500000000135311757206354034054 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test017.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test017.0000664000175000017500000000201711757206354034052 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test012.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test012.0000664000175000017500000000142511757206354034047 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/error002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/error0020000664000175000017500000000166411757206354034147 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test012.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test012.0000664000175000017500000000223211757206354034044 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### _:a1 . . . . _:a1 . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test004.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test004.0000664000175000017500000000150111757206354034043 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test009.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test009.0000664000175000017500000000100411757206354034046 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### ""^^ . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test016.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test016.0000664000175000017500000000103311757206354034046 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test016.nt,v 1.1 2002/07/26 04:26:56 jcarroll Exp $ # ##################################################################### . ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test002.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test002.0000664000175000017500000000135311757206354034046 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test002.ntrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfms-empty-property-elements/test002.0000664000175000017500000000071311757206354034045 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id$ # ##################################################################### "" . ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-container-membership-superProperty/restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-container-membership-superPropert0000775000175000017500000000000011757206354034377 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-container-membership-superProperty/not1P.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-container-membership-superPropert0000664000175000017500000000074311757206354034405 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-container-membership-superProperty/not1C.rdfrestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdfs-container-membership-superPropert0000664000175000017500000000064711757206354034410 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-literals/0000775000175000017500000000000011757206354030702 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-literals/test001.rdf0000664000175000017500000000201411757206354032574 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/rdf-charmod-literals/test001.nt0000664000175000017500000000106211757206354032444 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # $Id: test001.nt,v 1.1 2002/04/29 10:35:03 jgrant Exp $ # ##################################################################### _:a "D\u00FCrst" . _:a . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/amp-in-url/0000775000175000017500000000000011757206354026660 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/amp-in-url/test001.rdf0000664000175000017500000000260411757206354030557 0ustar jamespagejamespage xxx restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/rdf/amp-in-url/test001.nt0000664000175000017500000000104511757206354030423 0ustar jamespagejamespage# # Copyright World Wide Web Consortium, (Massachusetts Institute of # Technology, Institut National de Recherche en Informatique et en # Automatique, Keio University). # # All Rights Reserved. # # Please see the full Copyright clause at # # # Author: Dan Connolly # # $Id: test001.nt,v 1.2 2001/09/06 21:07:19 barstow Exp $ # ##################################################################### "xxx" . restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/MediaTypeTestCase.java0000664000175000017500000002665011757206352030313 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.test.RestletTestCase; import org.restlet.util.Series; /** * Test {@link org.restlet.data.MediaType}. * * @author Jerome Louvel */ public class MediaTypeTestCase extends RestletTestCase { protected final static String DEFAULT_SCHEME = "http"; protected final static String DEFAULT_SCHEMEPART = "//"; /** * Makes sure that a {@link MediaType} instance initialized on the specified * name has the expected values. * * @param name * type to analyze. * @param main * expected main type. * @param sub * expected subtype. * @param concrete * expected 'concrete' flag. */ public void assertMediaType(String name, String main, String sub, boolean concrete) { MediaType type; type = new MediaType(name); assertEquals(main, type.getMainType()); assertEquals(sub, type.getSubType()); assertEquals(concrete, type.isConcrete()); } /** * Makes sure concrete types are properly initialized. */ public void testConcrete() { assertMediaType("application/xml", "application", "xml", true); assertMediaType("application/ xml ", "application", "xml", true); assertMediaType(" application /xml", "application", "xml", true); assertMediaType(" application / xml ", "application", "xml", true); assertMediaType("application/atom+xml;type=entry", "application", "atom+xml", true); } /** * Makes sure concrete types are properly initialized. */ public void testParameters() { MediaType mt = MediaType.valueOf("application/atom+xml;type=entry"); assertEquals("entry", mt.getParameters().getFirstValue("type")); mt = MediaType .valueOf("multipart/x-mixed-replace; boundary=\"My boundary\""); assertEquals("\"My boundary\"", mt.getParameters().getFirstValue( "boundary")); } /** * Equality tests. */ public void testEquals() throws Exception { MediaType mt1 = new MediaType("application/xml"); MediaType mt2 = MediaType.APPLICATION_XML; assertTrue(mt1.equals(mt2)); assertEquals(mt1, mt2); final Series mediaParams1 = new Form(); mediaParams1.add(new Parameter("charset", "ISO-8859-1")); final MediaType mt1Bis = new MediaType("application/xml", mediaParams1); final Series mediaParams2 = new Form(); mediaParams2.add(new Parameter("charset", "ISO-8859-1")); final MediaType mt2Bis = new MediaType("application/xml", mediaParams2); final Series mediaParams3 = new Form(); mediaParams3.add(new Parameter("charset", "ISO-8859-15")); final MediaType mt3 = new MediaType("application/xml", mediaParams3); assertTrue(mt1Bis.equals(mt2Bis)); assertEquals(mt1, mt2); assertTrue(mt1Bis.equals(mt1, true)); assertTrue(mt1Bis.equals(mt2, true)); assertTrue(mt1Bis.equals(mt3, true)); mt1 = new MediaType("application/*"); mt2 = MediaType.APPLICATION_ALL; assertTrue(mt1.equals(mt2)); assertEquals(mt1, mt2); } /** * Test inclusion. */ public void testIncludes() throws Exception { MediaType mt1 = MediaType.APPLICATION_ALL; MediaType mt2 = MediaType.APPLICATION_XML; assertTrue(mt1.includes(mt1)); assertTrue(mt2.includes(mt2)); assertTrue(mt1.includes(mt2)); assertFalse(mt2.includes(mt1)); mt1 = MediaType.APPLICATION_ALL_XML; mt2 = MediaType.APPLICATION_XML; assertTrue(mt1.includes(mt1)); assertTrue(mt2.includes(mt2)); assertTrue(mt1.includes(mt2)); assertFalse(mt2.includes(mt1)); mt1 = MediaType.APPLICATION_ALL_XML; mt2 = MediaType.APPLICATION_ATOMPUB_SERVICE; assertTrue(mt1.includes(mt1)); assertTrue(mt2.includes(mt2)); assertTrue(mt1.includes(mt2)); assertFalse(mt2.includes(mt1)); assertFalse(mt1.includes(null)); } public void testMostSpecificMediaType() { assertEquals(MediaType.TEXT_ALL, MediaType.getMostSpecific( MediaType.ALL, MediaType.TEXT_ALL)); assertEquals(MediaType.TEXT_ALL, MediaType.getMostSpecific( MediaType.TEXT_ALL, MediaType.ALL)); assertEquals(MediaType.TEXT_PLAIN, MediaType.getMostSpecific( MediaType.ALL, MediaType.TEXT_ALL, MediaType.TEXT_PLAIN)); assertEquals(MediaType.TEXT_PLAIN, MediaType.getMostSpecific( MediaType.ALL, MediaType.TEXT_PLAIN, MediaType.TEXT_ALL)); assertEquals(MediaType.TEXT_PLAIN, MediaType.getMostSpecific( MediaType.TEXT_ALL, MediaType.ALL, MediaType.TEXT_PLAIN)); assertEquals(MediaType.TEXT_PLAIN, MediaType.getMostSpecific( MediaType.TEXT_ALL, MediaType.TEXT_PLAIN, MediaType.ALL)); assertEquals(MediaType.TEXT_PLAIN, MediaType.getMostSpecific( MediaType.TEXT_PLAIN, MediaType.ALL, MediaType.TEXT_ALL)); assertEquals(MediaType.TEXT_PLAIN, MediaType.getMostSpecific( MediaType.TEXT_PLAIN, MediaType.TEXT_ALL, MediaType.ALL)); } /** * Makes sure that 'abstract' types are properly initialised. */ public void testNotConcrete() { // */* assertMediaType("", "*", "*", false); assertMediaType(" ", "*", "*", false); assertMediaType("*/", "*", "*", false); assertMediaType("*/ ", "*", "*", false); assertMediaType(" * /", "*", "*", false); assertMediaType("/*", "*", "*", false); assertMediaType(" /*", "*", "*", false); assertMediaType("/ * ", "*", "*", false); assertMediaType(" / * ", "*", "*", false); assertMediaType("*/*", "*", "*", false); assertMediaType(" * /*", "*", "*", false); assertMediaType("*/ * ", "*", "*", false); assertMediaType(" * / * ", "*", "*", false); // */xml assertMediaType("/xml", "*", "xml", false); assertMediaType("/ xml ", "*", "xml", false); assertMediaType(" /xml", "*", "xml", false); assertMediaType(" / xml ", "*", "xml", false); assertMediaType("*/xml", "*", "xml", false); assertMediaType(" * /xml", "*", "xml", false); assertMediaType("*/ xml ", "*", "xml", false); assertMediaType(" * / xml ", "*", "xml", false); // application/* assertMediaType("application", "application", "*", false); assertMediaType(" application ", "application", "*", false); assertMediaType("application/", "application", "*", false); assertMediaType(" application /", "application", "*", false); assertMediaType(" application / ", "application", "*", false); assertMediaType("application/*", "application", "*", false); assertMediaType(" application /*", "application", "*", false); assertMediaType("application/ * ", "application", "*", false); assertMediaType(" application /*", "application", "*", false); } /** * Test references that are unequal. */ public void testUnEquals() throws Exception { MediaType mt1 = new MediaType("application/xml"); MediaType mt2 = new MediaType("application/xml2"); assertFalse(mt1.equals(mt2)); final Series mediaParams1 = new Form(); mediaParams1.add(new Parameter("charset", "ISO-8859-1")); final MediaType mt1Bis = new MediaType("application/xml", mediaParams1); final Series mediaParams3 = new Form(); mediaParams3.add(new Parameter("charset", "ISO-8859-15")); final MediaType mt3 = new MediaType("application/xml", mediaParams3); assertFalse(mt1Bis.equals(mt1)); assertFalse(mt1Bis.equals(mt3)); mt1 = new MediaType("application/1"); mt2 = MediaType.APPLICATION_ALL; assertFalse(mt1.equals(mt2)); } /** * Testing {@link MediaType#valueOf(String)} and * {@link MediaType#register(String, String)} */ public void testValueOf() { assertSame(MediaType.APPLICATION_XML, MediaType .valueOf("application/xml")); assertSame(MediaType.ALL, MediaType.valueOf("*/*")); final MediaType newType = MediaType .valueOf("application/x-restlet-test"); assertEquals("application", newType.getMainType()); assertEquals("x-restlet-test", newType.getSubType()); assertEquals("application/x-restlet-test", newType.getName()); // Should not have got registered by call to valueOf() alone assertNotSame(newType, MediaType.valueOf("application/x-restlet-test")); final MediaType registeredType = MediaType.register( "application/x-restlet-test", "Restlet testcase"); assertNotSame(newType, registeredType); // didn't touch old value assertEquals("application/x-restlet-test", registeredType.getName()); assertEquals("Restlet testcase", registeredType.getDescription()); // Later valueOf calls always returns the registered type assertSame(registeredType, MediaType .valueOf("application/x-restlet-test")); assertSame(registeredType, MediaType .valueOf("application/x-restlet-test")); // Test toString() equivalence MediaType mediaType = MediaType .valueOf("application/atom+xml; name=value"); assertEquals("application/atom+xml; name=value", mediaType.toString()); assertEquals(MediaType.APPLICATION_ATOM, mediaType.getParent()); } @SuppressWarnings("unchecked") public void testUnmodifiable() { Form form = new Form(); form.add("name1", "value1"); try { Series unmodifiableForm = (Series) Series .unmodifiableSeries(form); unmodifiableForm.add("name2", "value2"); fail("The series should be unmodifiable now"); } catch (UnsupportedOperationException uoe) { // As expected } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/ProductTokenTestCase.java0000664000175000017500000002254411757206352031051 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.data.ClientInfo; import org.restlet.data.Product; import org.restlet.engine.http.header.ProductReader; import org.restlet.engine.http.header.ProductWriter; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.Product}. * * @author Thierry Boileau */ public class ProductTokenTestCase extends RestletTestCase { public void testMainProduct() { final String userAgent1 = "Mozilla/4.0 (compatible; MSIE 6.0; America Online Browser 1.1; rev1.1; Windows NT 5.1;)"; final String userAgent2 = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-US; rv:1.8) Gecko/20051107 Camino/1.0b1"; final String userAgent3 = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:0.9.2) Gecko/20020508 Netscape6/6.1"; final String userAgent4 = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061024 Iceweasel/2.0 (Debian-2.0+dfsg-1)"; final String userAgent5 = "Mozilla/5.0 (compatible; Konqueror/3.5; Linux 2.6.15-1.2054_FC5; X11; i686; en_US) KHTML/3.5.4 (like Gecko)"; final String userAgent6 = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)"; final String userAgent7 = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"; final String userAgent8 = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/521.25 (KHTML, like Gecko) Safari/521.24"; final String userAgent9 = "Opera/9.00 (Macintosh; PPC Mac OS X; U; en)"; final String userAgent10 = "Wget/1.9"; final String userAgent11 = "Restlet-Framework/2.0-SNAPSHOT"; ClientInfo clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent1); Product product = clientInfo.getMainAgentProduct(); assertEquals("MSIE", product.getName()); assertEquals("6.0", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent2); product = clientInfo.getMainAgentProduct(); assertEquals("Camino", product.getName()); assertEquals("1.0b1", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent3); product = clientInfo.getMainAgentProduct(); assertEquals("Netscape6", product.getName()); assertEquals("6.1", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent4); product = clientInfo.getMainAgentProduct(); assertEquals("Iceweasel", product.getName()); assertEquals("2.0", product.getVersion()); assertEquals("Debian-2.0+dfsg-1", product.getComment()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent5); product = clientInfo.getMainAgentProduct(); assertEquals("Konqueror", product.getName()); assertEquals("3.5.4", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent6); product = clientInfo.getMainAgentProduct(); assertEquals("MSIE", product.getName()); assertEquals("5.5", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent7); product = clientInfo.getMainAgentProduct(); assertEquals("MSIE", product.getName()); assertEquals("6.0", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent8); product = clientInfo.getMainAgentProduct(); assertEquals("Safari", product.getName()); assertEquals("521.24", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent9); product = clientInfo.getMainAgentProduct(); assertEquals("Opera", product.getName()); assertEquals("9.00", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent10); product = clientInfo.getMainAgentProduct(); assertEquals("Wget", product.getName()); assertEquals("1.9", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent11); product = clientInfo.getMainAgentProduct(); assertEquals("Restlet-Framework", product.getName()); assertEquals("2.0-SNAPSHOT", product.getVersion()); clientInfo = new ClientInfo(); clientInfo.setAgent(userAgent7); final Map map = clientInfo.getAgentAttributes(); for (String key : map.keySet()) { System.out.println("[" + key + "," + map.get(key) + "]"); } } /** * Tests. */ public void testProductTokens() throws Exception { final String userAgent1 = "Mozilla/4.0 (compatible; MSIE 6.0; America Online Browser 1.1; rev1.1; Windows NT 5.1;)"; final String userAgent2 = "Advanced Browser (http://www.avantbrowser.com)"; final String userAgent3 = "Mozilla/5.0"; final String userAgent4 = "Mozilla"; final String userAgent5 = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-US; rv:1.8) Gecko/20051107 Camino/1.0b1"; final String userAgent6 = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061024 Iceweasel/2.0 (Debian-2.0+dfsg-1)"; List list = ProductReader.read(userAgent1); assertEquals(1, list.size()); assertEquals("Mozilla", list.get(0).getName()); assertEquals("4.0", list.get(0).getVersion()); assertEquals( "compatible; MSIE 6.0; America Online Browser 1.1; rev1.1; Windows NT 5.1;", list.get(0).getComment()); list = ProductReader.read(userAgent2); assertEquals(1, list.size()); assertEquals(list.get(0).getName(), "Advanced Browser"); assertNull(list.get(0).getVersion()); assertEquals(list.get(0).getComment(), "http://www.avantbrowser.com"); list = ProductReader.read(userAgent3); assertEquals(1, list.size()); assertEquals("Mozilla", list.get(0).getName()); assertEquals("5.0", list.get(0).getVersion()); assertNull(list.get(0).getComment()); list = ProductReader.read(userAgent4); assertEquals(1, list.size()); assertEquals("Mozilla", list.get(0).getName()); assertNull(list.get(0).getVersion()); assertNull(list.get(0).getComment()); list = ProductReader.read(userAgent5); assertEquals(3, list.size()); assertEquals("Mozilla", list.get(0).getName()); assertEquals("5.0", list.get(0).getVersion()); assertEquals("Macintosh; U; PPC Mac OS X; en-US; rv:1.8", list.get(0) .getComment()); assertEquals("Gecko", list.get(1).getName()); assertEquals("20051107", list.get(1).getVersion()); assertNull(list.get(1).getComment()); assertEquals("Camino", list.get(2).getName()); assertEquals("1.0b1", list.get(2).getVersion()); assertNull(list.get(2).getComment()); list = ProductReader.read(userAgent6); assertEquals(3, list.size()); assertEquals("Mozilla", list.get(0).getName()); assertEquals("5.0", list.get(0).getVersion()); assertEquals("X11; U; Linux i686; en-US; rv:1.8.1", list.get(0) .getComment()); assertEquals("Gecko", list.get(1).getName()); assertEquals("20061024", list.get(1).getVersion()); assertNull(list.get(1).getComment()); assertEquals("Iceweasel", list.get(2).getName()); assertEquals("2.0", list.get(2).getVersion()); assertEquals("Debian-2.0+dfsg-1", list.get(2).getComment()); final List products = new ArrayList(); products.add(new Product("Product", "1.2", null)); products.add(new Product("Nre", "1.1m4", "This is a comment")); list = ProductReader.read(ProductWriter.write(products)); assertEquals(2, list.size()); assertEquals("Product", list.get(0).getName()); assertEquals("1.2", list.get(0).getVersion()); assertNull(list.get(0).getComment()); assertEquals("Nre", list.get(1).getName()); assertEquals("1.1m4", list.get(1).getVersion()); assertEquals("This is a comment", list.get(1).getComment()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/StatusTestCase.java0000664000175000017500000000535111757206352027710 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import org.restlet.data.Status; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.Status}. * * @author Jerome Louvel */ public class StatusTestCase extends RestletTestCase { public void testCustomDescription() { final String customDescription = "My custom description"; final Status s = new Status(Status.CLIENT_ERROR_NOT_FOUND, customDescription); assertEquals(customDescription, s.getDescription()); } /** * Equality tests. */ public void testEquals() throws Exception { final Status s1 = new Status(201); final Status s2 = Status.SUCCESS_CREATED; assertTrue(s1.equals(s2)); assertTrue(s1.getCode() == s2.getCode()); assertEquals(s1, s2); assertTrue(s1.equals(s1)); assertEquals(s1, s1); } /** * Tests for status classes. */ public void testStatusClasses() { final Status s1 = new Status(287); assertTrue(s1.isSuccess()); final Status s2 = Status.CLIENT_ERROR_BAD_REQUEST; assertTrue(s2.isClientError()); assertTrue(s2.isError()); } /** * Unequality tests. */ public void testUnEquals() throws Exception { final Status s1 = new Status(200); final Status s2 = Status.SUCCESS_CREATED; assertFalse(s1.equals(s2)); assertFalse(s1.getCode() == s2.getCode()); assertFalse(s1.equals(null)); assertFalse(s2.equals(null)); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/FileReferenceTestCase.java0000664000175000017500000000373011757206352031122 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import java.io.File; import org.restlet.data.LocalReference; import org.restlet.test.RestletTestCase; /** * Unit test case for the File Reference parsing. * * @author Jerome Louvel */ public class FileReferenceTestCase extends RestletTestCase { public void testCreation() { String path = "D:\\Restlet\\build.xml"; LocalReference fr = LocalReference.createFileReference(path); fr.getFile(); assertEquals("file", fr.getScheme()); assertEquals("", fr.getAuthority()); if (File.separatorChar == '\\') { assertEquals("/D%3A/Restlet/build.xml", fr.getPath()); } else { assertEquals("/D%3A%5CRestlet%5Cbuild.xml", fr.getPath()); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/ReferenceTestCase.java0000664000175000017500000006655111757206352030334 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import java.util.ArrayList; import java.util.List; import org.restlet.data.Form; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.Reference}. * * @author Jerome Louvel * @author Lars Heuer (heuer[at]semagia.com) Semagia */ public class ReferenceTestCase extends RestletTestCase { protected final static String DEFAULT_SCHEME = "http"; protected final static String DEFAULT_SCHEMEPART = "//"; /** * Returns a reference that is initialized with http://www.restlet.org. * * @return Reference instance. */ protected Reference getDefaultReference() { final Reference ref = getReference(); ref.setHostDomain("www.restlet.org"); return ref; } /** * Returns a reference with uri == http:// * * @return Reference instance. */ protected Reference getReference() { final Reference ref = new Reference(); ref.setScheme(DEFAULT_SCHEME); ref.setSchemeSpecificPart(DEFAULT_SCHEMEPART); return ref; } /** * Test addition methods. */ public void testAdditions() throws Exception { final Reference ref = new Reference("http://www.restlet.org"); ref.addQueryParameter("abc", "123"); assertEquals("http://www.restlet.org?abc=123", ref.toString()); ref.addQueryParameter("def", null); assertEquals("http://www.restlet.org?abc=123&def", ref.toString()); ref.addSegment("root"); assertEquals("http://www.restlet.org/root?abc=123&def", ref.toString()); ref.addSegment("dir"); assertEquals("http://www.restlet.org/root/dir?abc=123&def", ref.toString()); } public void testEmptyRef() { Reference reference = new Reference(); reference.setAuthority("testAuthority"); // must not produce NPE reference = new Reference(); reference.setBaseRef("http://localhost"); // must not produce NPE reference = new Reference(); reference.setFragment("fragment"); // must not produce NPE reference = new Reference(); reference.setHostDomain("localhost"); // must not produce NPE assertEquals("localhost", reference.getAuthority()); reference.setHostPort(new Integer(4711)); // must not produce NPE assertEquals("localhost:4711", reference.getAuthority()); reference.setUserInfo("sdgj:skdfj"); // must not produce NPE assertEquals("sdgj:skdfj@localhost:4711", reference.getAuthority()); reference = new Reference(); reference.setIdentifier("http://host/abc/wkj"); // must not produce NPE reference = new Reference(); reference.setPath("loc/alhost"); // must not produce NPE reference = new Reference(); reference.setProtocol(Protocol.HTTPS); // must not produce NPE reference = new Reference(); reference.setQuery("a=b&c=&g=1"); // must not produce NPE reference = new Reference(); reference.setRelativePart("http://localhost"); // must not produce NPE reference = new Reference(); reference.setScheme("skjf"); // must not produce NPE reference = new Reference(); reference.setSchemeSpecificPart("host/afjhsd"); // must not produce NPE reference = new Reference(); final List segments = new ArrayList(); segments.add("skhf"); segments.add("sgdfg"); segments.add("xiz"); reference.setSegments(segments); // must not produce NPE } public void testEncoding() { // String uri1 = "/workspaces/W1​/content/Sin título.xml"; // String uri1rfe = // "%2Fworkspaces%2FW1%E2%80%8B%2Fcontent%2FSin%20t%C3%ADtulo.xml"; // String uri1xxe = // "/workspaces/W1​/content/Sin%20t%C3%83%C2%ADtulo.xml"; // String uri1msd = "/workspaces/W1/conte​nt/Sin%20t%EDtulo.xm​l"; // assertEquals(uri1, Reference.decode(uri1rfe)); // assertEquals(uri1, Reference.decode(uri1xxe)); // assertEquals(uri1, Reference.decode(uri1msd)); } /** * Equality tests. */ public void testEquals() throws Exception { final Reference ref1 = getDefaultReference(); final Reference ref2 = getDefaultReference(); assertEquals(ref1, ref2); assertTrue(ref1.equals(ref2)); } public void testGetLastSegment() { Reference reference = new Reference("http://hostname"); assertNull(reference.getLastSegment()); reference = new Reference("http://hostname/"); assertNull("", reference.getLastSegment()); reference = new Reference("http://hostname/abc"); assertEquals("abc", reference.getLastSegment()); reference = new Reference("http://hostname/abc/"); assertEquals("abc", reference.getLastSegment()); reference = new Reference("http://hostname/123/abc/"); assertEquals("abc", reference.getLastSegment()); reference = new Reference("http://hostname/123/abc"); assertEquals("abc", reference.getLastSegment()); } /** * Test hostname getting/setting. */ public void testHostName() throws Exception { final Reference ref = getReference(); String host = "www.restlet.org"; ref.setHostDomain(host); assertEquals(host, ref.getHostDomain()); host = "restlet.org"; ref.setHostDomain(host); assertEquals(host, ref.getHostDomain()); } public void testMatrix() { final Reference ref1 = new Reference( "http://domain.tld/whatever/a=1;b=2;c=4?x=a&y=b"); final Reference ref2 = new Reference( "http://domain.tld/whatever/a=1/foo;b=2;c=4;d?x=a&y=b"); final Reference ref3 = new Reference( "http://domain.tld/whatever/a=1;b=2;c=4/foo?x=a&y=b"); assertTrue(ref1.hasMatrix()); assertTrue(ref2.hasMatrix()); assertFalse(ref3.hasMatrix()); assertEquals("b=2;c=4", ref1.getMatrix()); assertEquals("b=2;c=4;d", ref2.getMatrix()); final Form form1 = ref1.getMatrixAsForm(); assertEquals("2", form1.getFirstValue("b")); assertEquals("4", form1.getFirstValue("c")); final Form form2 = ref1.getMatrixAsForm(); assertEquals("2", form2.getFirstValue("b")); assertEquals("4", form2.getFirstValue("c")); assertNull(form2.getFirstValue("d")); final Form newForm = new Form(); newForm.add("a", "1"); newForm.add("b", "2"); newForm.add("c", "4"); assertEquals("a=1;b=2;c=4", newForm.getMatrixString()); } /** * Tests the URI parsing. */ public void testParsing() { final String base = "http://a/b/c/d;p?q"; final String uri01 = "g:h"; final String uri02 = "g"; final String uri03 = "./g"; final String uri04 = "g/"; final String uri05 = "/g"; final String uri06 = "//g"; final String uri07 = "?y"; final String uri08 = "g?y"; final String uri09 = "#s"; final String uri10 = "g#s"; final String uri11 = "g?y#s"; final String uri12 = ";x"; final String uri13 = "g;x"; final String uri14 = "g;x?y#s"; final String uri15 = ""; final String uri16 = "."; final String uri17 = "./"; final String uri18 = ".."; final String uri19 = "../"; final String uri20 = "../g"; final String uri21 = "../.."; final String uri22 = "../../"; final String uri23 = "../../g"; final String uri24 = "../../../g"; final String uri25 = "../../../../g"; final String uri26 = "/./g"; final String uri27 = "/../g"; final String uri28 = "g."; final String uri29 = ".g"; final String uri30 = "g.."; final String uri31 = "..g"; final String uri32 = "./../g"; final String uri33 = "./g/."; final String uri34 = "g/./h"; final String uri35 = "g/../h"; final String uri36 = "g;x=1/./y"; final String uri37 = "g;x=1/../y"; final String uri101 = "g:h"; final String uri102 = "http://a/b/c/g"; final String uri103 = "http://a/b/c/g"; final String uri104 = "http://a/b/c/g/"; final String uri105 = "http://a/g"; final String uri106 = "http://g"; final String uri107 = "http://a/b/c/d;p?y"; final String uri108 = "http://a/b/c/g?y"; final String uri109 = "http://a/b/c/d;p?q#s"; final String uri110 = "http://a/b/c/g#s"; final String uri111 = "http://a/b/c/g?y#s"; final String uri112 = "http://a/b/c/;x"; final String uri113 = "http://a/b/c/g;x"; final String uri114 = "http://a/b/c/g;x?y#s"; final String uri115 = "http://a/b/c/d;p?q"; final String uri116 = "http://a/b/c/"; final String uri117 = "http://a/b/c/"; final String uri118 = "http://a/b/"; final String uri119 = "http://a/b/"; final String uri120 = "http://a/b/g"; final String uri121 = "http://a/"; final String uri122 = "http://a/"; final String uri123 = "http://a/g"; final String uri124 = "http://a/g"; final String uri125 = "http://a/g"; final String uri126 = "http://a/g"; final String uri127 = "http://a/g"; final String uri128 = "http://a/b/c/g."; final String uri129 = "http://a/b/c/.g"; final String uri130 = "http://a/b/c/g.."; final String uri131 = "http://a/b/c/..g"; final String uri132 = "http://a/b/g"; final String uri133 = "http://a/b/c/g/"; final String uri134 = "http://a/b/c/g/h"; final String uri135 = "http://a/b/c/h"; final String uri136 = "http://a/b/c/g;x=1/y"; final String uri137 = "http://a/b/c/y"; final Reference host = new Reference("http://host.com"); final Reference slashdir = new Reference(host, "/dir"); final Reference dir = new Reference(host, "dir"); final Reference dirslash = new Reference(host, "dir/"); final Reference fulldir = new Reference("http://host.com/dir"); final Reference fulldirsub = new Reference(fulldir, "sub"); final Reference fulldirslashsub = new Reference(fulldir, "/sub"); final Reference slashdirsub = new Reference(slashdir, "sub"); final Reference slashdirslashsub = new Reference(slashdir, "/sub"); final Reference dirslashsub = new Reference(dirslash, "sub"); final Reference fullsub = new Reference("http://host.com/dir/sub"); // Test the parsing of references into its components testRef0("foo://example.com:8042/over/there?name=ferret#nose", "foo", "example.com:8042", "/over/there", "name=ferret", "nose"); testRef0("urn:example:animal:ferret:nose", "urn", null, "example:animal:ferret:nose", null, null); testRef0("mailto:fred@example.com", "mailto", null, "fred@example.com", null, null); testRef0("foo://info.example.com?fred", "foo", "info.example.com", null, "fred", null); testRef0("*", null, null, "*", null, null); testRef0("http://localhost?query", "http", "localhost", null, "query", null); testRef0("http://localhost#?query", "http", "localhost", null, null, "?query"); testRef0("http://localhost/?query", "http", "localhost", "/", "query", null); testRef0("http://localhost/#?query", "http", "localhost", "/", null, "?query"); testRef0("http://localhost/path#frag/ment", "http", "localhost", "/path", null, "frag/ment"); testRef0("http://localhost/path?qu/ery", "http", "localhost", "/path", "qu/ery", null); // Test the resolution of relative references testRef1(base, uri01, uri101); testRef1(base, uri02, uri102); testRef1(base, uri03, uri103); testRef1(base, uri04, uri104); testRef1(base, uri05, uri105); testRef1(base, uri06, uri106); testRef1(base, uri07, uri107); testRef1(base, uri08, uri108); testRef1(base, uri09, uri109); testRef1(base, uri10, uri110); testRef1(base, uri11, uri111); testRef1(base, uri12, uri112); testRef1(base, uri13, uri113); testRef1(base, uri14, uri114); testRef1(base, uri15, uri115); testRef1(base, uri16, uri116); testRef1(base, uri17, uri117); testRef1(base, uri18, uri118); testRef1(base, uri19, uri119); testRef1(base, uri20, uri120); testRef1(base, uri21, uri121); testRef1(base, uri22, uri122); testRef1(base, uri23, uri123); testRef1(base, uri24, uri124); testRef1(base, uri25, uri125); testRef1(base, uri26, uri126); testRef1(base, uri27, uri127); testRef1(base, uri28, uri128); testRef1(base, uri29, uri129); testRef1(base, uri30, uri130); testRef1(base, uri31, uri131); testRef1(base, uri32, uri132); testRef1(base, uri33, uri133); testRef1(base, uri34, uri134); testRef1(base, uri35, uri135); testRef1(base, uri36, uri136); testRef1(base, uri37, uri137); // Test the relativization of absolute references testRef2(base, uri102, uri02); testRef2(base, uri104, uri04); testRef2(base, uri107, uri07); testRef2(base, uri108, uri08); testRef2(base, uri109, uri09); testRef2(base, uri110, uri10); testRef2(base, uri111, uri11); testRef2(base, uri112, uri12); testRef2(base, uri113, uri13); testRef2(base, uri114, uri14); testRef2(base, uri116, uri16); testRef2(base, uri118, uri18); testRef2(base, uri120, uri20); testRef2(base, uri121, uri21); testRef2(base, uri123, uri23); testRef2(uri104, uri116, uri18); testRef2(uri104, uri118, uri21); // Test the toString method with or without query/fragment testRef3("http://localhost/path#fragment", true, true, "http://localhost/path#fragment"); testRef3("http://localhost/path#fragment", true, false, "http://localhost/path"); testRef3("http://localhost/path#fragment", false, true, "http://localhost/path#fragment"); testRef3("http://localhost/path#fragment", false, false, "http://localhost/path"); testRef3("http://localhost/path?query", true, true, "http://localhost/path?query"); testRef3("http://localhost/path?query", true, false, "http://localhost/path?query"); testRef3("http://localhost/path?query", false, true, "http://localhost/path"); testRef3("http://localhost/path?query", false, false, "http://localhost/path"); testRef3("http://localhost/path?query#fragment", true, true, "http://localhost/path?query#fragment"); testRef3("http://localhost/path?query#fragment", true, false, "http://localhost/path?query"); testRef3("http://localhost/path?query#fragment", false, true, "http://localhost/path#fragment"); testRef3("http://localhost/path?query#fragment", false, false, "http://localhost/path"); testRef3("http://localhost/path#fragment?query", true, true, "http://localhost/path#fragment?query"); testRef3("http://localhost/path#fragment?query", true, false, "http://localhost/path"); testRef3("http://localhost/path#fragment?query", false, true, "http://localhost/path#fragment?query"); testRef3("http://localhost/path#fragment?query", false, false, "http://localhost/path"); testRef4(host, "http", "host.com", null, "http://host.com", "http://host.com", "http://host.com", null, null); testRef4(slashdir, null, null, "/dir", null, "/dir", "http://host.com/dir", null, "/dir"); testRef4(dir, null, null, "dir", null, "dir", "http://host.com/dir", null, "dir"); testRef4(dirslash, null, null, "dir/", null, "dir/", "http://host.com/dir/", null, "dir/"); testRef4(fulldir, "http", "host.com", "/dir", "http://host.com/dir", "http://host.com/dir", "http://host.com/dir", null, null); testRef4(fulldirsub, null, null, "sub", null, "sub", "http://host.com/sub", null, "sub"); testRef4(fulldirslashsub, null, null, "/sub", null, "/sub", "http://host.com/sub", null, "/sub"); testRef4(slashdirsub, null, null, "sub", null, "sub", "http://host.com/sub", null, "sub"); testRef4(slashdirslashsub, null, null, "/sub", null, "/sub", "http://host.com/sub", null, "/sub"); testRef4(dirslashsub, null, null, "sub", null, "sub", "http://host.com/dir/sub", null, "sub"); testRef4(fullsub, "http", "host.com", "/dir/sub", "http://host.com/dir/sub", "http://host.com/dir/sub", "http://host.com/dir/sub", null, null); } /** * Test port getting/setting. */ public void testPort() throws Exception { final Reference ref = getDefaultReference(); int port = 8080; ref.setHostPort(port); assertEquals(port, ref.getHostPort()); port = 9090; ref.setHostPort(port); assertEquals(port, ref.getHostPort()); } public void testProtocolConstructors() { assertEquals("http://restlet.org", new Reference(Protocol.HTTP, "restlet.org").toString()); assertEquals("https://restlet.org:8443", new Reference(Protocol.HTTPS, "restlet.org", 8443).toString()); final Reference ref = new Reference(Protocol.HTTP, "restlet.org"); ref.addQueryParameter("abc", "123"); assertEquals("http://restlet.org?abc=123", ref.toString()); } public void testQuery() { Reference ref1 = new Reference( "http://localhost/search?q=anythingelse%"); String query = ref1.getQuery(); assertEquals("q=anythingelse%25", query); Form queryForm = ref1.getQueryAsForm(); assertEquals("anythingelse%", queryForm.getFirstValue("q")); Form extJsQuery = new Form( "&_dc=1244741620627&callback=stcCallback1001"); assertEquals("1244741620627", extJsQuery.getFirstValue("_dc")); assertEquals("stcCallback1001", extJsQuery.getFirstValue("callback")); Reference ref = new Reference("http://localhost/v1/projects/13404"); ref.addQueryParameter("dyn", "true"); assertEquals("http://localhost/v1/projects/13404?dyn=true", ref.toString()); } public void testQueryWithUri() { Reference ref = new Reference(new Reference("http://localhost:8111/"), "http://localhost:8111/contrats/123?srvgwt=localhost:9997"); assertEquals("contrats/123?srvgwt=localhost:9997", ref.getRelativeRef() .toString()); } /** * Tests the parsing of a reference into its components * * @param reference * @param scheme * @param authority * @param path * @param query * @param fragment */ private void testRef0(String reference, String scheme, String authority, String path, String query, String fragment) { final Reference ref = new Reference(reference); assertEquals(scheme, ref.getScheme()); assertEquals(authority, ref.getAuthority()); assertEquals(path, ref.getPath()); assertEquals(query, ref.getQuery()); assertEquals(fragment, ref.getFragment()); } /** * Test the resolution of relative references. * * @param baseUri * @param relativeUri * @param expectedAbsoluteUri */ private void testRef1(String baseUri, String relativeUri, String expectedAbsoluteUri) { final Reference baseRef = new Reference(baseUri); final Reference relativeRef = new Reference(baseRef, relativeUri); final Reference absoluteRef = relativeRef.getTargetRef(); assertEquals(expectedAbsoluteUri, absoluteRef.toString()); } /** * Test the relativization of absolute references * * @param baseUri * @param absoluteUri * @param expectedRelativeUri */ private void testRef2(String baseUri, String absoluteUri, String expectedRelativeUri) { final Reference baseRef = new Reference(baseUri); final Reference absoluteRef = new Reference(absoluteUri); final Reference relativeRef = absoluteRef.getRelativeRef(baseRef); assertEquals(expectedRelativeUri, relativeRef.toString()); } /** * Test the toString method with or without query/fragment * * @param reference * @param query * @param fragment * @param toString */ private void testRef3(String reference, boolean query, boolean fragment, String toString) { final Reference ref = new Reference(reference); assertEquals(ref.toString(query, fragment), toString); } /** * Test the behaviour of several getters upon a Reference object. * * @param reference * @param query * @param fragment * @param toString */ private void testRef4(Reference reference, String scheme, String authority, String path, String remainingPart, String toString, String targetRef, String query, String relativePart) { assertEquals(reference.getScheme(), scheme); assertEquals(reference.getAuthority(), authority); assertEquals(reference.getPath(), path); assertEquals(reference.getRemainingPart(), remainingPart); assertEquals(reference.toString(), toString); assertEquals(reference.getTargetRef().toString(), targetRef); assertEquals(reference.getQuery(), query); assertEquals(reference.getRelativePart(), relativePart); } public void testRiap() throws Exception { Reference baseRef = new Reference("riap://component/exist/db/"); Reference ref = new Reference(baseRef, "something.xq"); assertEquals("riap://component/exist/db/something.xq", ref .getTargetRef().toString()); } /** * Test scheme getting/setting. */ public void testScheme() throws Exception { final Reference ref = getDefaultReference(); assertEquals(DEFAULT_SCHEME, ref.getScheme()); final String scheme = "https"; ref.setScheme(scheme); assertEquals(scheme, ref.getScheme()); ref.setScheme(DEFAULT_SCHEME); assertEquals(DEFAULT_SCHEME, ref.getScheme()); } /** * Test scheme specific part getting/setting. */ public void testSchemeSpecificPart() throws Exception { final Reference ref = getDefaultReference(); String part = "//www.restlet.org"; assertEquals(part, ref.getSchemeSpecificPart()); part = "//www.restlet.net"; ref.setSchemeSpecificPart(part); assertEquals(part, ref.getSchemeSpecificPart()); } /** * Test setting of the last segment. */ public void testSetLastSegment(){ Reference ref = new Reference("http://localhost:1234"); ref.addSegment("test"); assertEquals("http://localhost:1234/test", ref.toString()); ref.setLastSegment("last"); assertEquals("http://localhost:1234/last", ref.toString()); ref = new Reference("http://localhost:1234"); ref.setLastSegment("last"); assertEquals("http://localhost:1234/last", ref.toString()); ref.setLastSegment("test"); assertEquals("http://localhost:1234/test", ref.toString()); ref.addSegment("last"); assertEquals("http://localhost:1234/test/last", ref.toString()); } /** * Test references that are unequal. */ public void testUnEquals() throws Exception { final String uri1 = "http://www.restlet.org/"; final String uri2 = "http://www.restlet.net/"; final Reference ref1 = new Reference(uri1); final Reference ref2 = new Reference(uri2); assertFalse(ref1.equals(ref2)); assertFalse(ref1.equals(null)); } public void testUserinfo() { final Reference reference = new Reference("http://localhost:81"); // This format is depre. however we may prevent failures. reference.setUserInfo("login:password"); assertEquals("login:password@localhost:81", reference.getAuthority()); assertEquals("localhost", reference.getHostDomain()); assertEquals(81, reference.getHostPort()); assertEquals("login:password", reference.getUserInfo()); reference.setHostDomain("www.example.com"); assertEquals("login:password@www.example.com:81", reference.getAuthority()); assertEquals("www.example.com", reference.getHostDomain()); assertEquals(81, reference.getHostPort()); assertEquals("login:password", reference.getUserInfo()); reference.setHostPort(82); assertEquals("login:password@www.example.com:82", reference.getAuthority()); assertEquals("www.example.com", reference.getHostDomain()); assertEquals(82, reference.getHostPort()); assertEquals("login:password", reference.getUserInfo()); reference.setUserInfo("login"); assertEquals("login@www.example.com:82", reference.getAuthority()); assertEquals("www.example.com", reference.getHostDomain()); assertEquals(82, reference.getHostPort()); assertEquals("login", reference.getUserInfo()); } public void testValidity() { String uri = "http ://domain.tld/whatever/"; Reference ref = new Reference(uri); assertEquals("http+://domain.tld/whatever/", ref.toString()); uri = "file:///C|/wherever\\whatever.swf"; ref = new Reference(uri); assertEquals("file:///C%7C/wherever%5Cwhatever.swf", ref.toString()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java0000664000175000017500000004270311757206352027463 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.data; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Form; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.Range; import org.restlet.data.Status; import org.restlet.data.Tag; import org.restlet.engine.io.BioUtils; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Directory; import org.restlet.routing.Router; import org.restlet.test.RestletTestCase; /** * Test {@link org.restlet.data.Range}. * * @author Jerome Louvel */ public class RangeTestCase extends RestletTestCase { /** * Internal class used for test purpose. * */ private static class TestRangeApplication extends Application { public TestRangeApplication() { super(); getRangeService().setEnabled(true); } @Override public Restlet createInboundRoot() { Router router = new Router(); router.attach("/test", new TestRangeRestlet()); router.attach("/testGet", new TestRangeGetRestlet()); Directory directory = new Directory(getContext(), LocalReference.createFileReference(testDir)); directory.setModifiable(true); router.attach("/testPut/", directory); return router; } } /** * Internal class used for test purpose. It simply returns a string 10 * characters long. * */ private static class TestRangeGetRestlet extends Restlet { @Override public void handle(Request request, Response response) { response.setEntity(new StringRepresentation("1234567890")); response.getEntity().setTag(new Tag("TestRangeGetRestlet")); } } /** * Internal class used for test purpose. It tests the list of ranges sent by * the request and compares it with the values sent into the query. * */ private static class TestRangeRestlet extends Restlet { @Override public void handle(Request request, Response response) { Form form = request.getResourceRef().getQueryAsForm(); List ranges = request.getRanges(); boolean match = false; for (Parameter parameter : form) { long index = 0; long length = 0; String value = parameter.getValue(); if (value.startsWith("-")) { index = Range.INDEX_LAST; length = Long.parseLong(value.substring(1)); } else if (value.endsWith("-")) { index = Long.parseLong(value.substring(0, value.length() - 1)); length = Range.SIZE_MAX; } else { String[] tab = value.split("-"); if (tab.length == 2) { index = Long.parseLong(tab[0]); length = Long.parseLong(tab[1]) - index; } } boolean found = false; for (Range range : ranges) { found = (index == range.getIndex()) && (length == range.getSize()); if (found) { break; } } if (!found) { break; } match = true; } if (match) { response.setStatus(Status.SUCCESS_OK); } else { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } } } // Create a temporary directory for the tests private static final File testDir = new File( System.getProperty("java.io.tmpdir"), "rangeTestCase"); /** Component used for the tests. */ private Component component; @Override protected void setUp() throws Exception { super.setUp(); component = new Component(); component.getServers().add(Protocol.HTTP, TEST_PORT); component.getClients().add(Protocol.FILE); component.getDefaultHost().attach(new TestRangeApplication()); component.start(); } @Override protected void tearDown() throws Exception { component.stop(); component = null; super.tearDown(); } /** * Tests partial Get requests. * * @throws Exception */ @Test public void testGet() throws Exception { Client client = new Client(Protocol.HTTP); // Test partial Get. Request request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testGet"); Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1234567890", response.getEntity().getText()); assertEquals(10, response.getEntity().getSize()); request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testGet"); request.setRanges(Arrays.asList(new Range(0, 10))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("1234567890", response.getEntity().getText()); assertEquals(10, response.getEntity().getSize()); assertEquals(0, response.getEntity().getRange().getIndex()); assertEquals(10, response.getEntity().getRange().getSize()); request.setRanges(Arrays.asList(new Range(Range.INDEX_FIRST, 2))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("12", response.getEntity().getText()); assertEquals(2, response.getEntity().getSize()); assertEquals(0, response.getEntity().getRange().getIndex()); assertEquals(2, response.getEntity().getRange().getSize()); request.setRanges(Arrays.asList(new Range(2, 2))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("34", response.getEntity().getText()); assertEquals(2, response.getEntity().getSize()); assertEquals(2, response.getEntity().getRange().getIndex()); assertEquals(2, response.getEntity().getRange().getSize()); request.setRanges(Arrays.asList(new Range(2, 7))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("3456789", response.getEntity().getText()); assertEquals(7, response.getEntity().getSize()); assertEquals(2, response.getEntity().getRange().getIndex()); assertEquals(7, response.getEntity().getRange().getSize()); request.setRanges(Arrays.asList(new Range(Range.INDEX_LAST, 7))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("4567890", response.getEntity().getText()); assertEquals(7, response.getEntity().getSize()); assertEquals(3, response.getEntity().getRange().getIndex()); assertEquals(7, response.getEntity().getRange().getSize()); request.setRanges(Arrays.asList(new Range(1, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("234567890", response.getEntity().getText()); assertEquals(9, response.getEntity().getSize()); assertEquals(1, response.getEntity().getRange().getIndex()); assertEquals(9, response.getEntity().getRange().getSize()); client.stop(); } /** * Tests conditional ranges requests. * * @throws Exception */ @Test public void testConditionalRanges() throws Exception { Client client = new Client(Protocol.HTTP); // Test partial Get. Request request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testGet"); Response response = client.handle(request); Tag entityTag = response.getEntity().getTag(); request.setRanges(Arrays.asList(new Range(1, Range.SIZE_MAX))); request.getConditions().setRangeTag(entityTag); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("234567890", response.getEntity().getText()); assertEquals(9, response.getEntity().getSize()); assertEquals(1, response.getEntity().getRange().getIndex()); assertEquals(9, response.getEntity().getRange().getSize()); entityTag = new Tag(entityTag.getName() + "-test"); request.setRanges(Arrays.asList(new Range(1, Range.SIZE_MAX))); request.getConditions().setRangeTag(entityTag); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1234567890", response.getEntity().getText()); client.stop(); } /** * Tests partial Put requests. * * @throws IOException */ @Test public void testPut() throws IOException { BioUtils.delete(testDir, true); Client client = new Client(Protocol.HTTP); // PUT on a file that does not exist Request request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("1234567890")); request.setRanges(Arrays.asList(new Range(0, 10))); Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request .getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1234567890", response.getEntity().getText()); // Partial PUT on a file, the provided representation overflowed the // existing file request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("0000000000")); request.setRanges(Arrays.asList(new Range(1, 10))); response = client.handle(request); System.out.println(response.getStatus() + " / " + response.getStatus().getThrowable()); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request .getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10000000000", response.getEntity().getText()); // Partial PUT on a file that does not exists, the provided range // does not start at the 0 index. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai2.txt"); request.setEntity(new StringRepresentation("0000000000")); request.setRanges(Arrays.asList(new Range(1, 10))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); request.setMethod(Method.GET); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("0000000000", response.getEntity().getText()); // Partial PUT on a file, simple range request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("22")); request.setRanges(Arrays.asList(new Range(2, 2))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request .getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10220000000", response.getEntity().getText()); // Partial PUT on a file, the provided representation will be padded // at the very end of the file. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("888")); request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request .getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10220000888", response.getEntity().getText()); // Partial PUT on a file that does not exist, the range does not // specify the range size. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai3.txt"); request.setEntity(new StringRepresentation("888")); request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); request.setMethod(Method.GET); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("888", response.getEntity().getText()); // Partial PUT on a file, the provided representation will be padded // just before the end of the file. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("99")); request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request .getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10220000998", response.getEntity().getText()); request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setRanges(Arrays.asList(new Range(3, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("20000998", response.getEntity().getText()); BioUtils.delete(testDir, true); } /** * Tests ranges. * * @throws Exception */ @Test public void testRanges() throws Exception { Client client = new Client(Protocol.HTTP); // Test "range" header. Request request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=0-500"); request.setRanges(Arrays.asList(new Range(0, 500))); assertEquals(Status.SUCCESS_OK, client.handle(request).getStatus()); request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=-500"); request.setRanges(Arrays.asList(new Range(Range.INDEX_LAST, 500))); assertEquals(Status.SUCCESS_OK, client.handle(request).getStatus()); request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=500-"); request.setRanges(Arrays.asList(new Range(500, Range.SIZE_MAX))); assertEquals(Status.SUCCESS_OK, client.handle(request).getStatus()); request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=500-1000"); request.setRanges(Arrays.asList(new Range(500, 500))); assertEquals(Status.SUCCESS_OK, client.handle(request).getStatus()); request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=500-1000&range=500-"); request.setRanges(Arrays.asList(new Range(500, 500), new Range(500, Range.SIZE_MAX))); assertEquals(Status.SUCCESS_OK, client.handle(request).getStatus()); client.stop(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/util/0000775000175000017500000000000011757206354024170 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/util/TemplateTestCase.java0000664000175000017500000001177411757206354030254 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.util; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.engine.Engine; import org.restlet.routing.Template; import org.restlet.routing.Variable; import org.restlet.test.RestletTestCase; /** * Test case for URI templates. * * @author Jerome Louvel */ public class TemplateTestCase extends RestletTestCase { public void testEncodedCharacters() { Template template = new Template( "http://localhost/{token}/bookstore/{bookid}"); String encodedToken = "FtDF91VSX%2F7AN6C39k51ZV510SW%2Fot6SIGstq8XGCcHfOfHbZOZLUD4u%2BGUNK0bBawVZ4GR5TgV7PtRbF%2Bnm9abYJN6AWycdj9J6CLyU4D7Zou36KEjkel%2B0LtlGGhFPVrCvpBuqPy8V8o5IZ9tDys0Py6sXXAtEVbXBYeRYzOvIBzOZkIviIyceVCU%2BlYv%2Fh9k7Fhlb1JGtKUCj3ZDg%2FvJ1Co7dOC1Ho3%2Fe0Fup7k9qgTuCvZRSHcpizaEFPNLp"; String targetUri = "http://localhost/" + encodedToken + "/bookstore/1234"; Map variables1 = new HashMap(); int parsed1 = template.parse(targetUri, variables1); assertTrue("parsing of " + targetUri + " not successful, but it should be.", parsed1 >= 0); assertEquals(encodedToken, variables1.get("token")); } public void testPathMatching() { Template template = new Template("http://www.mydomain.com/abc/{v1}"); template.setMatchingMode(Template.MODE_STARTS_WITH); template.getDefaultVariable().setType(Variable.TYPE_URI_PATH); Map variables1 = new HashMap(); String string1 = "http://www.mydomain.com/abc/123/456"; int parsed1 = template.parse(string1, variables1); assertTrue("parsing of " + string1 + " not successful, but it should be.", parsed1 >= 0); assertEquals("123/456", variables1.get("v1")); Map variables2 = new HashMap(); String string2 = "http://www.mydomain.com/abc/123/456?s=tuv"; int parsed2 = template.parse(string2, variables2); assertTrue("parsing of " + string2 + " not successful, but it should be.", parsed2 >= 0); assertEquals("123/456", variables2.get("v1")); Map variables3 = new HashMap(); String string3 = "http://www.mydomain.com/abc/123/456#tuv"; int parsed3 = template.parse(string3, variables3); assertTrue("parsing of " + string3 + " not successful, but it should be.", parsed3 >= 0); assertEquals("123/456", variables3.get("v1")); } public void testVariableNames() throws Exception { Template tpl = new Template( "http://{userId}.restlet.com/invoices/{invoiceId}"); tpl.setLogger(Engine.getAnonymousLogger()); List names = tpl.getVariableNames(); assertEquals(2, names.size()); assertEquals("userId", names.get(0)); assertEquals("invoiceId", names.get(1)); } public void testWithPercentChars() { Template template = new Template("abc/{v1}"); template.getDefaultVariable().setType(Variable.TYPE_URI_ALL); Map variables1 = new HashMap(); String string1 = "abc/hff11kh"; int parsed1 = template.parse(string1, variables1); assertTrue("parsing of " + string1 + " not successful, but it should be.", parsed1 >= 0); assertEquals("hff11kh", variables1.get("v1")); Map variables2 = new HashMap(); String string2 = "abc/hf%20kh"; int parsed2 = template.parse(string2, variables2); assertTrue("parsing of " + string2 + " not successful, but it should be.", parsed2 >= 0); assertEquals("hf%20kh", variables2.get("v1")); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/TemplateFilterTestCase.java0000664000175000017500000002010711757206352030431 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test; import java.io.File; import java.io.FileWriter; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.engine.io.BioUtils; import org.restlet.resource.Directory; /** * Test case for template filters. * * @author Thierry Boileau */ public class TemplateFilterTestCase extends RestletTestCase { /** * Internal class used for test purpose * * @author Thierry Boileau */ private static class MyFreemakerApplication extends Application { File testDirectory; Directory directory; /** * Constructor. * * @param testDirectory * The test directory. */ public MyFreemakerApplication(File testDirectory) { setTestDirectory(testDirectory); } @Override public Restlet createInboundRoot() { // Create a Directory that manages a local directory this.directory = new Directory(getContext(), LocalReference .createFileReference(getTestDirectory())); this.directory.setNegotiatingContent(true); return new org.restlet.ext.freemarker.TemplateFilter(getContext(), this.directory); } public File getTestDirectory() { return this.testDirectory; } public void setTestDirectory(File testDirectory) { this.testDirectory = testDirectory; } } /** * Internal class used for test purpose * * @author Thierry Boileau */ private static class MyVelocityApplication extends Application { File testDirectory; Directory directory; /** * Constructor. */ public MyVelocityApplication(File testDirectory) { setTestDirectory(testDirectory); } @Override public Restlet createInboundRoot() { // Create a Directory that manages a local directory this.directory = new Directory(getContext(), LocalReference .createFileReference(getTestDirectory())); this.directory.setNegotiatingContent(true); return new org.restlet.ext.velocity.TemplateFilter(getContext(), this.directory); } public File getTestDirectory() { return this.testDirectory; } public void setTestDirectory(File testDirectory) { this.testDirectory = testDirectory; } } File testDir; public void testTemplateFilter() { try { // Create a temporary directory for the tests this.testDir = new File(System.getProperty("java.io.tmpdir"), "TemplateFilterTestCase"); BioUtils.delete(this.testDir, true); this.testDir.mkdir(); // Create temporary template files // Will be templated File testFileFm1 = new File(this.testDir, "testFm1.txt.fmt"); FileWriter fw = new FileWriter(testFileFm1); fw.write("Method=${m}/Authority=${ra}"); fw.close(); // Will not be templated File testFileFm2 = new File(this.testDir, "testFm2.txt"); fw = new FileWriter(testFileFm2); fw.write("Method=${m}/Authority=${ra}"); fw.close(); // Will be templated File testFileVl1 = new File(this.testDir, "testVl1.txt.vm"); fw = new FileWriter(testFileVl1); fw.write("Method=${m}/Path=${rp}"); fw.close(); // Will not be templated File testFileVl2 = new File(this.testDir, "testVl2.txt"); fw = new FileWriter(testFileVl2); fw.write("Method=${m}/Path=${rp}"); fw.close(); // Create a new component Component component = new Component(); component.getServers().add(Protocol.HTTP, TEST_PORT); component.getClients().add(Protocol.FILE); // Create an application filtered with FreeMarker MyFreemakerApplication freemarkerApplication = new MyFreemakerApplication( this.testDir); // Create an application filtered with Velocity MyVelocityApplication velocityApplication = new MyVelocityApplication( this.testDir); // Attach the applications to the component and start it component.getDefaultHost().attach("/freemarker", freemarkerApplication); component.getDefaultHost().attach("/velocity", velocityApplication); // Now, let's start the component! component.start(); // Allow extensions tunneling freemarkerApplication.getTunnelService().setExtensionsTunnel(true); velocityApplication.getTunnelService().setExtensionsTunnel(true); Client client = new Client(Protocol.HTTP); Response response = client.handle(new Request(Method.GET, "http://localhost:" + TEST_PORT + "/freemarker/" + testFileFm1.getName())); if (response.isEntityAvailable()) { assertEquals("Method=GET/Authority=localhost:" + TEST_PORT, response.getEntity().getText()); } response = client.handle(new Request(Method.GET, "http://localhost:" + TEST_PORT + "/freemarker/" + testFileFm2.getName())); assertTrue(response.getStatus().isSuccess()); if (response.isEntityAvailable()) { assertEquals("Method=${m}/Authority=${ra}", response .getEntity().getText()); } response = client.handle(new Request(Method.GET, "http://localhost:" + TEST_PORT + "/velocity/" + testFileVl1.getName())); if (response.isEntityAvailable()) { assertEquals("Method=GET/Path=/velocity/testVl1", response .getEntity().getText()); } response = client.handle(new Request(Method.GET, "http://localhost:" + TEST_PORT + "/velocity/" + testFileVl2.getName())); assertTrue(response.getStatus().isSuccess()); if (response.isEntityAvailable()) { assertEquals("Method=${m}/Path=${rp}", response.getEntity() .getText()); } // Now, let's stop the component! component.stop(); client.stop(); } catch (Exception e) { e.printStackTrace(); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/0000775000175000017500000000000011757206354024013 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/gwt/0000775000175000017500000000000011757206352024612 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/gwt/MyBean.java0000664000175000017500000000401211757206352026625 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.gwt; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Simple bean with generic types. * * @author Thierry Boileau */ public class MyBean implements Serializable { /** */ private static final long serialVersionUID = 1L; private List list; private Map map; private String name; public List getList() { return list; } public Map getMap() { return map; } public String getName() { return name; } public void setList(List list) { this.list = list; } public void setMap(Map map) { this.map = map; } public void setName(String name) { this.name = name; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/gwt/GwtConverterTest.java0000664000175000017500000000461011757206352030747 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.gwt; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import org.restlet.ext.gwt.GwtConverter; import org.restlet.representation.Representation; import org.restlet.test.RestletTestCase; /** * Tests basic conversion using the GwtConverter. * * @author Thierry Boileau */ public class GwtConverterTest extends RestletTestCase { public void testObjectToRepresentation() throws IOException { MyBean myBean = new MyBean(); myBean.setList(new ArrayList()); myBean.getList().add("list1"); myBean.getList().add("list2"); myBean.setMap(new HashMap()); myBean.getMap().put("key1", "value1"); myBean.getMap().put("key2", "value2"); myBean.setName("myname"); Representation rep = new GwtConverter().toRepresentation(myBean, null, null); assertNotNull(rep); String test = rep.getText(); System.out.println(test); assertTrue(test.contains("myname")); assertTrue(test.contains("list2")); assertTrue(test.contains("key1")); assertTrue(test.contains("value2")); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/wadl/0000775000175000017500000000000011757206354024742 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/wadl/YahooSearch.wadl0000664000175000017500000000275211757206354030026 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/wadl/NewsSearchResource.java0000664000175000017500000000266611757206352031367 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.wadl; import org.restlet.resource.ServerResource; /** * Empty resource for the WADL test case. * * @author Jerome Louvel */ public class NewsSearchResource extends ServerResource { } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/wadl/WadlTestCase.java0000664000175000017500000000370011757206354030130 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.wadl; import org.restlet.ext.wadl.WadlApplication; import org.restlet.ext.wadl.WadlComponent; import org.restlet.test.RestletTestCase; /** * Unit test case for the WADL extension. * * @author Jerome Louvel */ public class WadlTestCase extends RestletTestCase { public void testWadl() throws Exception { final WadlComponent comp = new WadlComponent( "clap://class/org/restlet/test/ext/wadl/YahooSearch.wadl"); final WadlApplication app = (WadlApplication) comp.getHosts().get(0) .getRoutes().get(0).getNext(); assertNotNull(app); assertEquals(app.getInboundRoot(), app.getRouter()); assertNotNull(app.getInboundRoot()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/jaxb/0000775000175000017500000000000011757206352024735 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/jaxb/Sample.java0000664000175000017500000000357411757206352027032 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class Sample { @XmlElement(name = "value") private String val; public Sample() { } public Sample(String val) { this.val = val; } public String getVal() { return val; } public void setVal(String val) { this.val = val; } @Override public String toString() { return "Sample [val=" + val + "]"; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/jaxb/JaxbBasicConverterTest.java0000664000175000017500000000461011757206352032157 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.jaxb; import java.io.IOException; import javax.xml.bind.JAXBException; import org.restlet.data.MediaType; import org.restlet.ext.jaxb.JaxbRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.service.ConverterService; import org.restlet.test.RestletTestCase; /** * Tests basic Conversion using the JaxbConverter * * @author Sanjay Acharya */ public class JaxbBasicConverterTest extends RestletTestCase { public void testObjectToRepresentation() { ConverterService cs = new ConverterService(); Representation rep = cs.toRepresentation(new Sample(), new Variant( MediaType.APPLICATION_XML), null); assertTrue(rep instanceof JaxbRepresentation); } public void testRepresentationToObject() throws IOException, JAXBException { ConverterService cs = new ConverterService(); JaxbRepresentation sampleRep = new JaxbRepresentation( MediaType.APPLICATION_XML, new Sample()); Object rep = cs.toObject(sampleRep, Sample.class, null); assertTrue(rep instanceof Sample); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/jaxb/JaxbIntegrationConverterTestCase.java0000664000175000017500000001457211757206352034225 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.jaxb; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.restlet.test.RestletTestCase; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Protocol; import org.restlet.ext.jaxb.JaxbRepresentation; import org.restlet.Request; import org.restlet.Response; import org.restlet.resource.ClientResource; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; /** * Simple Integration Tests that uses the JAXB Converter to perform POST, PUT * and GET operations. * * Note: You must have registered the JaxbConverter in * META-INF/services/org.restlet.engine.converter.ConverterHelper * * @author Sanjay Acharya */ public class JaxbIntegrationConverterTestCase extends RestletTestCase { private static final String IN_STRING = "foo"; private static final String HELLO_OUT_STRING = "Hello World " + IN_STRING; private Component component; private String uri; public void setUp() throws Exception { super.setUp(); this.component = new Component(); final Server server = this.component.getServers().add(Protocol.HTTP, 0); final Application application = createApplication(this.component); this.component.getDefaultHost().attach(application); this.component.start(); uri = "http://localhost:" + server.getEphemeralPort() + "/test"; } public void tearDown() throws Exception { super.tearDown(); if (component != null) { component.stop(); } this.component = null; } protected Application createApplication(Component component) { final Application application = new Application() { @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.attach("/test", SampleResource.class); return router; } }; return application; } /** * Test POST, PUT and GET using the Client class * * @throws Exception */ public void testIntegration() throws Exception { Client client = new Client(new Context(), Arrays.asList(Protocol.HTTP)); Request request = new Request(Method.POST, uri); request.setEntity(new JaxbRepresentation(new Sample(IN_STRING))); Response response = client.handle(request); JaxbRepresentation resultRepresentation = new JaxbRepresentation( response.getEntity(), Sample.class); Sample sample = resultRepresentation.getObject(); assertEquals(HELLO_OUT_STRING, sample.getVal()); request = new Request(Method.PUT, uri); request.setEntity(new JaxbRepresentation(new Sample(IN_STRING))); response = client.handle(request); resultRepresentation = new JaxbRepresentation( response.getEntity(), Sample.class); sample = resultRepresentation.getObject(); assertEquals(HELLO_OUT_STRING, sample.getVal()); request = new Request(Method.GET, uri); response = client.handle(request); resultRepresentation = new JaxbRepresentation( response.getEntity(), Sample.class); sample = resultRepresentation.getObject(); assertEquals(IN_STRING, sample.getVal()); client.stop(); } /** * Test POST, PUT and GET using the ClientResource class * * @throws Exception */ public void testWithClientResource() throws Exception { ClientResource sampleResource = new ClientResource(uri); List> m = new ArrayList>(); m.add(new Preference(MediaType.APPLICATION_XML)); sampleResource.getClientInfo().setAcceptedMediaTypes(m); Sample sample = new Sample(IN_STRING); sample = sampleResource.post(sample, Sample.class); assertEquals(HELLO_OUT_STRING, sample.getVal()); sampleResource.put(sample); assertTrue(sampleResource.getStatus().isSuccess()); sample = sampleResource.put(sample, Sample.class); assertEquals(HELLO_OUT_STRING, sample.getVal()); sample = sampleResource.get(Sample.class); assertEquals(IN_STRING, sample.getVal()); } public static class SampleResource extends ServerResource { @Post("xml") public Sample post(Sample sample) { assertNotNull(sample); return new Sample(HELLO_OUT_STRING); } @Get("xml") public Sample getSample() { return new Sample(IN_STRING); } @Put("xml:xml") public JaxbRepresentation putSample(Sample sample) { assertNotNull(sample); return new JaxbRepresentation(new Sample(HELLO_OUT_STRING)); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/jaxb/ObjectFactory.java0000664000175000017500000000263711757206352030346 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.jaxb; import javax.xml.bind.annotation.XmlRegistry; @XmlRegistry public class ObjectFactory { public Sample createSample() { return new Sample(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/0000775000175000017500000000000011757206354024753 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/service.xml0000664000175000017500000000124711757206354027141 0ustar jamespagejamespage AtomPub Test Site entry application/atom+xml;type=entry draft application/atom+xml;type=entry media */* restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/draft.xml0000664000175000017500000001436611757206354026607 0ustar jamespagejamespage BitWorking | Joe Gregorio http://bitworking.org/favicon.ico 2008-09-26T02:35:00.065423-04:00 Joe Gregorio http://bitworking.org/ my_test entry http://bitworking.org/news/24/eee-eee 2008-09-26T02:35:00.065423-04:00 2008-09-26T02:35:00.065423-04:00

    test

    <link href="http://bitworking.org/news/23/eeewww-ttt" /> <link href="23/" rel="edit" /> <link href="23/;media" rel="edit-media" /> <id>http://bitworking.org/news/23/eeewww-ttt</id> <updated>2008-09-26T02:34:39.344129-04:00</updated> <app:edited>2008-09-26T02:34:39.344129-04:00</app:edited> <summary type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml" /> </summary> <content type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml" /> </content> </entry><entry> <title>draft A http://bitworking.org/news/22/draft-A 2008-08-02T19:39:38.501682-04:00 2008-08-02T19:39:38.501682-04:00
    draft A
    Copy http://bitworking.org/news/20/Copy 2008-05-21T16:12:51.505857-04:00 2008-05-21T16:12:51.505857-04:00

    This is in the summary.

    This is all new content. And now we should get a cache hit.

    A title http://bitworking.org/news/19/A-title 2008-05-21T16:11:09.884781-04:00 2008-05-21T16:11:09.884781-04:00

    This is in the summary.

    This is all new content. And now we should get a cache hit.

    Testing creating an HTML file http://bitworking.org/news/18/This-is-new-stuff 2008-05-21T15:58:07.224649-04:00 2008-05-21T15:58:07.224649-04:00
    1. This is all new content.
    A title http://bitworking.org/news/17/A-title 2008-05-21T15:43:46.115747-04:00 2008-05-21T15:43:46.115747-04:00

    This is in the summary.

    This is all new content. And now we should get a cache hit.

    A longer title than the rest http://bitworking.org/news/15/A-longer-title-than-the-rest 2008-05-21T14:31:40.790675-04:00 2008-05-21T14:31:40.790675-04:00

    This is in the summary.

    This is all new content. And now we should get a cache hit.

    This is new stuff http://bitworking.org/news/13/This-is-retitled 2008-05-14T23:33:53.683341-04:00 2008-05-14T23:33:53.683341-04:00

    This is all new content.

    restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/categories.xml0000664000175000017500000000045311757206354027624 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/ConverterTestCase.java0000664000175000017500000000436711757206352031231 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.atom; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.ext.atom.Feed; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.service.ConverterService; import org.restlet.test.RestletTestCase; public class ConverterTestCase extends RestletTestCase { public void testObjectToRepresentation() { ConverterService cs = new ConverterService(); Feed feed = new Feed(); Representation representation = cs.toRepresentation(feed); assertEquals(MediaType.APPLICATION_ATOM, representation.getMediaType()); } public void testRepresentationToObject() throws IOException { ConverterService cs = new ConverterService(); ClientResource cr = new ClientResource( "clap://class/org/restlet/test/ext/atom/entry.xml"); Representation representation = cr.get(); Object object = cs.toObject(representation); assertTrue(object instanceof Feed); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/entry.xml0000664000175000017500000002761311757206354026647 0ustar jamespagejamespage BitWorking | Joe Gregorio http://bitworking.org/favicon.ico 2008-12-17T07:54:25.981880-04:00 Joe Gregorio http://bitworking.org/ Iñtërnâtiônàlizætiøn - 3 http://bitworking.org/news/448/acdhlkgcke 2008-12-17T07:54:25.981880-04:00 2008-12-17T07:54:25.981880-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 2 http://bitworking.org/news/447/aahdkdfllb 2008-12-17T07:54:21.357192-04:00 2008-12-17T07:54:21.357192-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 1 http://bitworking.org/news/446/iddjklgibj 2008-12-17T07:54:15.394080-04:00 2008-12-17T07:54:15.394080-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 1 http://bitworking.org/news/445/iddjklgibj 2008-12-17T07:54:15.393666-04:00 2008-12-17T07:54:15.393666-04:00

    A test of utf-8

    Internationalization - 2 http://bitworking.org/news/443/ebdkghflkl 2008-12-11T15:08:15.004401-04:00 2008-12-11T15:08:15.004401-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 3 http://bitworking.org/news/444/ldeghjiiil 2008-12-11T15:07:20.580724-04:00 2008-12-11T15:07:20.580724-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 1 http://bitworking.org/news/442/kjaejeebej 2008-12-11T15:07:05.605048-04:00 2008-12-11T15:07:05.605048-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 3 http://bitworking.org/news/438/jdjaibcjhf 2008-12-07T18:47:29.458480-04:00 2008-12-07T18:47:29.458480-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 2 http://bitworking.org/news/437/fhghiiadig 2008-12-07T18:47:26.875868-04:00 2008-12-07T18:47:26.875868-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 1 http://bitworking.org/news/436/kcklfafehd 2008-12-07T18:47:24.110337-04:00 2008-12-07T18:47:24.110337-04:00

    A test of utf-8

    testentry http://bitworking.org/news/435/testentry 2008-12-04T06:15:39.049598-04:00 2008-12-04T06:15:39.049598-04:00
    testentry content
    testentry http://bitworking.org/news/434/testentry 2008-12-04T06:13:48.999134-04:00 2008-12-04T06:13:48.999134-04:00
    testentry content
    Iñtërnâtiônàlizætiøn - 3 http://bitworking.org/news/433/gdbeblfldc 2008-11-24T08:04:17.488375-04:00 2008-11-24T08:04:17.488375-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 2 http://bitworking.org/news/432/iilabdijfj 2008-11-24T08:04:14.907706-04:00 2008-11-24T08:04:14.907706-04:00

    A test of utf-8

    Iñtërnâtiônàlizætiøn - 1 http://bitworking.org/news/431/jcieiealik 2008-11-24T08:04:12.342970-04:00 2008-11-24T08:04:12.342970-04:00

    A test of utf-8

    Entry1 http://bitworking.org/news/427/Entry1 2008-11-21T10:03:59.301997-04:00 2008-11-21T10:03:59.301997-04:00
    contenu a moi
    newtestcicle1 http://bitworking.org/news/423/newtestcicle1 2008-10-31T21:18:02.873813-04:00 2008-10-31T21:18:02.873813-04:00
    well, the client responds correctly
    Loggando http://bitworking.org/news/417/Loggando 2008-10-20T11:50:45.878609-04:00 2008-10-20T11:50:45.878609-04:00
    Testo
    Prova http http://bitworking.org/news/416/Prova-http 2008-10-20T11:23:27.302374-04:00 2008-10-20T11:23:27.302374-04:00
    Ciao
    Ciao sandro http://bitworking.org/news/415/Ciao-sandro 2008-10-15T12:15:50.962301-04:00 2008-10-15T12:15:50.962301-04:00
    Cia
    restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/AtomTestCase.java0000664000175000017500000000746011757206352030157 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.atom; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.engine.io.BioUtils; import org.restlet.ext.atom.Categories; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Service; import org.restlet.representation.FileRepresentation; import org.restlet.test.RestletTestCase; /** * Unit test case for the Atom extension. * * @author Jerome Louvel */ public class AtomTestCase extends RestletTestCase { public void testCategories() throws Exception { final Categories atomCategories = new Categories( "clap://class/org/restlet/test/ext/atom/categories.xml"); assertEquals(new Reference("http://example.com/cats/big3"), atomCategories.getScheme()); assertEquals("animal", atomCategories.getEntries().get(0).getTerm()); } public void testAtom() throws Exception { // Create a temporary directory for the tests final File testDir = new File(System.getProperty("java.io.tmpdir"), "AtomTestCase"); BioUtils.delete(testDir, true); testDir.mkdir(); final Service atomService = new Service( "clap://class/org/restlet/test/ext/atom/service.xml"); assertEquals("AtomPub Test Site", atomService.getWorkspaces().get(0) .getTitle()); assertEquals("entry", atomService.getWorkspaces().get(0) .getCollections().get(0).getTitle()); final Feed atomFeed = atomService.getWorkspaces().get(0) .getCollections().get(0).getFeed(); // Write the feed into a file. final File feedFile = new File(testDir, "feed.xml"); atomFeed .write(new BufferedOutputStream(new FileOutputStream(feedFile))); // Get the service from the file final FileRepresentation fileRepresentation = new FileRepresentation( feedFile, MediaType.TEXT_XML); final Feed atomFeed2 = new Feed(fileRepresentation); assertEquals(atomFeed2.getAuthors().get(0).getName(), atomFeed .getAuthors().get(0).getName()); assertEquals(atomFeed2.getEntries().get(0).getContent() .getInlineContent().getText(), atomFeed2.getEntries().get(0) .getContent().getInlineContent().getText()); assertEquals(atomFeed2.getEntries().get(0).getTitle().getContent(), atomFeed2.getEntries().get(0).getTitle().getContent()); BioUtils.delete(testDir, true); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/atom/media.xml0000664000175000017500000000212411757206354026553 0ustar jamespagejamespage BitWorking | Joe Gregorio http://bitworking.org/favicon.ico 2009-01-09T15:00:00.065144-04:00 Joe Gregorio http://bitworking.org/ waves http://bitworking.org/news/202/waves 2009-01-09T15:00:00.065144-04:00 2009-01-09T15:00:00.065144-04:00
    restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/rdf/0000775000175000017500000000000011757206352024564 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/rdf/RdfTestCase.java0000664000175000017500000001012411757206352027574 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.rdf; import org.restlet.data.MediaType; import org.restlet.ext.rdf.RdfRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.RestletTestCase; /** * Unit test case for the RDF extension. */ public class RdfTestCase extends RestletTestCase { public void testN3() throws Exception { Representation rep = new StringRepresentation( "@prefix rdf: ." + "@prefix rdfs: ." + "@prefix cfg: ." + "@prefix : ." + "@prefix n3: ." + "@prefix list: ." + "@prefix doc: ." + "@prefix dc: ." + "@prefix type: ." + "@keywords a, is, of." + "@base .\n" + "#Directive base.\n" + "@prefix prefix .\n\n" + " _:x1 has :x2. " + " :x3 has _:x4 ; _:x5 , . " + " _:x6 has . " + " = . " + " => . " + " <= . " + ":x7 \"string\". " + ":x8 \"\"\"str\ning\"\"\". " + ":x9 <= \"\"\"str\ning\"\"\". " + ":x10 @is of . " + ":x11^:x12. " + ":x13^:x14^:x15. " + ":x16^:x17 :x18 :x19. " + ":x20!:x21." + ":x22!:x23!:x24. " + "[] :x25 :x26." + "[:x27 :x28]." + "(:x29 :x30) :x31 :x32." + " _:x33 \"12\"^^type:int. " + " _:x33 12. ", MediaType.TEXT_RDF_N3); // File file = new File("/bnf.n3"); // rep = new FileRepresentation(file.getPath(), MediaType.TEXT_PLAIN); Representation n3Rep = new RdfRepresentation(rep); n3Rep.write(System.out); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/freemarker/0000775000175000017500000000000011757206352026134 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/freemarker/FreeMarkerTestCase.java0000664000175000017500000000554111757206352032463 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.freemarker; import java.io.File; import java.io.FileWriter; import java.util.Map; import java.util.TreeMap; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.test.RestletTestCase; import freemarker.template.Configuration; /** * Unit test for the FreeMarker extension. * * @author Jerome Louvel */ public class FreeMarkerTestCase extends RestletTestCase { public static void main(String[] args) { try { new FreeMarkerTestCase().testTemplate(); } catch (Exception e) { e.printStackTrace(); } } public void testTemplate() throws Exception { // Create a temporary directory for the tests final File testDir = new File(System.getProperty("java.io.tmpdir"), "FreeMarkerTestCase"); testDir.mkdir(); // Create a temporary template file final File testFile = File.createTempFile("test", ".ftl", testDir); final FileWriter fw = new FileWriter(testFile); fw.write("Value=${value}"); fw.close(); final Configuration fmc = new Configuration(); fmc.setDirectoryForTemplateLoading(testDir); final Map map = new TreeMap(); map.put("value", "myValue"); final String result = new TemplateRepresentation(testFile.getName(), fmc, map, MediaType.TEXT_PLAIN).getText(); assertEquals("Value=myValue", result); // Clean-up BioUtils.delete(testFile); BioUtils.delete(testDir, true); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/spring/0000775000175000017500000000000011757206354025315 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/spring/SpringTestCase.xml0000664000175000017500000000462011757206354030737 0ustar jamespagejamespage file value1 value2 restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java0000664000175000017500000002675211757206352033057 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.spring; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.ext.spring.SpringBeanFinder; import org.restlet.ext.spring.SpringBeanRouter; import org.restlet.resource.ServerResource; import org.restlet.routing.Filter; import org.restlet.routing.TemplateRoute; import org.restlet.security.ChallengeAuthenticator; import org.restlet.test.RestletTestCase; import org.restlet.util.RouteList; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; /** * @author Rhett Sutphin */ public class SpringBeanRouterTestCase extends RestletTestCase { private static class TestAuthenticator extends ChallengeAuthenticator { private TestAuthenticator() throws IllegalArgumentException { super(null, ChallengeScheme.HTTP_BASIC, "Test"); } } private static class TestFilter extends Filter { } private static class TestResource extends ServerResource { } private static class TestRestlet extends Restlet { } private static final String FISH_URI = "/renewable/fish/{fish_name}"; private static final String ORE_URI = "/non-renewable/ore/{ore_type}"; private DefaultListableBeanFactory factory; private SpringBeanRouter router; private RouteList actualRoutes() { doPostProcess(); return this.router.getRoutes(); } private void assertFinderForBean(String expectedBeanName, Restlet restlet) { assertTrue("Restlet is not a bean finder restlet: " + restlet.getClass().getName(), restlet instanceof SpringBeanFinder); final SpringBeanFinder actualFinder = (SpringBeanFinder) restlet; assertEquals("Finder does not point to correct bean", expectedBeanName, actualFinder.getBeanName()); assertEquals("Finder does not point to correct bean factory", this.factory, actualFinder.getBeanFactory()); } private void doPostProcess() { this.router.postProcessBeanFactory(this.factory); } private TemplateRoute matchRouteFor(String uri) { Request req = new Request(Method.GET, uri); return (TemplateRoute) router.getNext(req, new Response(req)); } private void registerBeanDefinition(String id, String alias, Class beanClass, String scope) { BeanDefinition bd = new RootBeanDefinition(beanClass); bd.setScope(scope == null ? BeanDefinition.SCOPE_SINGLETON : scope); this.factory.registerBeanDefinition(id, bd); if (alias != null) { this.factory.registerAlias(id, alias); } } @SuppressWarnings("deprecation") private void registerResourceBeanDefinition(String id, String alias) { registerBeanDefinition(id, alias, org.restlet.resource.Resource.class, BeanDefinition.SCOPE_PROTOTYPE); } private void registerServerResourceBeanDefinition(String id, String alias) { registerBeanDefinition(id, alias, ServerResource.class, BeanDefinition.SCOPE_PROTOTYPE); } private Set routeUris(RouteList routes) { final Set uris = new HashSet(); for (final TemplateRoute actualRoute : routes) { uris.add(actualRoute.getTemplate().getPattern()); } return uris; } @Override protected void setUp() throws Exception { super.setUp(); this.factory = new DefaultListableBeanFactory(); registerResourceBeanDefinition("ore", ORE_URI); registerServerResourceBeanDefinition("fish", FISH_URI); registerBeanDefinition("someOtherBean", null, String.class, null); this.router = new SpringBeanRouter(); } @Override protected void tearDown() throws Exception { this.factory = null; this.router = null; super.tearDown(); } public void testExplicitAttachmentsMayBeRestlets() throws Exception { String expected = "/protected/timber"; this.router .setAttachments(Collections.singletonMap(expected, "timber")); registerBeanDefinition("timber", null, TestAuthenticator.class, null); doPostProcess(); TemplateRoute timberRoute = matchRouteFor(expected); assertNotNull("No route for " + expected, timberRoute); assertTrue("Route is not for correct restlet", timberRoute.getNext() instanceof TestAuthenticator); } public void testExplicitAttachmentsTrumpBeanNames() throws Exception { this.router.setAttachments(Collections.singletonMap(ORE_URI, "fish")); RouteList actualRoutes = actualRoutes(); assertEquals("Wrong number of routes", 2, actualRoutes.size()); TemplateRoute oreRoute = matchRouteFor(ORE_URI); assertNotNull("No route for " + ORE_URI, oreRoute); assertFinderForBean("fish", oreRoute.getNext()); } public void testExplicitRoutingForNonResourceNonRestletBeansFails() throws Exception { this.router.setAttachments(Collections.singletonMap("/fail", "someOtherBean")); try { doPostProcess(); fail("Exception not thrown"); } catch (IllegalStateException ise) { assertEquals( "someOtherBean is not routable. It must be either a Resource, a ServerResource or a Restlet.", ise.getMessage()); } } public void testRoutesCreatedForBeanIdsIfAppropriate() throws Exception { String grain = "/renewable/grain/{grain_type}"; registerResourceBeanDefinition(grain, null); final Set actualUris = routeUris(actualRoutes()); assertEquals("Wrong number of URIs", 3, actualUris.size()); assertTrue("Missing grain URI: " + actualUris, actualUris .contains(grain)); } public void testRoutesCreatedForUrlAliases() throws Exception { final Set actualUris = routeUris(actualRoutes()); assertEquals("Wrong number of URIs", 2, actualUris.size()); assertTrue("Missing ore URI: " + actualUris, actualUris .contains(ORE_URI)); assertTrue("Missing fish URI: " + actualUris, actualUris .contains(FISH_URI)); } public void testRoutesPointToFindersForBeans() throws Exception { final RouteList actualRoutes = actualRoutes(); assertEquals("Wrong number of routes", 2, actualRoutes.size()); TemplateRoute oreRoute = matchRouteFor(ORE_URI); TemplateRoute fishRoute = matchRouteFor(FISH_URI); assertNotNull("ore route not present: " + actualRoutes, oreRoute); assertNotNull("fish route not present: " + actualRoutes, fishRoute); assertFinderForBean("ore", oreRoute.getNext()); assertFinderForBean("fish", fishRoute.getNext()); } public void testRoutingIncludesAuthenticators() throws Exception { String expected = "/protected/timber"; registerBeanDefinition("timber", expected, TestAuthenticator.class, null); doPostProcess(); TemplateRoute authenticatorRoute = matchRouteFor(expected); assertNotNull("No route for authenticator", authenticatorRoute); assertTrue("Route is not for authenticator", authenticatorRoute .getNext() instanceof TestAuthenticator); } public void testRoutingIncludesFilters() throws Exception { String expected = "/filtered/timber"; registerBeanDefinition("timber", expected, TestFilter.class, null); doPostProcess(); TemplateRoute filterRoute = matchRouteFor(expected); assertNotNull("No route for filter", filterRoute); assertTrue("Route is not for filter", filterRoute.getNext() instanceof Filter); } public void testRoutingIncludesOtherRestlets() throws Exception { String expected = "/singleton"; registerBeanDefinition("timber", expected, TestRestlet.class, null); doPostProcess(); TemplateRoute restletRoute = matchRouteFor(expected); assertNotNull("No route for restlet", restletRoute); assertTrue("Route is not for restlet", restletRoute.getNext() instanceof TestRestlet); } public void testRoutingIncludesResourceSubclasses() throws Exception { String expected = "/renewable/timber/{id}"; registerBeanDefinition("timber", expected, TestResource.class, BeanDefinition.SCOPE_PROTOTYPE); doPostProcess(); TemplateRoute timberRoute = matchRouteFor("/renewable/timber/sycamore"); assertNotNull("No route for timber", timberRoute); assertFinderForBean("timber", timberRoute.getNext()); } public void testRoutingIncludesSpringRouterStyleExplicitlyMappedBeans() throws Exception { final BeanDefinition bd = new RootBeanDefinition(ServerResource.class); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); this.factory.registerBeanDefinition("timber", bd); this.factory.registerAlias("timber", "no-slash"); String expectedTemplate = "/renewable/timber/{farm_type}"; router.setAttachments(Collections.singletonMap(expectedTemplate, "timber")); final RouteList actualRoutes = actualRoutes(); assertEquals("Wrong number of routes", 3, actualRoutes.size()); TemplateRoute timberRoute = matchRouteFor(expectedTemplate); assertNotNull("Missing timber route: " + actualRoutes, timberRoute); assertFinderForBean("timber", timberRoute.getNext()); } public void testRoutingSkipsResourcesWithoutAppropriateAliases() throws Exception { final BeanDefinition bd = new RootBeanDefinition(ServerResource.class); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); this.factory.registerBeanDefinition("timber", bd); this.factory.registerAlias("timber", "no-slash"); final RouteList actualRoutes = actualRoutes(); assertEquals("Timber resource should have been skipped", 2, actualRoutes.size()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/spring/AllSpringTests.java0000664000175000017500000000344311757206352031100 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.spring; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Suite with all Spring unit tests. * * @author Rhett Sutphin */ public class AllSpringTests extends TestCase { public static Test suite() { final TestSuite suite = new TestSuite(); suite.setName("all spring-ext tests"); suite.addTestSuite(SpringBeanRouterTestCase.class); suite.addTestSuite(SpringBeanFinderTestCase.class); suite.addTestSuite(SpringTestCase.class); return suite; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanFinderTestCase.java0000664000175000017500000002654611757206352033007 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.spring; import org.restlet.ext.spring.SpringBeanFinder; import org.restlet.resource.Resource; import org.restlet.resource.ServerResource; import org.restlet.test.RestletTestCase; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.StaticApplicationContext; import java.util.Arrays; /** * @author Rhett Sutphin */ @SuppressWarnings("deprecation") public class SpringBeanFinderTestCase extends RestletTestCase { private static class AnotherResource extends Resource { } private static class SomeResource extends Resource { private static int instantiationCount = 0; private SomeResource() { incrementInstantiationCount(); } public synchronized static void resetInstantiationCount() { instantiationCount = 0; } private synchronized static void incrementInstantiationCount() { instantiationCount++; } public synchronized static int getInstantiationCount() { return instantiationCount; } } private static class SomeServerResource extends ServerResource { private static int instantiationCount = 0; private String src; @SuppressWarnings("unused") public SomeServerResource() { setSrc("constructor"); incrementInstantiationCount(); } public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } public synchronized static void resetInstantiationCount() { instantiationCount = 0; } private synchronized static void incrementInstantiationCount() { instantiationCount++; } public synchronized static int getInstantiationCount() { return instantiationCount; } } private static final String BEAN_NAME = "fish"; private StaticApplicationContext applicationContext; private DefaultListableBeanFactory beanFactory; private SpringBeanFinder finder; private MutablePropertyValues createServerResourcePropertyValues() { return new MutablePropertyValues(Arrays.asList(new PropertyValue("src", "spring"))); } private void registerApplicationContextBean(String beanName, Class resourceClass) { this.applicationContext.registerPrototype(beanName, resourceClass); this.applicationContext.refresh(); } private void registerBeanFactoryBean(String beanName, Class resourceClass) { registerBeanFactoryBean(beanName, resourceClass, null); } private void registerBeanFactoryBean(String beanName, Class resourceClass, MutablePropertyValues values) { this.beanFactory.registerBeanDefinition(beanName, new RootBeanDefinition(resourceClass, values)); } @Override protected void setUp() throws Exception { super.setUp(); this.beanFactory = new DefaultListableBeanFactory(); this.applicationContext = new StaticApplicationContext(); this.finder = new SpringBeanFinder(); this.finder.setBeanName(BEAN_NAME); } @Override protected void tearDown() throws Exception { this.beanFactory = null; this.applicationContext = null; this.finder = null; super.tearDown(); } public void testBeanResolutionFailsWithNeitherApplicationContextOrBeanFactory() throws Exception { try { this.finder.createResource(); fail("Exception not thrown"); } catch (IllegalStateException iae) { assertEquals( "Either a beanFactory or an applicationContext is required for SpringBeanFinder.", iae.getMessage()); } } public void testBeanResolutionFailsWhenNoMatchingBeanButThereIsABeanFactory() throws Exception { try { this.finder.setBeanFactory(beanFactory); this.finder.create(); fail("Exception not thrown"); } catch (IllegalStateException iae) { assertEquals( "No bean named " + BEAN_NAME + " present.", iae.getMessage()); } } public void testBeanResolutionFailsWhenNoMatchingBeanButThereIsAnApplicationContext() throws Exception { try { this.finder.setApplicationContext(applicationContext); this.finder.create(); fail("Exception not thrown"); } catch (IllegalStateException iae) { assertEquals( "No bean named " + BEAN_NAME + " present.", iae.getMessage()); } } public void testNullWhenResourceBeanIsWrongType() throws Exception { registerBeanFactoryBean(BEAN_NAME, String.class); this.finder.setBeanFactory(beanFactory); Resource actual = this.finder.createResource(); assertNull("Should have returned null", actual); } public void testExceptionWhenServerResourceBeanIsWrongType() throws Exception { registerBeanFactoryBean(BEAN_NAME, String.class); this.finder.setBeanFactory(beanFactory); try { this.finder.create(); fail("Exception not thrown"); } catch (ClassCastException cce) { assertEquals( "fish does not resolve to an instance of org.restlet.resource.ServerResource", cce.getMessage()); } } public void testPrefersApplicationContextOverBeanFactoryIfTheBeanIsInBoth() throws Exception { registerApplicationContextBean(BEAN_NAME, SomeResource.class); registerBeanFactoryBean(BEAN_NAME, AnotherResource.class); this.finder.setApplicationContext(applicationContext); Resource actual = this.finder.createResource(); assertNotNull("Resource not found", actual); assertTrue("Resource not from application context: " + actual.getClass().getName(), actual instanceof SomeResource); } public void testReturnsResourceBeanWhenExists() throws Exception { registerBeanFactoryBean(BEAN_NAME, SomeResource.class); this.finder.setBeanFactory(beanFactory); final Resource actual = this.finder.createResource(); assertNotNull("Resource not found", actual); assertTrue("Resource not the correct type", actual instanceof SomeResource); } public void testReturnsServerResourceBeanForLongFormOfCreate() throws Exception { registerBeanFactoryBean(BEAN_NAME, SomeServerResource.class, createServerResourcePropertyValues()); this.finder.setBeanFactory(beanFactory); final ServerResource actual = this.finder.create( SomeServerResource.class, null, null); assertNotNull("Resource not found", actual); assertTrue("Resource not the correct type", actual instanceof SomeServerResource); assertEquals("Resource not from spring context", "spring", ((SomeServerResource) actual).getSrc()); } public void testReturnsServerResourceBeanWhenExists() throws Exception { registerBeanFactoryBean(BEAN_NAME, SomeServerResource.class, createServerResourcePropertyValues()); this.finder.setBeanFactory(beanFactory); final ServerResource actual = this.finder.create(); assertNotNull("Resource not found", actual); assertTrue("Resource not the correct type", actual instanceof SomeServerResource); } public void testUsesApplicationContextIfPresent() throws Exception { registerApplicationContextBean(BEAN_NAME, SomeResource.class); this.finder.setApplicationContext(applicationContext); Resource actual = this.finder.createResource(); assertNotNull("Resource not found", actual); assertTrue("Resource not the correct type", actual instanceof SomeResource); } public void testServerResourceNotInstantiatedFromBeanFactoryWhenCreateResourceCalled() throws Exception { SomeServerResource.resetInstantiationCount(); registerBeanFactoryBean(BEAN_NAME, SomeServerResource.class); this.finder.setBeanFactory(beanFactory); assertNull(this.finder.createResource()); assertEquals("Should not have been instantiated", 0, SomeServerResource.getInstantiationCount()); } public void testServerResourceNotInstantiatedFromApplicationContextWhenCreateResourceCalled() throws Exception { SomeServerResource.resetInstantiationCount(); registerApplicationContextBean(BEAN_NAME, SomeServerResource.class); this.finder.setApplicationContext(applicationContext); assertNull(this.finder.createResource()); assertEquals("Should not have been instantiated", 0, SomeServerResource.getInstantiationCount()); } public void testResourceNotInstantiatedFromBeanFactoryWhenCreateCalled() throws Exception { SomeResource.resetInstantiationCount(); registerBeanFactoryBean(BEAN_NAME, SomeResource.class); this.finder.setBeanFactory(beanFactory); try { this.finder.create(); } catch (ClassCastException e) { // expected } assertEquals("Should not have been instantiated", 0, SomeResource.getInstantiationCount()); } public void testResourceNotInstantiatedFromApplicationContextWhenCreateCalled() throws Exception { SomeResource.resetInstantiationCount(); registerApplicationContextBean(BEAN_NAME, SomeResource.class); this.finder.setApplicationContext(applicationContext); try { this.finder.create(); } catch (ClassCastException e) { // expected } assertEquals("Should not have been instantiated", 0, SomeResource.getInstantiationCount()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/spring/SpringTestCase.java0000664000175000017500000000516511757206352031063 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.spring; import org.restlet.Component; import org.restlet.Server; import org.restlet.test.RestletTestCase; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; /** * Unit test case for the Spring extension. * * @author Jerome Louvel */ public class SpringTestCase extends RestletTestCase { public void testSpring() throws Exception { // Load the Spring container ClassPathResource resource = new ClassPathResource( "org/restlet/test/ext/spring/SpringTestCase.xml"); BeanFactory factory = new XmlBeanFactory(resource); // Start the Restlet component Component component = (Component) factory.getBean("component"); component.start(); Thread.sleep(500); component.stop(); } public void testSpringServerProperties() { ClassPathResource resource = new ClassPathResource( "org/restlet/test/ext/spring/SpringTestCase.xml"); BeanFactory factory = new XmlBeanFactory(resource); Server server = (Server) factory.getBean("server"); assertEquals("value1", server.getContext().getParameters() .getFirstValue("key1")); assertEquals("value2", server.getContext().getParameters() .getFirstValue("key2")); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/0000775000175000017500000000000011757206354025103 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/0000775000175000017500000000000011757206354030066 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/CafeCustoFeedsApplication.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/CafeCustoFeedsApplicat0000664000175000017500000000715311757206352034316 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafecustofeeds; import org.restlet.Application; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.routing.Router; public class CafeCustoFeedsApplication extends Application { private static class MyClapRestlet extends Restlet { String file; boolean updatable; public MyClapRestlet(Context context, String file, boolean updatable) { super(context); this.file = file; this.updatable = updatable; } @Override public void handle(Request request, Response response) { if (Method.GET.equals(request.getMethod())) { Form form = request.getResourceRef().getQueryAsForm(); String uri = "/" + this.getClass().getPackage().getName().replace(".", "/") + "/" + file; if (form.getFirstValue("$expand") != null) { uri += form.getFirstValue("$expand"); } Response r = getContext().getClientDispatcher().handle( new Request(Method.GET, LocalReference .createClapReference(LocalReference.CLAP_CLASS, uri + ".xml"))); response.setEntity(r.getEntity()); response.setStatus(r.getStatus()); } else if (!updatable) { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } } @Override public Restlet createInboundRoot() { getMetadataService().setDefaultCharacterSet(CharacterSet.ISO_8859_1); getConnectorService().getClientProtocols().add(Protocol.CLAP); Router router = new Router(getContext()); router.attach("/$metadata", new MyClapRestlet(getContext(), "metadata", false)); router .attach("/Cafes", new MyClapRestlet(getContext(), "cafes", false)); router.attach("/Contacts('1')", new MyClapRestlet(getContext(), "contact1", false)); return router; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/cafesItems.xml0000664000175000017500000001201011757206354032665 0ustar jamespagejamespage Cafes http://localhost:8111/CafeCustoFeeds.svc/Cafes 2010-02-17T11:31:40Z http://localhost:8111/Cafe.svc/Cafes('1') 2010-02-17T11:31:40Z Items http://localhost:8111/Cafe.svc/Cafes('1')/Items 2010-02-17T11:31:40Z http://localhost:8111/Cafe.svc/Items('1') 2010-02-17T11:31:40Z 1 Poulet au curry http://localhost:8111/Cafe.svc/Items('2') 2010-02-17T11:31:40Z 2 Pate 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:31:40Z Items http://localhost:8111/Cafe.svc/Cafes('2')/Items 2010-02-17T11:31:40Z http://localhost:8111/Cafe.svc/Items('3') 2010-02-17T11:31:40Z 3 Banana Split http://localhost:8111/Cafe.svc/Items('4') 2010-02-17T11:31:40Z 4 Cotes du Rhone 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/Item.java0000664000175000017500000000517211757206352031632 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafecustofeeds; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class Item { private String description; private String id; /** * Constructor without parameter. * */ public Item() { super(); } /** * Constructor. * * @param id * The identifiant value of the entity. */ public Item(String id) { this(); this.id = id; } /** * Returns the value of the description attribute. * * @return The value of the description attribute. */ public String getDescription() { return description; } /** * Returns the value of the id attribute. * * @return The value of the id attribute. */ public String getId() { return id; } /** * Sets the value of the description attribute. * * @param Description * The value of the description attribute. */ public void setDescription(String description) { this.description = description; } /** * Sets the value of the id attribute. * * @param ID * The value of the id attribute. */ public void setId(String id) { this.id = id; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/Contact.java0000664000175000017500000000567711757206354032343 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafecustofeeds; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class Contact { private String id; private String name; private String title; /** * Constructor without parameter. * */ public Contact() { super(); } /** * Constructor. * * @param id * The identifiant value of the entity. */ public Contact(String id) { this(); this.id = id; } /** * Returns the value of the id attribute. * * @return The value of the id attribute. */ public String getId() { return id; } /** * Returns the value of the name attribute. * * @return The value of the name attribute. */ public String getName() { return name; } /** * Returns the value of the title attribute. * * @return The value of the title attribute. */ public String getTitle() { return title; } /** * Sets the value of the id attribute. * * @param ID * The value of the id attribute. */ public void setId(String id) { this.id = id; } /** * Sets the value of the name attribute. * * @param Name * The value of the name attribute. */ public void setName(String name) { this.name = name; } /** * Sets the value of the title attribute. * * @param Title * The value of the title attribute. */ public void setTitle(String title) { this.title = title; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/contact1.xml0000664000175000017500000000157611757206354032335 0ustar jamespagejamespage http://localhost:8111/CafeCustoFeeds.svc/Contacts('1') 2010-02-17T11:49:08Z 1 Agathe Zeblues restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/cafesContact.xml0000664000175000017500000000664011757206354033213 0ustar jamespagejamespage Cafes http://localhost:8111/CafeCustoFeeds.svc/Cafes 2010-02-17T11:34:58Z http://localhost:8111/Cafe.svc/Cafes('1') 2010-02-17T11:34:58Z Agathe Zeblues http://localhost:8111/Cafe.svc/Contacts('1') 2010-02-17T11:34:58Z 1 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:34:58Z Alphonse Denltas http://localhost:8111/Cafe.svc/Contacts('2') 2010-02-17T11:34:58Z 2 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/Cafe.java0000664000175000017500000001135111757206352031566 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafecustofeeds; import java.util.List; import org.restlet.test.ext.odata.cafecustofeeds.Contact; import org.restlet.test.ext.odata.cafecustofeeds.Item; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class Cafe { private String city; private String companyName; private String id; private String name; private int zipCode; private Contact contact; private List items; /** * Constructor without parameter. * */ public Cafe() { super(); } /** * Constructor. * * @param id * The identifiant value of the entity. */ public Cafe(String id) { this(); this.id = id; } /** * Returns the value of the city attribute. * * @return The value of the city attribute. */ public String getCity() { return city; } /** * Returns the value of the companyName attribute. * * @return The value of the companyName attribute. */ public String getCompanyName() { return companyName; } /** * Returns the value of the id attribute. * * @return The value of the id attribute. */ public String getId() { return id; } /** * Returns the value of the name attribute. * * @return The value of the name attribute. */ public String getName() { return name; } /** * Returns the value of the zipCode attribute. * * @return The value of the zipCode attribute. */ public int getZipCode() { return zipCode; } /** * Returns the value of the contact attribute. * * @return The value of the contact attribute. */ public Contact getContact() { return contact; } /** * Returns the value of the items attribute. * * @return The value of the items attribute. */ public List getItems() { return items; } /** * Sets the value of the city attribute. * * @param City * The value of the city attribute. */ public void setCity(String city) { this.city = city; } /** * Sets the value of the companyName attribute. * * @param CompanyName * The value of the companyName attribute. */ public void setCompanyName(String companyName) { this.companyName = companyName; } /** * Sets the value of the id attribute. * * @param ID * The value of the id attribute. */ public void setId(String id) { this.id = id; } /** * Sets the value of the name attribute. * * @param Name * The value of the name attribute. */ public void setName(String name) { this.name = name; } /** * Sets the value of the zipCode attribute. * * @param ZipCode * The value of the zipCode attribute. */ public void setZipCode(int zipCode) { this.zipCode = zipCode; } /** * Sets the value of the contact attribute. * * @param contact * The value of the contact attribute. */ public void setContact(Contact contact) { this.contact = contact; } /** * Sets the value of the items attribute. * * @param items * The value of the items attribute. */ public void setItems(List items) { this.items = items; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/metadata.xml0000664000175000017500000000705011757206354032372 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/cafes.xml0000664000175000017500000000427011757206354031674 0ustar jamespagejamespage Cafes http://localhost:8111/CafeCustoFeeds.svc/Cafes 2010-02-17T11:28:13Z http://localhost:8111/CafeCustoFeeds.svc/Cafes('1') 2010-02-17T11:28:13Z 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:28:13Z 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/CafeCustoFeedsService.javarestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafecustofeeds/CafeCustoFeedsService.0000664000175000017500000000702011757206354034232 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafecustofeeds; import org.restlet.ext.odata.Query; import org.restlet.ext.odata.Service; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class CafeCustoFeedsService extends Service { /** * Constructor. * */ public CafeCustoFeedsService() { super("http://localhost:8111/CafeCustoFeeds.svc"); } /** * Adds a new entity to the service. * * @param entity * The entity to add to the service. * @throws Exception */ public void addEntity(Cafe entity) throws Exception { addEntity("/Cafes", entity); } /** * Creates a query for cafe entities hosted by this service. * * @param subpath * The path to this entity relatively to the service URI. * @return A query object. */ public Query createCafeQuery(String subpath) { return createQuery(subpath, Cafe.class); } /** * Adds a new entity to the service. * * @param entity * The entity to add to the service. * @throws Exception */ public void addEntity(Item entity) throws Exception { addEntity("/Items", entity); } /** * Creates a query for item entities hosted by this service. * * @param subpath * The path to this entity relatively to the service URI. * @return A query object. */ public Query createItemQuery(String subpath) { return createQuery(subpath, Item.class); } /** * Adds a new entity to the service. * * @param entity * The entity to add to the service. * @throws Exception */ public void addEntity(Contact entity) throws Exception { addEntity("/Contacts", entity); } /** * Creates a query for contact entities hosted by this service. * * @param subpath * The path to this entity relatively to the service URI. * @return A query object. */ public Query createContactQuery(String subpath) { return createQuery(subpath, Contact.class); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/0000775000175000017500000000000011757206354026001 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/CafeApplication.java0000664000175000017500000000752011757206352031670 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafe; import org.restlet.Application; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.routing.Router; /** * Sample application that simulates the "Cafe" WCF service. * * @author Thierry Boileau * */ public class CafeApplication extends Application { private static class MyClapRestlet extends Restlet { String file; boolean updatable; public MyClapRestlet(Context context, String file, boolean updatable) { super(context); this.file = file; this.updatable = updatable; } @Override public void handle(Request request, Response response) { if (Method.GET.equals(request.getMethod())) { Form form = request.getResourceRef().getQueryAsForm(); String uri = "/" + this.getClass().getPackage().getName().replace(".", "/") + "/" + file; if (form.getFirstValue("$expand") != null) { uri += form.getFirstValue("$expand"); } if (form.getFirstValue("$skiptoken") != null) { uri += form.getFirstValue("$skiptoken"); } Response r = getContext().getClientDispatcher().handle( new Request(Method.GET, LocalReference .createClapReference(LocalReference.CLAP_CLASS, uri + ".xml"))); response.setEntity(r.getEntity()); response.setStatus(r.getStatus()); } else if (!updatable) { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } } @Override public Restlet createInboundRoot() { getMetadataService().setDefaultCharacterSet(CharacterSet.ISO_8859_1); getConnectorService().getClientProtocols().add(Protocol.CLAP); Router router = new Router(getContext()); router.attach("/$metadata", new MyClapRestlet(getContext(), "metadata", false)); router .attach("/Cafes", new MyClapRestlet(getContext(), "cafes", false)); router.attach("/Contacts('1')", new MyClapRestlet(getContext(), "contact1", false)); return router; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/cafesItems.xml0000664000175000017500000001152111757206354030606 0ustar jamespagejamespage Cafes http://localhost:8111/Cafe.svc/Cafes 2010-02-17T11:31:40Z http://localhost:8111/Cafe.svc/Cafes('1') 2010-02-17T11:31:40Z Items http://localhost:8111/Cafe.svc/Cafes('1')/Items 2010-02-17T11:31:40Z http://localhost:8111/Cafe.svc/Items('1') 2010-02-17T11:31:40Z 1 Poulet au curry http://localhost:8111/Cafe.svc/Items('2') 2010-02-17T11:31:40Z 2 Pate 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:31:40Z Items http://localhost:8111/Cafe.svc/Cafes('2')/Items 2010-02-17T11:31:40Z http://localhost:8111/Cafe.svc/Items('3') 2010-02-17T11:31:40Z 3 Banana Split http://localhost:8111/Cafe.svc/Items('4') 2010-02-17T11:31:40Z 4 Cotes du Rhone 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/Item.java0000664000175000017500000000514611757206352027546 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafe; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class Item { private String description; private String id; /** * Constructor without parameter. * */ public Item() { super(); } /** * Constructor. * * @param id * The identifiant value of the entity. */ public Item(String id) { this(); this.id = id; } /** * Returns the value of the description attribute. * * @return The value of the description attribute. */ public String getDescription() { return description; } /** * Returns the value of the id attribute. * * @return The value of the id attribute. */ public String getId() { return id; } /** * Sets the value of the description attribute. * * @param Description * The value of the description attribute. */ public void setDescription(String description) { this.description = description; } /** * Sets the value of the id attribute. * * @param ID * The value of the id attribute. */ public void setId(String id) { this.id = id; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/cafesSkip2.xml0000664000175000017500000000403311757206354030515 0ustar jamespagejamespage Cafes http://localhost:8111/Cafe.svc/Cafes 2010-02-17T11:28:13Z http://localhost:8111/Cafe.svc/Cafes('1') 2010-02-17T11:28:13Z 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:28:13Z 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/cafesSkip1.xml0000664000175000017500000000415711757206354030523 0ustar jamespagejamespage Cafes http://localhost:8111/Cafe.svc/Cafes 2010-02-17T11:28:13Z http://localhost:8111/Cafe.svc/Cafes('1') 2010-02-17T11:28:13Z 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:28:13Z 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/Contact.java0000664000175000017500000000565311757206352030246 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafe; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class Contact { private String id; private String name; private String title; /** * Constructor without parameter. * */ public Contact() { super(); } /** * Constructor. * * @param id * The identifiant value of the entity. */ public Contact(String id) { this(); this.id = id; } /** * Returns the value of the id attribute. * * @return The value of the id attribute. */ public String getId() { return id; } /** * Returns the value of the name attribute. * * @return The value of the name attribute. */ public String getName() { return name; } /** * Returns the value of the title attribute. * * @return The value of the title attribute. */ public String getTitle() { return title; } /** * Sets the value of the id attribute. * * @param ID * The value of the id attribute. */ public void setId(String id) { this.id = id; } /** * Sets the value of the name attribute. * * @param Name * The value of the name attribute. */ public void setName(String name) { this.name = name; } /** * Sets the value of the title attribute. * * @param Title * The value of the title attribute. */ public void setTitle(String title) { this.title = title; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/CafeService.java0000664000175000017500000000673611757206352031035 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafe; import org.restlet.ext.odata.Query; import org.restlet.ext.odata.Service; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class CafeService extends Service { /** * Constructor. * */ public CafeService() { super("http://localhost:8111/Cafe.svc"); } /** * Adds a new entity to the service. * * @param entity * The entity to add to the service. * @throws Exception */ public void addEntity(Cafe entity) throws Exception { addEntity("/Cafes", entity); } /** * Creates a query for cafe entities hosted by this service. * * @param subpath * The path to this entity relatively to the service URI. * @return A query object. */ public Query createCafeQuery(String subpath) { return createQuery(subpath, Cafe.class); } /** * Adds a new entity to the service. * * @param entity * The entity to add to the service. * @throws Exception */ public void addEntity(Item entity) throws Exception { addEntity("/Items", entity); } /** * Creates a query for item entities hosted by this service. * * @param subpath * The path to this entity relatively to the service URI. * @return A query object. */ public Query createItemQuery(String subpath) { return createQuery(subpath, Item.class); } /** * Adds a new entity to the service. * * @param entity * The entity to add to the service. * @throws Exception */ public void addEntity(Contact entity) throws Exception { addEntity("/Contacts", entity); } /** * Creates a query for contact entities hosted by this service. * * @param subpath * The path to this entity relatively to the service URI. * @return A query object. */ public Query createContactQuery(String subpath) { return createQuery(subpath, Contact.class); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/contact1.xml0000664000175000017500000000144611757206354030244 0ustar jamespagejamespage http://localhost:8111/Cafe.svc/Contacts('1') 2010-02-17T11:49:08Z 1 Agathe Zeblues Chief restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/cafesContact.xml0000664000175000017500000000643211757206354031125 0ustar jamespagejamespage Cafes http://localhost:8111/Cafe.svc/Cafes 2010-02-17T11:34:58Z http://localhost:8111/Cafe.svc/Cafes('1') 2010-02-17T11:34:58Z http://localhost:8111/Cafe.svc/Contacts('1') 2010-02-17T11:34:58Z 1 Agathe Zeblues Chief 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:34:58Z http://localhost:8111/Cafe.svc/Contacts('2') 2010-02-17T11:34:58Z 2 Alphonse Denltas Boss 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/Cafe.java0000664000175000017500000001130111757206352027474 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata.cafe; import java.util.List; import org.restlet.test.ext.odata.cafe.Contact; import org.restlet.test.ext.odata.cafe.Item; /** * Generated by the generator tool for the WCF Data Services extension for the Restlet framework.
    * * @see Metadata of the target WCF Data Services * */ public class Cafe { private String city; private String companyName; private String id; private String name; private int zipCode; private Contact contact; private List items; /** * Constructor without parameter. * */ public Cafe() { super(); } /** * Constructor. * * @param id * The identifiant value of the entity. */ public Cafe(String id) { this(); this.id = id; } /** * Returns the value of the city attribute. * * @return The value of the city attribute. */ public String getCity() { return city; } /** * Returns the value of the companyName attribute. * * @return The value of the companyName attribute. */ public String getCompanyName() { return companyName; } /** * Returns the value of the id attribute. * * @return The value of the id attribute. */ public String getId() { return id; } /** * Returns the value of the name attribute. * * @return The value of the name attribute. */ public String getName() { return name; } /** * Returns the value of the zipCode attribute. * * @return The value of the zipCode attribute. */ public int getZipCode() { return zipCode; } /** * Returns the value of the contact attribute. * * @return The value of the contact attribute. */ public Contact getContact() { return contact; } /** * Returns the value of the items attribute. * * @return The value of the items attribute. */ public List getItems() { return items; } /** * Sets the value of the city attribute. * * @param City * The value of the city attribute. */ public void setCity(String city) { this.city = city; } /** * Sets the value of the companyName attribute. * * @param CompanyName * The value of the companyName attribute. */ public void setCompanyName(String companyName) { this.companyName = companyName; } /** * Sets the value of the id attribute. * * @param ID * The value of the id attribute. */ public void setId(String id) { this.id = id; } /** * Sets the value of the name attribute. * * @param Name * The value of the name attribute. */ public void setName(String name) { this.name = name; } /** * Sets the value of the zipCode attribute. * * @param ZipCode * The value of the zipCode attribute. */ public void setZipCode(int zipCode) { this.zipCode = zipCode; } /** * Sets the value of the contact attribute. * * @param contact * The value of the contact attribute. */ public void setContact(Contact contact) { this.contact = contact; } /** * Sets the value of the items attribute. * * @param items * The value of the items attribute. */ public void setItems(List items) { this.items = items; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/metadata.xml0000664000175000017500000000574611757206354030317 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/cafe/cafes.xml0000664000175000017500000000403311757206354027604 0ustar jamespagejamespage Cafes http://localhost:8111/Cafe.svc/Cafes 2010-02-17T11:28:13Z http://localhost:8111/Cafe.svc/Cafes('1') 2010-02-17T11:28:13Z 1 Le Cafe Louis 92300 Levallois-Perret Cafe corp. http://localhost:8111/Cafe.svc/Cafes('2') 2010-02-17T11:28:13Z 2 Le Petit Marly 78310 Marly Le Roi Cafe inc. restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/ODataCafeCustoFeedsTestCase.java0000664000175000017500000001632011757206352033136 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata; import java.util.Iterator; import org.restlet.Component; import org.restlet.data.Protocol; import org.restlet.ext.odata.Query; import org.restlet.test.RestletTestCase; import org.restlet.test.ext.odata.cafecustofeeds.Cafe; import org.restlet.test.ext.odata.cafecustofeeds.CafeCustoFeedsService; import org.restlet.test.ext.odata.cafecustofeeds.Contact; import org.restlet.test.ext.odata.cafecustofeeds.Item; /** * Test case for OData customizable feeds. * * @author Thierry Boileau * */ public class ODataCafeCustoFeedsTestCase extends RestletTestCase { /** Inner component. */ private Component component = new Component(); /** OData service used for all tests. */ private CafeCustoFeedsService service; @Override protected void setUp() throws Exception { super.setUp(); component.getServers().add(Protocol.HTTP, 8111); component.getClients().add(Protocol.CLAP); component .getDefaultHost() .attach( "/CafeCustoFeeds.svc", new org.restlet.test.ext.odata.cafecustofeeds.CafeCustoFeedsApplication()); component.start(); service = new CafeCustoFeedsService(); } @Override protected void tearDown() throws Exception { component.stop(); component = null; service = null; super.tearDown(); } /** * Tests the parsing of Feed element. */ public void testQueryCafes() { Query query = service.createCafeQuery("/Cafes"); Iterator iterator = query.iterator(); assertTrue(iterator.hasNext()); Cafe cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); } /** * Tests the parsing of Feed element with expansion of the one to one * association "Contact". */ public void testQueryCafesExpandContact() { Query query1 = service.createCafeQuery("/Cafes"); Query query2 = query1.expand("Contact"); Iterator iterator = query2.iterator(); assertTrue(iterator.hasNext()); Cafe cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); Contact contact = cafe.getContact(); assertNotNull(contact); assertEquals("1", contact.getId()); assertEquals("Agathe Zeblues", contact.getName()); assertEquals("Chief", contact.getTitle()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); contact = cafe.getContact(); assertNotNull(contact); assertEquals("2", contact.getId()); assertEquals("Alphonse Denltas", contact.getName()); assertEquals("Boss", contact.getTitle()); } /** * Tests the parsing of Feed element with expansion of the one to many * association "Items". */ public void testQueryCafesExpandItem() { Query query1 = service.createCafeQuery("/Cafes"); Query query2 = query1.expand("Items"); Iterator iterator = query2.iterator(); assertTrue(iterator.hasNext()); Cafe cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); Iterator iterator2 = cafe.getItems().iterator(); assertTrue(iterator2.hasNext()); Item item = iterator2.next(); assertEquals("1", item.getId()); assertEquals("Poulet au curry", item.getDescription()); assertTrue(iterator2.hasNext()); item = iterator2.next(); assertEquals("2", item.getId()); assertEquals("Pate", item.getDescription()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); iterator2 = cafe.getItems().iterator(); assertTrue(iterator2.hasNext()); item = iterator2.next(); assertEquals("3", item.getId()); assertEquals("Banana Split", item.getDescription()); assertTrue(iterator2.hasNext()); item = iterator2.next(); assertEquals("4", item.getId()); assertEquals("Cotes du Rhone", item.getDescription()); } /** * Tests the parsing of Entry element. */ public void testQueryContact() { Query query = service.createContactQuery("/Contacts('1')"); Iterator iterator = query.iterator(); assertTrue(iterator.hasNext()); Contact contact = iterator.next(); assertNotNull(contact); assertEquals("1", contact.getId()); assertEquals("Agathe Zeblues", contact.getName()); assertEquals("Chief", contact.getTitle()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/ODataTestSuite.java0000664000175000017500000000341211757206352030606 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata; import junit.framework.Test; import junit.framework.TestSuite; /** * Suite of unit tests for the OData extension. * * @author Thierry Boileau */ public class ODataTestSuite extends TestSuite { /** * JUnit constructor. * * @return The unit test. */ public static Test suite() { return new ODataTestSuite(); } /** Constructor. */ public ODataTestSuite() { addTestSuite(ODataCafeTestCase.class); addTestSuite(ODataCafeCustoFeedsTestCase.class); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/odata/ODataCafeTestCase.java0000664000175000017500000002110411757206354031147 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.odata; import java.util.Iterator; import org.restlet.Component; import org.restlet.data.Protocol; import org.restlet.ext.odata.Query; import org.restlet.test.RestletTestCase; import org.restlet.test.ext.odata.cafe.Cafe; import org.restlet.test.ext.odata.cafe.CafeService; import org.restlet.test.ext.odata.cafe.Contact; import org.restlet.test.ext.odata.cafe.Item; /** * Test case for OData service. * * @author Thierry Boileau * */ public class ODataCafeTestCase extends RestletTestCase { /** Inner component. */ private Component component = new Component(); /** OData service used for all tests. */ private CafeService service; @Override protected void setUp() throws Exception { super.setUp(); component.getServers().add(Protocol.HTTP, 8111); component.getClients().add(Protocol.CLAP); component.getDefaultHost().attach("/Cafe.svc", new org.restlet.test.ext.odata.cafe.CafeApplication()); component.start(); service = new CafeService(); } @Override protected void tearDown() throws Exception { component.stop(); component = null; super.tearDown(); } /** * Tests the parsing of Feed element. */ public void testQueryCafes() { Query query = service.createCafeQuery("/Cafes"); Iterator iterator = query.iterator(); assertTrue(iterator.hasNext()); Cafe cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); } /** * Tests the parsing of Feed element with expansion of the one to one * association "Contact". */ public void testQueryCafesExpandContact() { Query query1 = service.createCafeQuery("/Cafes"); Query query2 = query1.expand("Contact"); Iterator iterator = query2.iterator(); assertTrue(iterator.hasNext()); Cafe cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); Contact contact = cafe.getContact(); assertNotNull(contact); assertEquals("1", contact.getId()); assertEquals("Agathe Zeblues", contact.getName()); assertEquals("Chief", contact.getTitle()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); contact = cafe.getContact(); assertNotNull(contact); assertEquals("2", contact.getId()); assertEquals("Alphonse Denltas", contact.getName()); assertEquals("Boss", contact.getTitle()); } /** * Tests the parsing of Feed element with expansion of the one to many * association "Items". */ public void testQueryCafesExpandItem() { Query query1 = service.createCafeQuery("/Cafes"); Query query2 = query1.expand("Items"); Iterator iterator = query2.iterator(); assertTrue(iterator.hasNext()); Cafe cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); Iterator iterator2 = cafe.getItems().iterator(); assertTrue(iterator2.hasNext()); Item item = iterator2.next(); assertEquals("1", item.getId()); assertEquals("Poulet au curry", item.getDescription()); assertTrue(iterator2.hasNext()); item = iterator2.next(); assertEquals("2", item.getId()); assertEquals("Pate", item.getDescription()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); iterator2 = cafe.getItems().iterator(); assertTrue(iterator2.hasNext()); item = iterator2.next(); assertEquals("3", item.getId()); assertEquals("Banana Split", item.getDescription()); assertTrue(iterator2.hasNext()); item = iterator2.next(); assertEquals("4", item.getId()); assertEquals("Cotes du Rhone", item.getDescription()); } /** * Tests the parsing of Entry element. */ public void testQueryContact() { Query query = service.createContactQuery("/Contacts('1')"); Iterator iterator = query.iterator(); assertTrue(iterator.hasNext()); Contact contact = iterator.next(); assertNotNull(contact); assertEquals("1", contact.getId()); assertEquals("Agathe Zeblues", contact.getName()); assertEquals("Chief", contact.getTitle()); } /** * Tests the server paging feature. */ public void testServerPaging() { Query query1 = service.createCafeQuery("/Cafes"); Query query2 = query1.skipToken("Skip1"); Iterator iterator = query2.iterator(); assertTrue(iterator.hasNext()); Cafe cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("1", cafe.getId()); assertEquals("Le Cafe Louis", cafe.getName()); assertEquals("Cafe corp.", cafe.getCompanyName()); assertEquals("Levallois-Perret", cafe.getCity()); assertEquals(92300, cafe.getZipCode()); assertTrue(iterator.hasNext()); cafe = iterator.next(); assertEquals("2", cafe.getId()); assertEquals("Le Petit Marly", cafe.getName()); assertEquals("Cafe inc.", cafe.getCompanyName()); assertEquals("Marly Le Roi", cafe.getCity()); assertEquals(78310, cafe.getZipCode()); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/0000775000175000017500000000000011757206354024613 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/RestletXmlTestCase.java0000664000175000017500000002116311757206352031216 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.junit.Before; import org.restlet.data.MediaType; import org.restlet.engine.util.DefaultSaxHandler; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.RestletTestCase; import org.xml.sax.SAXException; /** * Basic JUnit test case for parsing and validating two well-formed restlet.xml * files with and without the {@code xmlns} attribute and two tests for parsing * and validating an invalid restlet.xml which violates the Component.xsd * schema. */ public class RestletXmlTestCase extends RestletTestCase { private static final String _XML_BODY = "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n"; private static final String BAD_XML = "\n" + "\n" + "abcd" + _XML_BODY; private static final String XML_WITH_XMLNS = "\n" + "\n" + _XML_BODY; private static final String XML_WITHOUT_XMLNS = "\n" + "\n" + _XML_BODY; private DocumentBuilder builder; private Validator validator; // default 0-arguments constructor private Source getAsSource(String xmlString) { return new StreamSource(getAsStream(xmlString)); } private InputStream getAsStream(String xmlString) { return new ByteArrayInputStream(xmlString.getBytes()); } @Override @Before protected void setUp() throws Exception { super.setUp(); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); dbf.setXIncludeAware(true); SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); DefaultSaxHandler handler = new DefaultSaxHandler(); schemaFactory.setErrorHandler(handler); schemaFactory.setResourceResolver(handler); InputStream is = getClass().getResourceAsStream( "/org/restlet/Component.xsd"); assertNotNull("Component.xsd stream MUST NOT be null", is); StreamSource ss = new StreamSource(is); Schema schema = schemaFactory.newSchema(ss); dbf.setSchema(schema); builder = dbf.newDocumentBuilder(); builder.setErrorHandler(handler); builder.setEntityResolver(handler); validator = schema.newValidator(); } @Override protected void tearDown() throws Exception { builder = null; validator = null; super.tearDown(); } public void testParserBadXML() { System.out.println("-- testParserBadXML"); try { builder.parse(getAsStream(BAD_XML)); assertTrue(true); } catch (SAXException x) { fail("MUST be able to parse a good restlet.xml with xmlns attribute"); } catch (IOException x) { fail("MUST be able to parse a good restlet.xml with xmlns attribute"); } } public void testParserWithoutXMLNS() { System.out.println("-- testParserWithoutXMLNS"); try { builder.parse(getAsStream(XML_WITHOUT_XMLNS)); assertTrue(true); } catch (SAXException x) { fail("MUST be able to parse a good restlet.xml without xmlns attribute"); } catch (IOException x) { fail("MUST be able to parse a good restlet.xml without xmlns attribute"); } } public void testParserWithXMLNS() { System.out.println("-- testParserWithXMLNS"); try { builder.parse(getAsStream(XML_WITH_XMLNS)); assertTrue(true); } catch (SAXException x) { fail("MUST be able to parse a good restlet.xml with xmlns attribute"); } catch (IOException x) { fail("MUST be able to parse a good restlet.xml with xmlns attribute"); } } public void testValidateMethod() { System.out.println("-- testValidateMethod"); InputStream is = getClass().getResourceAsStream( "/org/restlet/Component.xsd"); assertNotNull("Component.xsd stream MUST NOT be null", is); Representation schemaRepresentation = new InputRepresentation(is, MediaType.APPLICATION_W3C_SCHEMA); DomRepresentation configRepresentation = new DomRepresentation( new StringRepresentation(XML_WITH_XMLNS)); try { configRepresentation.validate(schemaRepresentation); assertTrue(true); } catch (Exception x) { x.printStackTrace(System.err); fail(x.getLocalizedMessage()); } } public void testValidatorBadXML() { System.out.println("-- testValidatorBadXML"); try { validator.validate(getAsSource(BAD_XML)); fail("MUST NOT be able to validate bad restlet.xml"); } catch (SAXException x) { // the error must be a "cvc-complex-type.2.4.a" assertTrue("MUST detect schema violation", x.getLocalizedMessage() .startsWith("cvc-complex-type.2.4.a")); // ...and it has to refer to 'bad-element' assertTrue("MUST detect schema violation related to 'bad-element'", x.getLocalizedMessage().indexOf("bad-element") > 0); } catch (IOException x) { fail("MUST throw a SAXException only"); } } public void testValidatorWithoutXMLNS() { System.out.println("-- testValidatorWithoutXMLNS"); try { validator.validate(getAsSource(XML_WITHOUT_XMLNS)); fail("MUST NOT be able to validate restlet.xml without xmlns attribute"); } catch (SAXException x) { assertTrue(true); } catch (IOException x) { fail(""); } } public void testValidatorWithXMLNS() { System.out.println("-- testValidatorWithXMLNS"); try { validator.validate(getAsSource(XML_WITH_XMLNS)); assertTrue(true); } catch (SAXException x) { fail("MUST be able to validate restlet.xml with xmlns attribute"); } catch (IOException x) { fail("MUST be able to validate restlet.xml with xmlns attribute"); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/TransformerTestCase.java0000664000175000017500000001232011757206352031410 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.xml; import java.io.ByteArrayOutputStream; import org.restlet.Component; import org.restlet.data.MediaType; import org.restlet.ext.xml.TransformRepresentation; import org.restlet.ext.xml.Transformer; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.RestletTestCase; /** * Test case for the Transformer class. * * @author Jerome Louvel */ public class TransformerTestCase extends RestletTestCase { class FailureTracker { boolean allOk = true; final StringBuffer trackedMessages = new StringBuffer(); void report() { if (!this.allOk) { fail("TRACKER REPORT: \n" + this.trackedMessages.toString()); } } void trackFailure(String message) { System.err.println(message); this.trackedMessages.append(message + "\n"); this.allOk = false; } void trackFailure(String message, int index, Throwable e) { e.printStackTrace(); trackFailure(message + " " + index + ": " + e.getMessage()); } } public static void main(String[] args) { try { new TransformerTestCase().testTransform(); new TransformerTestCase().parallelTestTransform(); } catch (Exception e) { e.printStackTrace(); } } final String output = "cust12323.45"; // Create a source XML document final Representation source = new StringRepresentation( "" + "" + "" + "" + "23.45" + "" + "", MediaType.TEXT_XML); // Create a transform XSLT sheet final Representation xslt = new StringRepresentation( "" + "" + "" + "" + "" + "", MediaType.TEXT_XML); /** * This was removed from the automatically tested method because it is too * consuming. * * @throws Exception */ public void parallelTestTransform() throws Exception { final Component comp = new Component(); final TransformRepresentation tr = new TransformRepresentation( comp.getContext(), this.source, this.xslt); final FailureTracker tracker = new FailureTracker(); final int testVolume = 5000; final Thread[] parallelTransform = new Thread[testVolume]; for (int i = 0; i < parallelTransform.length; i++) { final int index = i; parallelTransform[i] = new Thread() { @Override public void run() { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); tr.write(out); final String result = out.toString(); assertEquals(TransformerTestCase.this.output, result); out.close(); } catch (Throwable e) { tracker.trackFailure( "Exception during write in thread ", index, e); } } }; } for (final Thread pt : parallelTransform) { pt.start(); } tracker.report(); } public void testTransform() throws Exception { final Transformer transformer = new Transformer( Transformer.MODE_REQUEST, this.xslt); final String result = transformer.transform(this.source).getText(); assertEquals(this.output, result); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/xslt/0000775000175000017500000000000011757206354025605 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/xslt/one/0000775000175000017500000000000011757206354026366 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/xslt/one/1st.xsl0000664000175000017500000000126511757206354027631 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/xslt/one/1st.xml0000664000175000017500000000007411757206354027620 0ustar jamespagejamespage 1st restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/xslt/two/0000775000175000017500000000000011757206354026416 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/xslt/two/2nd.xml0000664000175000017500000000007411757206354027624 0ustar jamespagejamespage 2nd restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/xslt/two/2nd.xsl0000664000175000017500000000062411757206354027633 0ustar jamespagejamespage restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/xml/ResolvingTransformerTestCase.java0000664000175000017500000002704111757206352033307 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.xml; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Random; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.restlet.Application; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.ext.xml.TransformRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.test.RestletTestCase; /** * ResolvingTransformerTestCase tests the resolving aspects of the * Transformer/TransformerRepresentation to guarantee proper functioning of the * xsl :import, :include and document() features. * * @author Marc Portier (mpo@outerthought.org) */ public class ResolvingTransformerTestCase extends RestletTestCase { class AssertResolvingHelper { String baseUri; URIResolver resolver; AssertResolvingHelper(String baseUri, URIResolver resolver) { this.baseUri = baseUri; this.resolver = resolver; } /** * Asserts that the testUri resolves into the expectedUri */ void assertResolving(String message, String testUri, String testData) throws TransformerException, IOException { Source resolvedSource = this.resolver .resolve(testUri, this.baseUri); assertNotNull("resolved source for " + testUri + " should not be null", resolvedSource); StringBuilder data = new StringBuilder(); if (resolvedSource instanceof StreamSource) { StreamSource streamSource = (StreamSource) resolvedSource; Reader dataReader = (streamSource).getReader(); if (dataReader == null) { InputStream in = (streamSource.getInputStream()); assertNotNull("no reader or inputstream available", in); dataReader = new InputStreamReader(in); } assertNotNull("no reader to data in source.", dataReader); char[] buf = new char[1024]; int len = 0; while ((len = dataReader.read(buf)) != -1) { data.append(buf, 0, len); } dataReader.close(); } else { // TODO support other source implementations (namely sax-source // impls) fail("test implementation currently doesn't handle other source (e.g. sax) implementations"); } assertEquals(message, testData, data.toString()); } } class SimpleUriMapApplication extends Application { private final Map uriMap = new HashMap(); public SimpleUriMapApplication() { // Turn off the useless extension tunnel. getTunnelService().setExtensionsTunnel(false); } void add(String uri, Representation rep) { this.uriMap.put(uri, rep); } @Override public Restlet createInboundRoot() { return new Restlet() { @Override public void handle(Request request, Response response) { String remainder = request.getResourceRef() .getRemainingPart(); Representation answer = SimpleUriMapApplication.this.uriMap .get(remainder); if (answer != null) { response.setEntity(answer); } } }; } } private final static String MY_BASEPATH; private final static String MY_NAME; private final static String MY_PATH; static { MY_PATH = ResolvingTransformerTestCase.class.getName() .replace('.', '/'); final int lastPos = MY_PATH.lastIndexOf('/'); MY_NAME = MY_PATH.substring(lastPos); MY_BASEPATH = MY_PATH.substring(0, lastPos); } // testing purely the resolver, no active transforming context (ie xslt // engine) in this test public void testResolving() throws Exception { Component comp = new Component(); // create an xml input representation Representation xml = new StringRepresentation( "", MediaType.TEXT_XML); // create an xsl template representation Representation xslt = new StringRepresentation( "" + "" + "", MediaType.TEXT_XML); TransformRepresentation transRep = new TransformRepresentation(comp .getContext(), xml, xslt); // create a test-stream representation to be returned when the correct // code is presented String testCode = "rnd." + (new Random()).nextInt(); String testData = "\"The resolver is doing OK\", said the testclass " + MY_NAME + "."; Representation testRep = new StringRepresentation(testData); SimpleUriMapApplication testApp = new SimpleUriMapApplication(); testApp.add(testCode, testRep); comp.getInternalRouter().attach("/testApp/", testApp); String testBase = "riap://component/testApp"; URIResolver uriResolver = transRep.getUriResolver(); assertNotNull("no resolver present!", uriResolver); String baseUri = testBase + "/dummy"; AssertResolvingHelper test = new AssertResolvingHelper(baseUri, uriResolver); String absoluteUri = testBase + "/" + testCode; test.assertResolving("error in absolute resolving.", absoluteUri, testData); String relUri = testCode; test.assertResolving("error in relative resolving.", relUri, testData); String relLocalUri = "./" + testCode; test.assertResolving("error in relative resolving to ./", relLocalUri, testData); String relParentUri = "../testApp/" + testCode; test.assertResolving("error in relative resolving to ../", relParentUri, testData); } // functional test in the actual xslt engine context public void testTransform() throws Exception { Component comp = new Component(); comp.getClients().add(Protocol.CLAP); // here is the plan / setup // * make a transformer from clap://**/xslt/one/1st.xsl // * let it import a relative xsl ../two/2nd.xsl // * let that in turn import a riap://component/three/3rd.xsl // * provide input-xml-structure input/element-1st..-3rd/** // * let each xsl call-in as well an extra document() 1st-3rd.xml with a // simple 1st // * each xsl should provide the template for one of the lines // * output should show all converted lines as read from the various // external documents String thirdDocData = "" + ("rnd." + (new Random()).nextInt()) + ""; // Note below doesn't work,: // final String xsl2xmlLink = "riap://application/3rd.xml"; // cause: the application-context one refers to with above is the one // that is creating the xslt sheet // (and the associated uri-resolver) Since that isn't an actual // application-context so it doesn't support // the riap-authority 'application' // This does work though: String xsl2xmlLink = "./3rd.xml"; // and "/three/3rd.xml" would // too... Representation xml3 = new StringRepresentation("" + thirdDocData, MediaType.TEXT_XML); Representation xslt3 = new StringRepresentation( "" + "" + " " + " " + " " + " " + "", MediaType.TEXT_XML); SimpleUriMapApplication thirdLevel = new SimpleUriMapApplication(); thirdLevel.add("3rd.xsl", xslt3); thirdLevel.add("3rd.xml", xml3); comp.getInternalRouter().attach("/three/", thirdLevel); // xml In Representation xmlIn = new StringRepresentation( "drie"); // xslOne Reference xsltOneRef = new LocalReference("clap://thread/" + MY_BASEPATH + "/xslt/one/1st.xsl"); Representation xsltOne = comp.getContext().getClientDispatcher() .handle(new Request(Method.GET, xsltOneRef)).getEntity(); TransformRepresentation tr = new TransformRepresentation(comp .getContext(), xmlIn, xsltOne); // TODO transformer output should go to SAX! The sax-event-stream should // then be fed into a DOMBuilder // and then the assertions should be written as DOM tests... // (NOTE: current string-compare assertion might fail on lexical aspects // as ignorable whitespace, encoding settings etc etc) ByteArrayOutputStream out = new ByteArrayOutputStream(); tr.write(out); String xmlOut = out.toString(); String expectedResult = "1st2nd" + thirdDocData + ""; assertEquals("xslt result doesn't match expectations", expectedResult, xmlOut); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/velocity/0000775000175000017500000000000011757206352025647 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/velocity/VelocityTestCase.java0000664000175000017500000000764211757206352031755 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.velocity; import java.io.File; import java.io.FileWriter; import java.util.Map; import java.util.TreeMap; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.engine.io.BioUtils; import org.restlet.ext.velocity.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.test.RestletTestCase; /** * Test case for the Velocity extension. * * @author Jerome Louvel */ public class VelocityTestCase extends RestletTestCase { public void testRepresentationTemplate() throws Exception { // Create a temporary directory for the tests File testDir = new File(System.getProperty("java.io.tmpdir"), "VelocityTestCase"); testDir.mkdir(); // Create a temporary template file File testFile = File.createTempFile("test", ".vm", testDir); FileWriter fw = new FileWriter(testFile); fw.write("Value=$value"); fw.close(); Map map = new TreeMap(); map.put("value", "myValue"); // Representation approach Reference ref = LocalReference.createFileReference(testFile); ClientResource r = new ClientResource(ref); Representation templateFile = r.get(); TemplateRepresentation tr = new TemplateRepresentation(templateFile, map, MediaType.TEXT_PLAIN); final String result = tr.getText(); assertEquals("Value=myValue", result); // Clean-up BioUtils.delete(testFile); BioUtils.delete(testDir, true); } public void testStandardTemplate() throws Exception { // Create a temporary directory for the tests final File testDir = new File(System.getProperty("java.io.tmpdir"), "VelocityTestCase"); testDir.mkdir(); // Create a temporary template file final File testFile = File.createTempFile("test", ".vm", testDir); final FileWriter fw = new FileWriter(testFile); fw.write("Value=$value"); fw.close(); final Map map = new TreeMap(); map.put("value", "myValue"); // Standard approach final TemplateRepresentation tr = new TemplateRepresentation(testFile .getName(), map, MediaType.TEXT_PLAIN); tr.getEngine().setProperty("file.resource.loader.path", testDir.getAbsolutePath()); final String result = tr.getText(); assertEquals("Value=myValue", result); // Clean-up BioUtils.delete(testFile); BioUtils.delete(testDir, true); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/lucene/0000775000175000017500000000000011757206354025266 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/lucene/LuceneTestCase.java0000664000175000017500000000502711757206354031004 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.ext.lucene; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.apache.tika.parser.rtf.RTFParser; import org.restlet.ext.lucene.TikaRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.test.RestletTestCase; /** * Unit tests for the Lucene extension. * * @author Jerome Louvel */ public class LuceneTestCase extends RestletTestCase { public void testTika() throws Exception { ClientResource r = new ClientResource( "clap://system/org/restlet/test/ext/lucene/LuceneTestCase.rtf"); Representation rtfSample = r.get(); // rtfSample.write(System.out); // Prepare a SAX content handler SAXTransformerFactory factory = ((SAXTransformerFactory) TransformerFactory .newInstance()); TransformerHandler transform = factory.newTransformerHandler(); transform.setResult(new StreamResult(System.out)); // Analyze the RTF representation TikaRepresentation tr = new TikaRepresentation(rtfSample); tr.setTikaParser(new RTFParser()); tr.parse(transform); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/ext/lucene/LuceneTestCase.rtf0000664000175000017500000001657611757206354030671 0ustar jamespagejamespage{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff0\deff0\stshfdbch0\stshfloch0\stshfhich0\stshfbi0\deflang1036\deflangfe1036{\fonttbl{\f0\froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f37\froman\fcharset238\fprq2 Times New Roman CE;}{\f38\froman\fcharset204\fprq2 Times New Roman Cyr;} {\f40\froman\fcharset161\fprq2 Times New Roman Greek;}{\f41\froman\fcharset162\fprq2 Times New Roman Tur;}{\f42\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f43\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);} {\f44\froman\fcharset186\fprq2 Times New Roman Baltic;}{\f45\froman\fcharset163\fprq2 Times New Roman (Vietnamese);}}{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255; \red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;} {\stylesheet{\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 \snext0 Normal;}{\*\cs10 \additive \ssemihidden Default Paragraph Font;}{\*\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\trcbpat1\trcfpat1\tblind0\tblindtype3\tscellwidthfts0\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv \ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs20 \ltrch\fcs0 \fs20\lang1024\langfe1024\cgrid\langnp1024\langfenp1024 \snext11 \ssemihidden Normal Table;}{\s15\ql \li0\ri0\widctlpar \tqc\tx4536\tqr\tx9072\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 \sbasedon0 \snext15 \styrsid13858392 header;}{ \s16\ql \li0\ri0\widctlpar\tqc\tx4536\tqr\tx9072\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 \sbasedon0 \snext16 \styrsid13858392 footer;}{\s17\ql \li0\ri0\sb100\sa100\sbauto1\saauto1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 \sbasedon0 \snext17 \styrsid13858392 Normal (Web);}{\*\cs18 \additive \rtlch\fcs1 \af0 \ltrch\fcs0 \ul\cf2 \sbasedon10 \styrsid13858392 Hyperlink;}}{\*\latentstyles\lsdstimax156\lsdlockeddef0}{\*\pgptbl {\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}} {\*\rsidtbl \rsid5582936\rsid7097383\rsid8676977\rsid11236168\rsid11499920\rsid13858392\rsid16064046}{\*\generator Microsoft Word 11.0.0000;}{\info{\title Tika uses Java's built-in Swing library to parse Rich Text Format (RTF) documents} {\author Jerome Louvel}{\operator Jerome Louvel}{\creatim\yr2009\mo1\dy11\hr15\min46}{\revtim\yr2009\mo1\dy11\hr15\min47}{\version1}{\edmins1}{\nofpages1}{\nofwords60}{\nofchars336}{\*\company Restlet S.A.S.}{\nofcharsws395} {\vern24613}{\*\password 00000000}}{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}\paperw11907\paperh16840\margl1418\margr1418\margt1418\margb1418\gutter0\ltrsect \deftab708\widowctrl\ftnbj\aenddoc\hyphhotz425\donotembedsysfont1\donotembedlingdata0\grfdocevents0\validatexml1\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors1\noxlattoyen\expshrtn \noultrlspc\dntblnsbdb\nospaceforul\formshade\horzdoc\dgmargin\dghspace120\dgvspace180\dghorigin1418\dgvorigin1418\dghshow2\dgvshow2 \jexpand\viewkind1\viewscale100\pgbrdrhead\pgbrdrfoot\splytwnine\ftnlytwnine\htmautsp\nolnhtadjtbl\useltbaln\alntblind\lytcalctblwd\lyttblrtgr\lnbrkrule\nobrkwrptbl\snaptogridincell\allowfieldendsel\wrppunct \asianbrkrule\rsidroot13858392\newtblstyruls\nogrowautofit\viewbksp1 \fet0{\*\wgrffmtfilter 013f}\ilfomacatclnup0{\*\ftnsep \ltrpar \pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 \chftnsep \par }}{\*\ftnsepc \ltrpar \pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 \chftnsepc \par }}{\*\aftnsep \ltrpar \pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 \chftnsep \par }}{\*\aftnsepc \ltrpar \pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 \chftnsepc \par }}\ltrpar \sectd \ltrsect\psz9\linex0\headery1418\footery1418\colsx708\endnhere\sectlinegrid360\sectdefaultcl\sectrsid11236168\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}} \pard\plain \ltrpar\ql \li720\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin720\itap0\pararsid13858392 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 Tika uses Java's built-in Swing library to parse Rich Text Format (RTF) documents. Support for RTF was added in Tika 0.1. \par }\pard\plain \ltrpar\s17\ql \li720\ri0\sb100\sa100\sbauto1\saauto1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin720\itap0\pararsid13858392 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 The RTF parser in Tika uses the Swing }{\field\fldedit{\*\fldinst {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 HYPERLINK "http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/text/rtf/RTFEditorKit.html" }}{\fldrslt {\rtlch\fcs1 \af0 \ltrch\fcs0 \cs18\ul\cf2\insrsid13858392 RTFEditorKit}}}\sectd \psz9\linex0\headery1418\footery1418\colsx708\endnhere\sectlinegrid360\sectdefaultcl\sectrsid11236168\sftnbj {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid13858392 class to extract all text from an RTF document as a single paragraph. Document metadata extraction is currently not supported. \par }\pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1036\langfe1036\cgrid\langnp1036\langfenp1036 {\rtlch\fcs1 \af0 \ltrch\fcs0 \insrsid16064046 \par }}restlet-2.0.14/org.restlet.test/src/org/restlet/test/bench/0000775000175000017500000000000011757206354024272 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/bench/TestGetClient.java0000664000175000017500000000462211757206354027657 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.bench; import java.io.IOException; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; public class TestGetClient { public static void main(String[] args) throws IOException { long startTime = System.currentTimeMillis(); ClientResource resource = new ClientResource("http://localhost:8554/"); try { Representation entity = resource.get(); System.out.println("Status: " + resource.getStatus()); long expectedSize = entity.getSize(); long receivedSize = entity.exhaust(); System.out.println("Size expected: " + expectedSize); System.out.println("Size consumed: " + receivedSize); if ((expectedSize != -1) && (expectedSize != receivedSize)) { System.out.println("ERROR: SOME BYTES WERE LOST!"); } } catch (ResourceException e) { System.out.println("Status: " + resource.getStatus()); } long endTime = System.currentTimeMillis(); System.out.println("Duration: " + (endTime - startTime) + " ms"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/bench/TestPostClient.java0000664000175000017500000000415711757206352030066 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.bench; import org.restlet.data.MediaType; import org.restlet.representation.FileRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; public class TestPostClient { public static void main(String[] args) { long startTime = System.currentTimeMillis(); ClientResource resource = new ClientResource("http://localhost:8554/"); FileRepresentation fr = new FileRepresentation("file:///c:/test.mpg", MediaType.VIDEO_MPEG); System.out.println("Size sent: " + fr.getSize()); try { resource.post(fr); } catch (ResourceException e) { // Nothing } System.out.println("Status: " + resource.getStatus()); long endTime = System.currentTimeMillis(); System.out.println("Duration: " + (endTime - startTime) + " ms"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/bench/TestGetServer.java0000664000175000017500000000402311757206354027702 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.bench; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.representation.FileRepresentation; public class TestGetServer { public static void main(String[] args) throws Exception { Server server = new Server(Protocol.HTTP, 8554, new Restlet() { @Override public void handle(Request request, Response response) { FileRepresentation fr = new FileRepresentation( "file:///c:/test.mpg", MediaType.VIDEO_MPEG); System.out.println("Size sent: " + fr.getSize()); response.setEntity(fr); } }); server.start(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/bench/TestPostChunkedClient.java0000664000175000017500000000451211757206354031365 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.bench; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.representation.FileRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; public class TestPostChunkedClient { public static void main(String[] args) throws IOException { long startTime = System.currentTimeMillis(); ClientResource resource = new ClientResource("http://localhost:8554/"); FileRepresentation fr = new FileRepresentation("file:///c:/test.mpg", MediaType.VIDEO_MPEG); System.out.println("Size sent: " + fr.getSize()); InputRepresentation ir = new InputRepresentation(fr.getStream(), fr .getMediaType()); try { resource.post(ir); } catch (ResourceException e) { // Nothing } System.out.println("Status: " + resource.getStatus()); long endTime = System.currentTimeMillis(); System.out.println("Duration: " + (endTime - startTime) + " ms"); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/bench/TestPostServer.java0000664000175000017500000000476611757206352030124 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.bench; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; public class TestPostServer { public static void main(String[] args) throws Exception { Server server = new Server(Protocol.HTTP, 8554, new Restlet() { int count = 0; @Override public void handle(Request request, Response response) { try { System.out.println("Request received (" + (++count) + ")"); long expectedSize = request.getEntity().getSize(); long receivedSize = request.getEntity().exhaust(); System.out.println("Size expected: " + expectedSize); System.out.println("Size consumed: " + receivedSize); if ((expectedSize != -1) && (expectedSize != receivedSize)) { System.out.println("ERROR: SOME BYTES WERE LOST!"); } System.out .println("--------------------------------------"); } catch (Exception e) { e.printStackTrace(); } } }); server.start(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/bench/TestGetChunkedServer.java0000664000175000017500000000457711757206352031220 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.bench; import java.io.IOException; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.representation.FileRepresentation; import org.restlet.representation.InputRepresentation; public class TestGetChunkedServer { public static void main(String[] args) throws Exception { Server server = new Server(Protocol.HTTP, 8554, new Restlet() { @Override public void handle(Request request, Response response) { try { FileRepresentation fr = new FileRepresentation( "file:///c:/test.mpg", MediaType.VIDEO_MPEG); System.out.println("Size sent: " + fr.getSize()); InputRepresentation ir = new InputRepresentation(fr .getStream(), fr.getMediaType()); response.setEntity(ir); } catch (IOException e) { e.printStackTrace(); } } }); server.start(); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/security/0000775000175000017500000000000011757206354025062 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.test/src/org/restlet/test/security/SaasComponent.java0000664000175000017500000000664011757206352030503 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.security; import org.restlet.Component; import org.restlet.Context; import org.restlet.data.Protocol; import org.restlet.security.Group; import org.restlet.security.MemoryRealm; import org.restlet.security.User; import org.restlet.test.RestletTestCase; /** * Sample SAAS component with declared organizations. * * @author Jerome Louvel */ public class SaasComponent extends Component { public SaasComponent() { Context context = getContext().createChildContext(); SaasApplication app = new SaasApplication(context); MemoryRealm realm = new MemoryRealm(); context.setDefaultEnroler(realm.getEnroler()); context.setDefaultVerifier(realm.getVerifier()); // Add users User stiger = new User("stiger", "pwd", "Scott", "Tiger", "scott.tiger@foobar.com"); realm.getUsers().add(stiger); User larmstrong = new User("larmstrong", "pwd", "Louis", "Armstrong", "la@foobar.com"); realm.getUsers().add(larmstrong); // Add groups Group employees = new Group("employees ", "All FooBar employees"); employees.getMemberUsers().add(larmstrong); realm.getRootGroups().add(employees); Group contractors = new Group("contractors ", "All FooBar contractors"); contractors.getMemberUsers().add(stiger); realm.getRootGroups().add(contractors); Group managers = new Group("managers", "All FooBar managers"); realm.getRootGroups().add(managers); Group directors = new Group("directors ", "Top-level directors"); directors.getMemberUsers().add(larmstrong); managers.getMemberGroups().add(directors); Group developers = new Group("developers", "All FooBar developers"); realm.getRootGroups().add(developers); Group engineers = new Group("engineers", "All FooBar engineers"); engineers.getMemberUsers().add(stiger); developers.getMemberGroups().add(engineers); // realm.map(customer1, app.getRole("user")); realm.map(managers, app.getRole("admin")); getDefaultHost().attach(app); getServers().add(Protocol.HTTP, RestletTestCase.TEST_PORT); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/security/SaasApplication.java0000664000175000017500000000722011757206352030777 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.security; import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.routing.Router; import org.restlet.security.Authorizer; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.Role; import org.restlet.security.RoleAuthorizer; import org.restlet.test.component.HelloWorldRestlet; /** * Sample SAAS application with a Basic authenticator guarding a hello world * Restlet. * * @author Jerome Louvel */ public class SaasApplication extends Application { public SaasApplication() { this(null); } public SaasApplication(Context context) { super(context); Role admin = new Role("admin", "Application administrators"); getRoles().add(admin); Role user = new Role("user", "Application users"); getRoles().add(user); } @Override public Restlet createInboundRoot() { Router root = new Router(); // Attach test 1 ChallengeAuthenticator authenticator = new ChallengeAuthenticator( getContext(), ChallengeScheme.HTTP_BASIC, "saas"); authenticator.setNext(new HelloWorldRestlet()); root.attach("/test1", authenticator); // Attach test 2 Authorizer authorizer = Authorizer.ALWAYS; authorizer.setNext(new HelloWorldRestlet()); root.attach("/test2", authorizer); // Attach test 3 authorizer = Authorizer.NEVER; authorizer.setNext(new HelloWorldRestlet()); root.attach("/test3", authorizer); // Attach test 4 RoleAuthorizer roleAuthorizer = new RoleAuthorizer(); roleAuthorizer.getAuthorizedRoles().add(getRole("admin")); roleAuthorizer.setNext(new HelloWorldRestlet()); authenticator = new ChallengeAuthenticator(getContext(), ChallengeScheme.HTTP_BASIC, "saas"); authenticator.setNext(roleAuthorizer); root.attach("/test4", authenticator); // Attach test 5 roleAuthorizer = new RoleAuthorizer(); roleAuthorizer.getForbiddenRoles().add(getRole("admin")); roleAuthorizer.setNext(new HelloWorldRestlet()); authenticator = new ChallengeAuthenticator(getContext(), ChallengeScheme.HTTP_BASIC, "saas"); authenticator.setNext(roleAuthorizer); root.attach("/test5", authenticator); return root; } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/security/DigestVerifierTestCase.java0000664000175000017500000000560611757206354032303 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.security; import org.restlet.data.Digest; import org.restlet.ext.crypto.DigestVerifier; import org.restlet.security.MapVerifier; import org.restlet.test.RestletTestCase; /** * Restlet unit tests for the DigestVerifierTestCase class. * * @author Jerome Louvel */ public class DigestVerifierTestCase extends RestletTestCase { public void test1() { MapVerifier mv = new MapVerifier(); mv.getLocalSecrets().put("scott", "tiger".toCharArray()); DigestVerifier sdv = new DigestVerifier( Digest.ALGORITHM_SHA_1, mv, null); assertTrue(sdv.verify("scott", "RuPXcqGIjq3/JsetpH/XUC15bgc=" .toCharArray())); } public void test2() { MapVerifier mv = new MapVerifier(); mv.getLocalSecrets().put("scott", "RuPXcqGIjq3/JsetpH/XUC15bgc=".toCharArray()); DigestVerifier sdv = new DigestVerifier( Digest.ALGORITHM_SHA_1, mv, Digest.ALGORITHM_SHA_1); assertTrue(sdv.verify("scott", "RuPXcqGIjq3/JsetpH/XUC15bgc=" .toCharArray())); assertFalse(sdv.verify("scott", "xxxxx".toCharArray())); assertFalse(sdv.verify("tom", "RuPXcqGIjq3/JsetpH/XUC15bgc=" .toCharArray())); } public void test3() { MapVerifier mv = new MapVerifier(); mv.getLocalSecrets().put("scott", "RuPXcqGIjq3/JsetpH/XUC15bgc=".toCharArray()); DigestVerifier sdv = new DigestVerifier(null, mv, Digest.ALGORITHM_SHA_1); assertTrue(sdv.verify("scott", "tiger".toCharArray())); } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/security/SecurityTestCase.java0000664000175000017500000001274011757206354031174 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.security; import org.junit.After; import org.junit.Before; import org.restlet.Component; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Status; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Restlet unit tests for the security package. * * @author Jerome Louvel */ public class SecurityTestCase extends RestletTestCase { private Component component; @Before public void startComponent() throws Exception { this.component = new SaasComponent(); this.component.start(); } @After public void stopServer() throws Exception { if ((this.component != null) && this.component.isStarted()) { this.component.stop(); } this.component = null; } public void testSecurity() { try { startComponent(); String uri = "http://localhost:" + TEST_PORT + "/test1"; ClientResource resource = new ClientResource(uri); // TEST SERIES 1 // Try without authentication try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, resource.getStatus()); // Try with authentication resource.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "stiger", "pwd")); try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.SUCCESS_OK, resource.getStatus()); // TEST SERIES 2 uri = "http://localhost:" + TEST_PORT + "/test2"; resource = new ClientResource(uri); try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.SUCCESS_OK, resource.getStatus()); // TEST SERIES 3 uri = "http://localhost:" + TEST_PORT + "/test3"; resource = new ClientResource(uri); try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, resource.getStatus()); // TEST SERIES 4 uri = "http://localhost:" + TEST_PORT + "/test4"; resource = new ClientResource(uri); resource.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "stiger", "pwd")); try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, resource.getStatus()); // Try again with another user resource.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "larmstrong", "pwd")); try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.SUCCESS_OK, resource.getStatus()); // TEST SERIES 5 uri = "http://localhost:" + TEST_PORT + "/test5"; resource = new ClientResource(uri); resource.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "stiger", "pwd")); try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.SUCCESS_OK, resource.getStatus()); // Try again with another user resource.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_BASIC, "larmstrong", "pwd")); try { resource.get(); } catch (ResourceException e) { } resource.release(); assertEquals(Status.CLIENT_ERROR_FORBIDDEN, resource.getStatus()); stopServer(); } catch (Exception e) { e.printStackTrace(); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/security/HttpDigestTestCase.java0000664000175000017500000001165411757206352031445 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.security; import org.junit.Test; import org.restlet.Application; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.ext.crypto.DigestAuthenticator; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.routing.Router; import org.restlet.security.MapVerifier; import org.restlet.test.RestletTestCase; /** * Restlet unit tests for HTTP DIGEST authentication client/server. * * @author Jerome Louvel */ public class HttpDigestTestCase extends RestletTestCase { private Component component; private int port; private static class MyApplication extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); DigestAuthenticator da = new DigestAuthenticator(getContext(), "TestRealm", "mySecretServerKey"); MapVerifier mapVerifier = new MapVerifier(); mapVerifier.getLocalSecrets().put("scott", "tiger".toCharArray()); da.setWrappedVerifier(mapVerifier); Restlet restlet = new Restlet(getContext()) { @Override public void handle(Request request, Response response) { response.setEntity("hello, world", MediaType.TEXT_PLAIN); } }; da.setNext(restlet); router.attach("/", da); return router; } } @Override protected void setUp() throws Exception { component = new Component(); Server server = component.getServers().add(Protocol.HTTP, 0); Application application = new MyApplication(); component.getDefaultHost().attach(application); component.start(); port = server.getEphemeralPort(); super.setUp(); } @Override protected void tearDown() throws Exception { component.stop(); component = null; super.tearDown(); } @Test public void testDigest() throws Exception { ClientResource cr = new ClientResource("http://localhost:" + port + "/"); // Try unauthenticated request try { cr.get(); } catch (ResourceException re) { assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, cr.getStatus()); ChallengeRequest c1 = null; for (ChallengeRequest challengeRequest : cr.getChallengeRequests()) { if (ChallengeScheme.HTTP_DIGEST.equals(challengeRequest .getScheme())) { c1 = challengeRequest; break; } } assertEquals(ChallengeScheme.HTTP_DIGEST, c1.getScheme()); String realm = c1.getRealm(); assertEquals("TestRealm", realm); // String opaque = c1.getParameters().getFirstValue("opaque"); // String qop = c1.getParameters().getFirstValue("qop"); // assertEquals(null, opaque); // assertEquals("auth", qop); // Try authenticated request cr.getRequest().setMethod(Method.GET); ChallengeResponse c2 = new ChallengeResponse(c1, cr.getResponse(), "scott", "tiger".toCharArray()); cr.setChallengeResponse(c2); cr.get(); assertTrue(cr.getStatus().isSuccess()); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/security/HttpBasicTestCase.java0000664000175000017500000002425411757206354031251 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.security; import java.util.Arrays; import org.junit.After; import org.junit.Before; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.MapVerifier; import org.restlet.test.RestletTestCase; /** * Restlet unit tests for HTTP Basic authentication client/server. By default, * runs server on localhost on port {@value #DEFAULT_PORT}, which can be * overridden by setting system property {@value #RESTLET_TEST_PORT} * * @author Stian Soiland * @author Jerome Louvel */ public class HttpBasicTestCase extends RestletTestCase { public class AuthenticatedRestlet extends Restlet { @Override public void handle(Request request, Response response) { response.setEntity(AUTHENTICATED_MSG, MediaType.TEXT_PLAIN); } } public class TestVerifier extends MapVerifier { public TestVerifier() { getLocalSecrets().put(SHORT_USERNAME, SHORT_PASSWORD.toCharArray()); getLocalSecrets().put(LONG_USERNAME, LONG_PASSWORD.toCharArray()); } @Override public boolean verify(String identifier, char[] inputSecret) { // NOTE: Allocating Strings are not really secure treatment of // passwords final String almostSecret = new String(inputSecret); System.out.println("Checking " + identifier + " " + almostSecret); try { return super.verify(identifier, inputSecret); } finally { // Clear secret from memory as soon as possible (This is better // treatment, but of course useless due to our almostSecret // copy) Arrays.fill(inputSecret, '\000'); } } } public static final String WRONG_USERNAME = "wrongUser"; public static final String SHORT_USERNAME = "user13"; public static final String SHORT_PASSWORD = "pw15"; public static final String LONG_USERNAME = "aVeryLongUsernameIsIndeedRequiredForThisTest"; public static final String LONG_PASSWORD = "thisLongPasswordIsExtremelySecure"; public static final String AUTHENTICATED_MSG = "You are authenticated"; public static void main(String[] args) { new HttpBasicTestCase().testHTTPBasic(); } private Component component; private String uri; private ChallengeAuthenticator authenticator; private MapVerifier verifier; public void guardLong() { assertTrue("Didn't authenticate short user/pwd", this.verifier.verify( LONG_USERNAME, LONG_PASSWORD.toCharArray())); } public void guardLongWrong() { assertFalse("Authenticated long username with wrong password", this.verifier.verify(LONG_USERNAME, SHORT_PASSWORD .toCharArray())); } // Test our guard.checkSecret() stand-alone public void guardShort() { assertTrue("Didn't authenticate short user/pwd", this.verifier.verify( SHORT_USERNAME, SHORT_PASSWORD.toCharArray())); } public void guardShortWrong() { assertFalse("Authenticated short username with wrong password", this.verifier.verify(SHORT_USERNAME, LONG_PASSWORD .toCharArray())); } public void guardWrongUser() { assertFalse("Authenticated wrong username", this.verifier.verify( WRONG_USERNAME, SHORT_PASSWORD.toCharArray())); } public void HTTPBasicLong() throws Exception { final Request request = new Request(Method.GET, this.uri); final Client client = new Client(Protocol.HTTP); final ChallengeResponse authentication = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, LONG_USERNAME, LONG_PASSWORD); request.setChallengeResponse(authentication); final Response response = client.handle(request); assertEquals("Long username did not return 200 OK", Status.SUCCESS_OK, response.getStatus()); assertEquals(AUTHENTICATED_MSG, response.getEntity().getText()); client.stop(); } public void HTTPBasicLongWrong() throws Exception { final Request request = new Request(Method.GET, this.uri); final Client client = new Client(Protocol.HTTP); final ChallengeResponse authentication = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, LONG_USERNAME, SHORT_PASSWORD); request.setChallengeResponse(authentication); final Response response = client.handle(request); assertEquals("Long username w/wrong pw did not throw 403", Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); client.stop(); } // Test various HTTP Basic auth connections public void HTTPBasicNone() throws Exception { final Request request = new Request(Method.GET, this.uri); final Client client = new Client(Protocol.HTTP); final Response response = client.handle(request); assertEquals("No user did not throw 401", Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); client.stop(); } public void HTTPBasicShort() throws Exception { final Request request = new Request(Method.GET, this.uri); final Client client = new Client(Protocol.HTTP); final ChallengeResponse authentication = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, SHORT_USERNAME, SHORT_PASSWORD); request.setChallengeResponse(authentication); final Response response = client.handle(request); assertEquals("Short username did not return 200 OK", Status.SUCCESS_OK, response.getStatus()); assertEquals(AUTHENTICATED_MSG, response.getEntity().getText()); client.stop(); } public void HTTPBasicShortWrong() throws Exception { final Request request = new Request(Method.GET, this.uri); final Client client = new Client(Protocol.HTTP); final ChallengeResponse authentication = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, SHORT_USERNAME, LONG_PASSWORD); request.setChallengeResponse(authentication); final Response response = client.handle(request); assertEquals("Short username did not throw 401", Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); client.stop(); } public void HTTPBasicWrongUser() throws Exception { final Request request = new Request(Method.GET, this.uri); final Client client = new Client(Protocol.HTTP); final ChallengeResponse authentication = new ChallengeResponse( ChallengeScheme.HTTP_BASIC, WRONG_USERNAME, SHORT_PASSWORD); request.setChallengeResponse(authentication); final Response response = client.handle(request); assertEquals("Wrong username did not throw 401", Status.CLIENT_ERROR_UNAUTHORIZED, response.getStatus()); client.stop(); } @Before public void makeServer() throws Exception { int port = TEST_PORT; this.component = new Component(); this.component.getServers().add(Protocol.HTTP, port); this.uri = "http://localhost:" + port + "/"; final Application application = new Application() { @Override public Restlet createInboundRoot() { HttpBasicTestCase.this.verifier = new TestVerifier(); HttpBasicTestCase.this.authenticator = new ChallengeAuthenticator( getContext(), ChallengeScheme.HTTP_BASIC, HttpBasicTestCase.class.getSimpleName()); HttpBasicTestCase.this.authenticator .setVerifier(HttpBasicTestCase.this.verifier); HttpBasicTestCase.this.authenticator .setNext(new AuthenticatedRestlet()); return HttpBasicTestCase.this.authenticator; } }; this.component.getDefaultHost().attach(application); this.component.start(); } @After public void stopServer() throws Exception { if ((this.component != null) && this.component.isStarted()) { this.component.stop(); } this.component = null; } public void testHTTPBasic() { try { makeServer(); HTTPBasicWrongUser(); HTTPBasicShort(); HTTPBasicShortWrong(); HTTPBasicNone(); HTTPBasicLong(); HTTPBasicLongWrong(); stopServer(); } catch (Exception e) { e.printStackTrace(); } } } restlet-2.0.14/org.restlet.test/src/org/restlet/test/security/RoleTestCase.java0000664000175000017500000000415511757206352030265 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.security; import org.restlet.security.Role; import org.restlet.test.RestletTestCase; /** * Suite of unit tests for the {@link Role} class. * * @author Thierry Boileau */ public class RoleTestCase extends RestletTestCase { public void testRoleEquality() { Role role1 = new Role("role", ""); Role role2 = new Role("role", ""); assertEquals(role1, role2); Role role3 = new Role("role3", ""); Role role4 = new Role("role4", ""); role1.getChildRoles().add(role3); role1.getChildRoles().add(role4); assertNotSame(role1, role2); role2.getChildRoles().add(role4); role2.getChildRoles().add(role3); assertNotSame(role1, role2); role2.getChildRoles().clear(); role2.getChildRoles().add(role3); role2.getChildRoles().add(role4); assertEquals(role1, role2); } } restlet-2.0.14/org.restlet.ext.odata/0000775000175000017500000000000012001473132020063 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/pom.xml0000600000175000017500000000251212001473132021366 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.odata Restlet Extension - OData service Integration with OData services. org.freemarker freemarker 2.3.19 org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.atom 2.0.14 org.restlet.jse org.restlet.ext.freemarker 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 restlet-2.0.14/org.restlet.ext.odata/src/0000775000175000017500000000000012001473132020652 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/META-INF/0000775000175000017500000000000011757206452022032 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023463 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.odata/src/org/0000775000175000017500000000000011757206344021461 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/0000775000175000017500000000000011757206344023143 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/0000775000175000017500000000000011757206344023743 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/0000775000175000017500000000000011757206344025033 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/0000775000175000017500000000000011757206344026647 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/reflect/0000775000175000017500000000000011757206344030273 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/reflect/ReflectUtils.java0000664000175000017500000004541011757206344033547 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.reflect; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.ext.atom.Category; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.ext.odata.internal.edm.Property; import org.restlet.ext.odata.internal.edm.TypeUtils; /** * Handles Java reflection operations. * * @author Thierry Boileau */ public class ReflectUtils { /** The internal logger. */ private final static Logger logger = Context.getCurrentLogger(); /** List of reserved Java words. */ private final static List reservedWords = Arrays.asList("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "double", "else", "enum", "extends", "final", "finally", "float", "for", "if", "goto", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "switch", "synchronized", "this", "throw", "transient", "try", "void", "volatile", "while"); /** * Returns the Java class of a set of entries contained inside a Feed. * * @param feed * The feed to analyze. * @return The Java class of a set of entries contained inside a Feed or * null if it has not been found. */ public static Class getEntryClass(Feed feed) { Class result = null; if (feed != null && feed.getEntries() != null && !feed.getEntries().isEmpty()) { for (Entry entry : feed.getEntries()) { if (entry.getCategories() != null && !entry.getCategories().isEmpty()) { Category category = entry.getCategories().get(0); try { result = Class.forName(TypeUtils .getFullClassName(category.getTerm())); break; } catch (ClassNotFoundException e) { continue; } } } } return result; } /** * Returns the class of this entity's attribute, or if it is a Collection * (array, generic list, set), it returns the generic type. * * @param entity * The entity. * @param propertyName * The property name. * @return The simple class of this entity's attribute. */ public static Class getSimpleClass(Object entity, String propertyName) { Class result = null; String normPteName = normalize(propertyName); try { Field field = entity.getClass().getDeclaredField(normPteName); if (field.getType().isArray()) { result = field.getType().getComponentType(); } else { java.lang.reflect.Type genericFieldType = field .getGenericType(); if (genericFieldType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericFieldType; java.lang.reflect.Type[] fieldArgTypes = aType .getActualTypeArguments(); if (fieldArgTypes.length == 1) { result = (Class) fieldArgTypes[0]; } } else { result = field.getType(); } } } catch (Exception e) { logger.log(Level.WARNING, "Can't access to the following property " + normPteName + " on " + entity.getClass() + ".", e); } return result; } /** * Returns the value of a property on an entity based on its name. * * @param entity * The entity. * @param propertyName * The property name. * @return The value of a property for an entity. * @throws Exception */ public static Object invokeGetter(Object entity, String propertyName) throws Exception { Object result = null; if (propertyName != null && entity != null) { propertyName = propertyName.replaceAll("/", "."); Object o = entity; String pty = propertyName; int index = propertyName.indexOf("."); if (index != -1) { o = invokeGetter(entity, propertyName.substring(0, index)); pty = propertyName.substring(index + 1); result = invokeGetter(o, pty); } else { String getterName = null; char firstLetter = propertyName.charAt(0); if (Character.isLowerCase(firstLetter)) { getterName = "get" + Character.toUpperCase(firstLetter) + pty.substring(1); } else { getterName = "get" + pty; } Method getter = null; Method method; for (int i = 0; (getter == null) && (i < entity.getClass().getDeclaredMethods().length); i++) { method = entity.getClass().getDeclaredMethods()[i]; if (method.getName().equals(getterName)) { getter = method; } } if (getter != null) { result = getter.invoke(o); } } } return result; } /** * Sets a property on an entity based on its name. * * @param entity * The entity to update. * @param propertyName * The property name. * @param propertyValue * The property value. * @throws Exception */ public static void invokeSetter(Object entity, String propertyName, Object propertyValue) throws Exception { if (propertyName != null && entity != null) { propertyName = propertyName.replaceAll("/", "."); Object o = entity; String pty = propertyName; String[] strings = propertyName.split("\\."); if (strings.length > 1) { for (int i = 0; i < strings.length - 1; i++) { String string = strings[i]; Object p = invokeGetter(o, string); if (p == null) { // Try to instantiate it Field[] fields = o.getClass().getDeclaredFields(); for (Field field : fields) { if (field.getName().equalsIgnoreCase(string)) { p = field.getType().newInstance(); break; } } } o = p; } pty = strings[strings.length - 1]; } String setterName = null; char firstLetter = pty.charAt(0); if (Character.isLowerCase(firstLetter)) { setterName = "set" + Character.toUpperCase(firstLetter) + pty.substring(1); } else { setterName = "set" + pty; } Method setter = null; Method method; for (int i = 0; (setter == null) && (i < o.getClass().getDeclaredMethods().length); i++) { method = o.getClass().getDeclaredMethods()[i]; if (method.getName().equals(setterName)) { if ((method.getParameterTypes() != null) && (method.getParameterTypes().length == 1)) { setter = method; } } } if (setter != null) { setter.invoke(o, propertyValue); } } } /** * Sets a property on an entity based on its name. * * @param entity * The entity to update. * @param propertyName * The property name. * @param propertyValue * The property value. * @param propertyType * The property data type. * @throws Exception */ public static void invokeSetter(Object entity, String propertyName, String propertyValue, String propertyType) throws Exception { if (propertyName != null) { propertyName = propertyName.replaceAll("/", "."); Object o = entity; String pty = propertyName; String[] strings = propertyName.split("\\."); if (strings.length > 1) { for (int i = 0; i < strings.length - 1; i++) { String string = strings[i]; Object p = invokeGetter(o, string); if (p == null) { // Try to instantiate it Field[] fields = o.getClass().getDeclaredFields(); for (Field field : fields) { if (field.getName().equalsIgnoreCase(string)) { p = field.getType().newInstance(); break; } } } o = p; } pty = strings[strings.length - 1]; } String setterName = null; char firstLetter = propertyName.charAt(0); if (Character.isLowerCase(firstLetter)) { setterName = "set" + Character.toUpperCase(firstLetter) + pty.substring(1); } else { setterName = "set" + pty; } Method setter = null; Object setterParameter = null; Method method; for (int i = 0; (setter == null) && (i < o.getClass().getDeclaredMethods().length); i++) { method = o.getClass().getDeclaredMethods()[i]; if (method.getName().equals(setterName)) { if ((method.getParameterTypes() != null) && (method.getParameterTypes().length == 1)) { Class parameterType = method.getParameterTypes()[0]; if (String.class.equals(parameterType)) { setterParameter = propertyValue; setter = method; } else if (Integer.class.equals(parameterType)) { setterParameter = Integer.valueOf(propertyValue); setter = method; } else if (int.class.equals(parameterType)) { setterParameter = Integer.valueOf(propertyValue); setter = method; } } } } if (setter != null) { setter.invoke(o, setterParameter); } } } /** * Returns true if the given name is a Java reserved word. * * @param name * The name to test. * @return True if the given name is a Java reserved word. */ public static boolean isReservedWord(String name) { return reservedWords.contains(name); } /** * Returns the name following the the java naming rules. * * @see * Identifiers * @param name * The name to convert. * @return The name following the the java naming rules. */ public static String normalize(String name) { String result = null; if (name != null) { // Build the normalized name according to the java naming rules StringBuilder b = new StringBuilder(); boolean upperCase = false; char oldChar = 0; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isDigit(c)) { b.append(c); oldChar = c; } else if (c >= 'a' && c <= 'z') { if (upperCase) { b.append(Character.toUpperCase(c)); upperCase = false; } else { b.append(c); } oldChar = c; } else if (c >= 'A' && c <= 'Z') { if (upperCase) { b.append(c); upperCase = false; } else if (oldChar != 0 && Character.isLowerCase(oldChar)) { b.append(c); } else { b.append(Character.toLowerCase(c)); } oldChar = c; } else if (c == '.') { upperCase = true; } else if (Character.isJavaIdentifierPart(c)) { b.append(c); oldChar = c; } else { upperCase = true; } } result = b.toString(); } return result; } /** * Sets a property on an entity based on its name. * * @param entity * The entity to update. * @param property * The property. * @param propertyValue * The property value. * @throws Exception */ public static void setProperty(Object entity, Property property, String propertyValue) throws Exception { if (property.getType() != null) { invokeSetter(entity, property.getNormalizedName(), TypeUtils .fromEdm(propertyValue, property.getType().getName())); } } /** * Sets a property on an entity based on its name. * * @param entity * The entity to update. * @param propertyName * The property name. * @param isCollection * Should this property be a collection. * @param iterator * The collection of values to set. * @param propertyClass * The kind of objects stored by this property. * @throws Exception */ public static void setProperty(Object entity, String propertyName, boolean isCollection, Iterator iterator, Class propertyClass) throws Exception { String normPteName = normalize(propertyName); if (iterator == null || !iterator.hasNext()) { return; } boolean isGeneric = false; boolean isArray = false; Field field = entity.getClass().getDeclaredField(normPteName); if (field.getType().isArray()) { isArray = true; } else { java.lang.reflect.Type genericFieldType = field.getGenericType(); if (genericFieldType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericFieldType; java.lang.reflect.Type[] fieldArgTypes = aType .getActualTypeArguments(); if (fieldArgTypes.length == 1) { isGeneric = true; } } } if (isCollection) { if (isArray) { List list = new ArrayList(); for (; iterator.hasNext();) { list.add(iterator.next()); } ReflectUtils.invokeSetter(entity, normPteName, list.toArray()); } else if (isGeneric) { if (List.class.isAssignableFrom(field.getType())) { List list = new ArrayList(); for (; iterator.hasNext();) { list.add(iterator.next()); } ReflectUtils.invokeSetter(entity, normPteName, list); } else if (Set.class.isAssignableFrom(field.getType())) { Set set = new TreeSet(); for (; iterator.hasNext();) { set.add(iterator.next()); } ReflectUtils.invokeSetter(entity, normPteName, set); } } } else { for (; iterator.hasNext();) { Object property = iterator.next(); ReflectUtils.invokeSetter(entity, normPteName, property); } } } /** * Sets a property on an entity based on its name. * * @param entity * The entity to update. * @param propertyName * The property name. * @param propertyValue * The property value. * @throws Exception */ public static void setProperty(Object entity, String propertyName, String propertyValue) throws Exception { int colonIndex = propertyName.indexOf(':'); if (colonIndex != -1) { propertyName = propertyName.substring(colonIndex + 1); } invokeSetter(entity, propertyName, propertyValue, null); } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/EntryContentHandler.java0000664000175000017500000006462411757206344033460 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.atom.Content; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.EntryReader; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Link; import org.restlet.ext.atom.Person; import org.restlet.ext.atom.Relation; import org.restlet.ext.odata.Service; import org.restlet.ext.odata.internal.edm.AssociationEnd; import org.restlet.ext.odata.internal.edm.EntityType; import org.restlet.ext.odata.internal.edm.Mapping; import org.restlet.ext.odata.internal.edm.Metadata; import org.restlet.ext.odata.internal.edm.Property; import org.restlet.ext.odata.internal.reflect.ReflectUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Content handler for Atom Feed that takes care of OData specific needs, such * as parsing XML content from other namespaces than Atom. It generates an * entity based on the values discovered in the entry. * * @author Thierry Boileau * @param * The type of the parsed entity. */ public class EntryContentHandler extends EntryReader { private enum State { ASSOCIATION, CONTENT, ENTRY, PROPERTIES, PROPERTY } /** The currently parsed association. */ private AssociationEnd association; /** The currently parsed inline content. */ private Content inlineContent; /** The currently parsed inline entry. */ private Entry inlineEntry; /** The currently parsed inline feed. */ private Feed inlineFeed; /** The currently parsed inline link. */ private Link inlineLink; /** The path of the current XML element relatively to the Entry. */ List eltPath; /** The entity targeted by this entry. */ private T entity; /** The class of the entity targeted by this entry. */ private Class entityClass; /** The OData type of the parsed entity. */ private EntityType entityType; /** Used to parsed Atom link elements that contains entries. */ EntryContentHandler inlineEntryHandler; /** Used to parsed Atom link elements that contains feeds. */ FeedContentHandler inlineFeedHandler; /** Internal logger. */ private Logger logger; /** The currently parsed OData mapping. */ private Mapping mapping; /** The metadata of the WCF service. */ private Metadata metadata; /** Must the current property be set to null? */ private boolean parsePropertyNull; /** Used to handle complex types. */ private List propertyPath; /** Gleans text content. */ StringBuilder sb = null; /** Heap of states. */ List states; /** * Constructor. * * @param entityClass * The class of the parsed entities. * @param entityType * The entity type of the parsed entities. * @param metadata * The metadata of the remote OData service. * @param logger * The logger. */ public EntryContentHandler(Class entityClass, EntityType entityType, Metadata metadata, Logger logger) { this.entityClass = entityClass; this.entityType = entityType; this.metadata = metadata; this.logger = logger; } /** * Constructor. * * @param entityClass * The class of the parsed entities. * @param metadata * The metadata of the remote OData service. * @param logger * The logger. */ public EntryContentHandler(Class entityClass, Metadata metadata, Logger logger) { super(); this.entityClass = entityClass; this.entityType = metadata.getEntityType(entityClass); this.metadata = metadata; this.logger = logger; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (State.ASSOCIATION == getState()) { // Delegates to the inline content handler if (association.isToMany()) { inlineFeedHandler.characters(ch, start, length); } else { inlineEntryHandler.characters(ch, start, length); } } else if (State.PROPERTY == getState() || mapping != null) { sb.append(ch, start, length); } } @Override public void endContent(Content content) { if (State.ASSOCIATION == getState()) { // Delegates to the inline content handler if (association.isToMany()) { inlineFeedHandler.endContent(content); } else { inlineEntryHandler.endContent(content); } } else { popState(); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (State.ASSOCIATION == getState()) { // Delegates to the inline content handler if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equals("feed")) { inlineFeedHandler.endFeed(inlineFeed); } else if (localName.equals("link")) { if (association.isToMany()) { inlineFeedHandler.endLink(inlineLink); } else { inlineEntryHandler.endLink(inlineLink); } } else if (localName.equalsIgnoreCase("entry")) { if (association.isToMany()) { inlineFeedHandler.endEntry(inlineEntry); } else { inlineEntryHandler.endEntry(inlineEntry); } } else if (localName.equalsIgnoreCase("content")) { if (association.isToMany()) { inlineFeedHandler.endContent(inlineContent); } else { inlineEntryHandler.endContent(inlineContent); } } } if (association.isToMany()) { inlineFeedHandler.endElement(uri, localName, qName); } else { inlineEntryHandler.endElement(uri, localName, qName); } } else if (State.PROPERTY == getState()) { if (parsePropertyNull) { popState(); parsePropertyNull = false; } else { Object obj = entity; if (propertyPath.size() > 1) { // Complex property. for (int i = 0; i < propertyPath.size() - 1; i++) { try { Object o = ReflectUtils.invokeGetter(obj, propertyPath.get(i)); if (o == null) { // Try to instantiate it Field[] fields = obj.getClass() .getDeclaredFields(); for (Field field : fields) { if (field.getName().equalsIgnoreCase( propertyPath.get(i))) { o = field.getType().newInstance(); break; } } } ReflectUtils.invokeSetter(obj, propertyPath.get(i), o); obj = o; } catch (Exception e) { obj = null; } } } Property property = metadata.getProperty(obj, localName); if (property != null) { try { ReflectUtils.setProperty(obj, property, sb.toString()); } catch (Exception e) { getLogger().warning( "Cannot set " + localName + " property on " + obj + " with value " + sb.toString()); } } if (!propertyPath.isEmpty()) { propertyPath.remove(propertyPath.size() - 1); } if (propertyPath.isEmpty()) { // There is only one state for parsing complex or simple // properties. popState(); } } } else if (State.PROPERTIES == getState()) { popState(); } else if (State.CONTENT == getState()) { popState(); } else if (mapping != null) { // A mapping has been discovered if (sb != null) { try { ReflectUtils.invokeSetter(entity, mapping.getPropertyPath(), sb.toString()); } catch (Exception e) { getLogger().warning( "Cannot set the mapped property " + mapping.getPropertyPath() + " on " + entity + " with value " + sb.toString()); } } mapping = null; } else if (State.ENTRY == getState()) { if (!eltPath.isEmpty()) { eltPath.remove(eltPath.size() - 1); } } } @Override public void endEntry(Entry entry) { this.states = new ArrayList(); // Handle Atom mapped values. for (Mapping m : metadata.getMappings()) { if (entityType != null && entityType.equals(m.getType()) && m.getNsUri() == null && m.getNsPrefix() == null) { // mapping atom Person author = (entry.getAuthors().isEmpty()) ? null : entry .getAuthors().get(0); Person contributor = (entry.getContributors().isEmpty()) ? null : entry.getContributors().get(0); Object value = null; if ("SyndicationAuthorEmail".equals(m.getValuePath())) { value = (author != null) ? author.getEmail() : null; } else if ("SyndicationAuthorName".equals(m.getValuePath())) { value = (author != null) ? author.getName() : null; } else if ("SyndicationAuthorUri".equals(m.getValuePath())) { value = (author != null) ? author.getUri().toString() : null; } else if ("SyndicationContributorEmail".equals(m .getValuePath())) { value = (contributor != null) ? contributor.getEmail() : null; } else if ("SyndicationContributorName" .equals(m.getValuePath())) { value = (contributor != null) ? contributor.getName() : null; } else if ("SyndicationContributorUri".equals(m.getValuePath())) { value = (contributor != null) ? contributor.getUri() .toString() : null; } else if ("SyndicationPublished".equals(m.getValuePath())) { value = entry.getPublished(); } else if ("SyndicationRights".equals(m.getValuePath())) { value = (entry.getRights() != null) ? entry.getRights() .getContent() : null; } else if ("SyndicationSummary".equals(m.getValuePath())) { value = entry.getSummary(); } else if ("SyndicationTitle".equals(m.getValuePath())) { value = (entry.getTitle() != null) ? entry.getTitle() .getContent() : null; } else if ("SyndicationUpdated".equals(m.getValuePath())) { value = entry.getUpdated(); } try { if (value != null) { ReflectUtils.invokeSetter(entity, m.getPropertyPath(), value); } } catch (Exception e) { getLogger().warning( "Cannot set " + m.getPropertyPath() + " property on " + entity + " with value " + value); } } } // If the entity is a blob, get the edit reference if (entityType != null && entityType.isBlob() && entityType.getBlobValueEditRefProperty() != null) { // Look for en entry with a "edit-media" relation value. Link link = entry.getLink(Relation.EDIT_MEDIA); String pty = entityType.getBlobValueEditRefProperty().getName(); if (link != null) { try { ReflectUtils.invokeSetter(entity, pty, link.getHref()); } catch (Exception e) { getLogger().warning( "Cannot set the property " + pty + " on " + entity + " with value " + link.getHref()); } } } } @Override public void endLink(Link link) { if (State.ASSOCIATION == getState()) { String propertyName = ReflectUtils.normalize(link.getTitle()); if (association.isToMany()) { inlineFeedHandler.endLink(link); try { ReflectUtils.setProperty(entity, propertyName, association .isToMany(), inlineFeedHandler.getEntities() .iterator(), ReflectUtils.getSimpleClass(entity, propertyName)); } catch (Exception e) { getLogger().warning( "Cannot set " + propertyName + " property on " + entity + " from link"); } inlineFeedHandler = null; } else { inlineEntryHandler.endLink(link); try { ReflectUtils.invokeSetter(entity, propertyName, inlineEntryHandler.getEntity()); } catch (Exception e) { getLogger().warning( "Cannot set " + propertyName + " property on " + entity + " from link"); } inlineEntryHandler = null; } // This works if the inline entries does not contain links as // well... popState(); association = null; } } public T getEntity() { return entity; } /** * Returns the current logger. * * @return The current logger. */ private Logger getLogger() { if (logger == null) { logger = Context.getCurrentLogger(); } return logger; } /** * Returns a media type from an Atom type attribute. * * @param type * The Atom type attribute. * @return The media type. */ private MediaType getMediaType(String type) { MediaType result = null; if (type == null) { // No type defined } else if (type.equals("text")) { result = MediaType.TEXT_PLAIN; } else if (type.equals("html")) { result = MediaType.TEXT_HTML; } else if (type.equals("xhtml")) { result = MediaType.APPLICATION_XHTML; } else { result = new MediaType(type); } return result; } /** * Returns the state at the top of the heap. * * @return The state at the top of the heap. */ private State getState() { State result = null; if (this.states != null) { int size = this.states.size(); if (size > 0) { result = this.states.get(size - 1); } } return result; } /** * Returns the state at the top of the heap and removes it from the heap. * * @return The state at the top of the heap. */ private State popState() { State result = null; int size = this.states.size(); if (size > 0) { result = this.states.remove(size - 1); } return result; } /** * Adds a new state at the top of the heap. * * @param state * The state to add. */ private void pushState(State state) { this.states.add(state); } @Override public void startContent(Content content) { if (State.ENTRY == getState()) { pushState(State.CONTENT); if (entityType != null && entityType.isBlob() && entityType.getBlobValueRefProperty() != null) { Reference ref = content.getExternalRef(); if (ref != null) { try { ReflectUtils.invokeSetter(entity, entityType .getBlobValueRefProperty().getName(), ref); } catch (Exception e) { getLogger().warning( "Cannot set " + entityType.getBlobValueRefProperty() .getName() + " property on " + entity + " with value " + ref); } } } } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (State.ASSOCIATION == getState()) { // Delegates to the inline content handler if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equals("feed")) { Feed feed = new Feed(); String attr = attrs.getValue("xml:base"); if (attr != null) { feed.setBaseReference(new Reference(attr)); } inlineFeed = feed; this.inlineFeedHandler.startFeed(feed); } else if (localName.equals("link")) { Link link = new Link(); link.setHref(new Reference(attrs.getValue("", "href"))); link.setRel(Relation.valueOf(attrs.getValue("", "rel"))); String type = attrs.getValue("", "type"); if (type != null && type.length() > 0) { link.setType(new MediaType(type)); } link.setHrefLang(new Language(attrs .getValue("", "hreflang"))); link.setTitle(attrs.getValue("", "title")); String attr = attrs.getValue("", "length"); link.setLength((attr == null) ? -1L : Long.parseLong(attr)); inlineLink = link; if (association.isToMany()) { inlineFeedHandler.startLink(link); } else { inlineEntryHandler.startLink(link); } } else if (localName.equalsIgnoreCase("entry")) { Entry entry = new Entry(); if (association.isToMany()) { inlineFeedHandler.startEntry(entry); } else { inlineEntryHandler.startEntry(entry); } inlineEntry = entry; } else if (localName.equalsIgnoreCase("content")) { Content content = new Content(); MediaType type = getMediaType(attrs.getValue("", "type")); String srcAttr = attrs.getValue("", "src"); if (srcAttr != null) // Content available externally content.setExternalRef(new Reference(srcAttr)); content.setExternalType(type); if (association.isToMany()) { inlineFeedHandler.startContent(content); } else { inlineEntryHandler.startContent(content); } inlineContent = content; } } if (association.isToMany()) { inlineFeedHandler.startElement(uri, localName, qName, attrs); } else { inlineEntryHandler.startElement(uri, localName, qName, attrs); } } else if (Service.WCF_DATASERVICES_METADATA_NAMESPACE.equals(uri) && "properties".equals(localName)) { pushState(State.PROPERTIES); propertyPath = new ArrayList(); } else if (State.PROPERTIES == getState()) { pushState(State.PROPERTY); if (Boolean.parseBoolean(attrs.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "null"))) { parsePropertyNull = true; } else { sb = new StringBuilder(); propertyPath.add(localName); } } else if (State.PROPERTY == getState()) { sb = new StringBuilder(); propertyPath.add(localName); } else if (State.ENTRY == getState()) { if (localName.equalsIgnoreCase("link") && association != null) { pushState(State.ASSOCIATION); } else { // Could be mapped value eltPath.add(localName); StringBuilder sb = new StringBuilder(); for (int i = 0; i < eltPath.size(); i++) { if (i > 0) { sb.append("/"); } sb.append(eltPath.get(i)); } String str = sb.toString(); // Check if this path is mapped. for (Mapping m : metadata.getMappings()) { if (entityType != null && entityType.equals(m.getType()) && m.getNsUri() != null && m.getNsUri().equals(uri) && str.equals(m.getValueNodePath())) { if (m.isAttributeValue()) { String value = attrs.getValue(m .getValueAttributeName()); if (value != null) { try { ReflectUtils.invokeSetter(entity, m .getPropertyPath(), value); } catch (Exception e) { getLogger().warning( "Cannot set " + m.getPropertyPath() + " property on " + entity + " with value " + value); } } } else { this.sb = new StringBuilder(); mapping = m; } break; } } } } } @SuppressWarnings("unchecked") @Override public void startEntry(Entry entry) { this.states = new ArrayList(); pushState(State.ENTRY); eltPath = new ArrayList(); // Instantiate the entity try { entity = (T) entityClass.newInstance(); } catch (Exception e) { getLogger().warning( "Error when instantiating class " + entityClass); } } @Override public void startLink(Link link) { if (State.ASSOCIATION == getState()) { // Delegates to the inline content handler if (association.isToMany()) { inlineFeedHandler.startLink(link); } else { inlineEntryHandler.startLink(link); } } else { if (link.getTitle() != null && entityType != null) { String propertyName = ReflectUtils.normalize(link.getTitle()); // Get the associated entity association = metadata.getAssociation(entityType, propertyName); if (association != null) { if (association.isToMany()) { inlineFeedHandler = new FeedContentHandler( ReflectUtils.getSimpleClass(entity, propertyName), metadata, getLogger()); } else { inlineEntryHandler = new EntryContentHandler( ReflectUtils.getSimpleClass(entity, propertyName), metadata, getLogger()); } } } } } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/FeedContentHandler.java0000664000175000017500000002032411757206344033207 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.ext.atom.Content; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.FeedReader; import org.restlet.ext.atom.Link; import org.restlet.ext.odata.Service; import org.restlet.ext.odata.internal.edm.EntityType; import org.restlet.ext.odata.internal.edm.Metadata; import org.restlet.ext.odata.internal.reflect.ReflectUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Generic Content handler for Atom Feed that takes care of OData specific * needs, such as parsing XML content from other namespaces than Atom. It * generates entities based on the values discovered in the feed. * * @author Thierry Boileau * @param * The type of the parsed entities. */ public class FeedContentHandler extends FeedReader { /** The value retrieved from the "count" tag. */ private int count = -1; /** The list of entities to complete. */ List entities; /** The class of the entity targeted by this feed. */ private Class entityClass; /** The OData type of the parsed entities. */ private EntityType entityType; /** Used to parsed Atom entry elements. */ EntryContentHandler entryHandler; /** Internal logger. */ private Logger logger; /** The metadata of the OData service. */ private Metadata metadata; /** Are we parsing the count tag? */ private boolean parseCount; /** Are we parsing an entry? */ private boolean parseEntry; /** Used to glean text content. */ StringBuilder sb = null; /** * Constructor. * * @param entityClass * The class of the parsed entities. * @param metadata * The metadata of the remote OData service. * @param logger * The logger. */ public FeedContentHandler(Class entityClass, Metadata metadata, Logger logger) { super(); this.entityClass = entityClass; this.entities = new ArrayList(); this.entryHandler = new EntryContentHandler(entityClass, metadata, logger); this.logger = logger; this.metadata = metadata; } /** * Constructor. * * @param entityClass * The class of the parsed entities. * @param entityType * The entity type of the parsed entities. * @param metadata * The metadata of the remote OData service. * @param logger * The logger. */ public FeedContentHandler(Class entityClass, EntityType entityType, Metadata metadata, Logger logger) { this.entityClass = entityClass; this.entities = new ArrayList(); this.entityType = entityType; this.entryHandler = new EntryContentHandler(entityClass, entityType, metadata, logger); this.logger = logger; this.metadata = metadata; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (parseCount) { sb.append(ch, start, length); } else if (parseEntry) { // Delegate to the Entry reader entryHandler.characters(ch, start, length); } } @Override public void endContent(Content content) { if (parseEntry) { // Delegate to the Entry reader entryHandler.endContent(content); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (parseCount) { this.count = Integer.parseInt(sb.toString()); parseCount = false; } else if (parseEntry) { // Delegate to the Entry reader entryHandler.endElement(uri, localName, qName); } } @Override public void endEntry(Entry entry) { parseEntry = false; // Delegate to the Entry reader entryHandler.endEntry(entry); T entity = entryHandler.getEntity(); if (entity != null) { entities.add(entity); } else { getLogger().warning("Can't add a null entity."); } } @Override public void endLink(Link link) { if (parseEntry) { // Delegate to the Entry reader entryHandler.endLink(link); } } @Override public void endPrefixMapping(String prefix) throws SAXException { if (parseEntry) { // Delegate to the Entry reader entryHandler.endPrefixMapping(prefix); } } /** * Returns the value of the "count" tag, that is to say the size of the * current entity set. * * @return The size of the current entity set, as specified by the Atom * document. */ public int getCount() { return count; } /** * Returns the list of discovered entities. * * @return The list of discovered entities. */ public List getEntities() { return entities; } /** * Returns the current logger. * * @return The current logger. */ private Logger getLogger() { if (logger == null) { logger = Context.getCurrentLogger(); } return logger; } @Override public void startContent(Content content) { if (parseEntry) { // Delegate to the Entry reader entryHandler.startContent(content); } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (!parseEntry && Service.WCF_DATASERVICES_METADATA_NAMESPACE.equals(uri) && "count".equals(localName)) { sb = new StringBuilder(); parseCount = true; } else if (parseEntry) { // Delegate to the Entry reader entryHandler.startElement(uri, localName, qName, attrs); } } @Override public void startEntry(Entry entry) { parseEntry = true; // Delegate to the Entry reader entryHandler.startEntry(entry); } @Override public void startFeed(Feed feed) { if (this.entityClass == null) { this.entityClass = ReflectUtils.getEntryClass(feed); } if (this.entityType == null && metadata != null) { entityType = metadata.getEntityType(entityClass); } } @Override public void startLink(Link link) { if (parseEntry) { // Delegate to the Entry reader entryHandler.startLink(link); } } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { if (parseEntry) { // Delegate to the Entry reader entryHandler.startPrefixMapping(prefix, uri); } } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/templates/0000775000175000017500000000000011757206344030645 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/templates/complexType.ftl0000664000175000017500000001061211757206344033665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package ${packageName}; <#compress> <#list type.importedJavaClasses?sort as clazz> import ${clazz}; <#list type.importedTypes?sort as t> import ${t.fullClassName}; <#compress> /** * Generated by the generator tool for the OData extension for the Restlet framework.
    * <#if metadata.metadataRef??> * @see Metadata of the target OData service * */ public <#if type.abstractType>abstract class ${className} { <#list type.properties?sort_by("name") as property> <#if property.type??> private ${property.type.className} ${property.propertyName}<#if property.defaultValue??> = property.defaultValue; <#else> // private [error: no defined type] ${property.propertyName}<#if property.defaultValue??> = property.defaultValue; <#list type.complexProperties?sort_by("name") as property> <#if property.complexType??> private ${property.complexType.className} ${property.propertyName}; <#else> // private [error: no defined type] ${property.propertyName}; /** * Constructor without parameter. * */ public ${className}() { super(); } <#list type.properties?sort_by("name") as property> <#if property.type??> /** * Returns the value of the "${property.propertyName}" attribute. * * @return The value of the "${property.propertyName}" attribute. */ <#if property.getterAccess??>${property.getterAccess}<#else>public ${property.type.className} get${property.normalizedName?cap_first}() { return ${property.propertyName}; } <#list type.complexProperties?sort_by("name") as property> <#if property.complexType??> /** * Returns the value of the "${property.propertyName}" attribute. * * @return The value of the "${property.propertyName}" attribute. */ <#if property.getterAccess??>${property.getterAccess}<#else>public ${property.complexType.className} get${property.normalizedName?cap_first}() { return ${property.propertyName}; } <#list type.properties?sort_by("name") as property> <#if property.type??> /** * Sets the value of the "${property.propertyName}" attribute. * * @param ${property.propertyName} * The value of the "${property.normalizedName}" attribute. */ <#if property.setterAccess??>${property.setterAccess}<#else>public void set${property.normalizedName?cap_first}(${property.type.className} ${property.propertyName}) { this.${property.propertyName} = ${property.propertyName}; } <#list type.complexProperties?sort_by("name") as property> <#if property.complexType??> /** * Sets the value of the "${property.normalizedName}" attribute. * * @param ${property.propertyName} * The value of the "${property.normalizedName}" attribute. */ <#if property.setterAccess??>${property.setterAccess}<#else>public void set${property.normalizedName?cap_first}(${property.complexType.className} ${property.propertyName}) { this.${property.propertyName} = ${property.propertyName}; } }restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/templates/service.ftl0000664000175000017500000001353111757206344033017 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.data.Reference; import org.restlet.ext.odata.Query; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; <#list entityContainer.entities?sort as entitySet> import ${entitySet.type.fullClassName}; <#compress> /** * Generated by the generator tool for the OData extension for the Restlet framework.
    * <#if metadata.metadataRef??> * @see Metadata of the target OData service * */ public class ${className} extends org.restlet.ext.odata.Service { /** * Constructor. * */ public ${className}() { super("${dataServiceUri}"); } <#list entityContainer.entities as entitySet> <#assign type=entitySet.type> /** * Adds a new entity to the service. * * @param entity * The entity to add to the service. * @throws Exception */ public void addEntity(${type.fullClassName} entity) throws Exception { <#if entityContainer.defaultEntityContainer>addEntity("/${entitySet.name}", entity);<#else>addEntity("/${entityContainer.name}.${entitySet.name}", entity); } /** * Creates a query for ${type.normalizedName} entities hosted by this service. * * @param subpath * The path to this entity relatively to the service URI. * @return A query object. */ public Query<${type.fullClassName}> create${type.className}Query(String subpath) { return createQuery(subpath, ${type.fullClassName}.class); } <#if (type.blob && type.blobValueRefProperty?? && type.blobValueRefProperty.name??)> /** * Returns the binary representation of the given media resource. * * @param entity * The given media resource. * @return The binary representation of the given media resource. */ public Representation getValue(${type.fullClassName} entity) throws ResourceException { Reference ref = getValueRef(entity); if (ref != null) { ClientResource cr = createResource(ref); return cr.get(); } return null; } /** * Returns the binary representation of the given media resource. * * @param entity * The given media resource. * @param acceptedMediaTypes * The requested media types of the representation. * @return The given media resource. */ public Representation getValue(${type.fullClassName} entity, List> acceptedMediaTypes) throws ResourceException { Reference ref = getValueRef(entity); if (ref != null) { ClientResource cr = createResource(ref); cr.getClientInfo().setAcceptedMediaTypes(acceptedMediaTypes); return cr.get(); } return null; } /** * Returns the binary representation of the given media resource. * * @param entity * The given media resource. * @param mediaType * The requested media type of the representation * @return The given media resource. */ public Representation getValue(${type.fullClassName} entity, MediaType mediaType) throws ResourceException { Reference ref = getValueRef(entity); if (ref != null) { ClientResource cr = createResource(ref); return cr.get(mediaType); } return null; } /** * Returns the reference of the binary representation of the given entity. * * @param entity * The media resource. * @return The reference of the binary representation of the given entity. */ public Reference getValueRef(${type.fullClassName} entity) { if (entity != null) { return entity.get${type.blobValueRefProperty.name?cap_first}(); } return null; } /** * Sets the value of the given media entry link. * * @param entity * The media entry link which value is to be updated * @param blob * The new representation. * @throws ResourceException */ public void setValue(${type.fullClassName} entity, Representation blob) throws ResourceException { Reference ref = entity.get${type.blobValueEditRefProperty.name?cap_first}(); if (ref != null) { ClientResource cr = createResource(ref); cr.put(blob); } } }restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/templates/entityType.ftl0000664000175000017500000001734511757206344033544 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package ${packageName}; <#if type.blob>import org.restlet.data.Reference; <#compress> <#list type.importedJavaClasses?sort as clazz> import ${clazz}; <#list type.importedTypes?sort as t> import ${t.fullClassName}; <#compress> /** * Generated by the generator tool for the OData extension for the Restlet framework.
    * <#if metadata.metadataRef??> * @see Metadata of the target OData service * */ public <#if type.abstractType>abstract class ${className} { <#list type.properties?sort_by("name") as property> <#if property.type??> private ${property.type.className} ${property.propertyName}<#if property.defaultValue??> = property.defaultValue; <#else> // private [error: no defined type] ${property.propertyName}<#if property.defaultValue??> = property.defaultValue; <#list type.complexProperties?sort_by("name") as property> <#if property.complexType??> private ${property.complexType.className} ${property.propertyName}; <#else> // private [error: no defined type] ${property.propertyName}; <#list type.associations?sort_by("name") as association> private <#if association.toRole.toMany>List<${association.toRole.type.className}><#else>${association.toRole.type.className} ${association.normalizedName}; <#if type.blob> /** The reference of the underlying blob representation. */ private Reference ${type.blobValueRefProperty.name}; /** The reference to update the underlying blob representation. */ private Reference ${type.blobValueEditRefProperty.name}; /** * Constructor without parameter. * */ public ${className}() { super(); } /** * Constructor. * * @param id * The identifiant value of the entity. */ public ${className}(<#if type.keys??><#list type.keys as key>${key.type.className} ${key.normalizedName}<#if key_has_next>, ) { this(); <#if type.keys??><#list type.keys as key> this.${key.normalizedName} = ${key.normalizedName}; } <#list type.properties?sort_by("name") as property> <#if property.type??> /** * Returns the value of the "${property.propertyName}" attribute. * * @return The value of the "${property.propertyName}" attribute. */ <#if property.getterAccess??>${property.getterAccess}<#else>public ${property.type.className} get${property.normalizedName?cap_first}() { return ${property.propertyName}; } <#list type.complexProperties?sort_by("name") as property> <#if property.complexType??> /** * Returns the value of the "${property.propertyName}" attribute. * * @return The value of the "${property.propertyName}" attribute. */ <#if property.getterAccess??>${property.getterAccess}<#else>public ${property.complexType.className} get${property.normalizedName?cap_first}() { return ${property.propertyName}; } <#list type.associations?sort_by("name") as association> /** * Returns the value of the "${association.normalizedName}" attribute. * * @return The value of the "${association.normalizedName}" attribute. */ <#if association.toRole.toMany> public List<${association.toRole.type.className}> get${association.normalizedName?cap_first}() { <#else> public ${association.toRole.type.className} get${association.normalizedName?cap_first}() { return ${association.normalizedName}; } <#if type.blob> /** * Returns the @{Link Reference} of the underlying blob. * * @return The @{Link Reference} of the underlying blob. */ public Reference get${type.blobValueRefProperty.name?cap_first}() { return ${type.blobValueRefProperty.name}; } <#if type.blob> /** * Returns the @{Link Reference} to update the underlying blob. * * @return The @{Link Reference} to update the underlying blob. */ public Reference get${type.blobValueEditRefProperty.name?cap_first}() { return ${type.blobValueEditRefProperty.name}; } <#list type.properties?sort_by("name") as property> <#if property.type??> /** * Sets the value of the "${property.normalizedName}" attribute. * * @param ${property.propertyName} * The value of the "${property.normalizedName}" attribute. */ <#if property.setterAccess??>${property.setterAccess}<#else>public void set${property.normalizedName?cap_first}(${property.type.className} ${property.propertyName}) { this.${property.propertyName} = ${property.propertyName}; } <#list type.complexProperties?sort_by("name") as property> <#if property.complexType??> /** * Sets the value of the "${property.normalizedName}" attribute. * * @param ${property.propertyName} * The value of the "${property.normalizedName}" attribute. */ <#if property.setterAccess??>${property.setterAccess}<#else>public void set${property.normalizedName?cap_first}(${property.complexType.className} ${property.propertyName}) { this.${property.propertyName} = ${property.propertyName}; } <#list type.associations?sort_by("name") as association> /** * Sets the value of the "${association.normalizedName}" attribute. * * @param ${association.normalizedName}" * The value of the "${association.normalizedName}" attribute. */ <#if association.toRole.toMany> public void set${association.normalizedName?cap_first}(List<${association.toRole.type.className}> ${association.normalizedName}) { <#else> public void set${association.normalizedName?cap_first}(${association.toRole.type.className} ${association.normalizedName}) { this.${association.normalizedName} = ${association.normalizedName}; } <#if type.blob> /** * Sets the @{Link Reference} of the underlying blob. * * @param ref * The @{Link Reference} of the underlying blob. */ public void set${type.blobValueRefProperty.name?cap_first}(Reference ref) { this.${type.blobValueRefProperty.name} = ref; } <#if type.blob> /** * Sets the @{Link Reference} to update the underlying blob. * * @param ref * The @{Link Reference} to update the underlying blob. */ public void set${type.blobValueEditRefProperty.name?cap_first}(Reference ref) { this.${type.blobValueEditRefProperty.name} = ref; } }restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/0000775000175000017500000000000011757206344027414 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Association.java0000664000175000017500000000536111757206344032540 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; /** * Defines an association inside a schema. * * @author Thierry Boileau * @see Association * Element (CSDL) */ public class Association extends NamedObject { /** The list of entities linked by this association. */ private List ends; /** The schema. */ private Schema schema; /** * Constructor. * * @param name * The name of the schema. */ public Association(String name) { super(name); } /** * Returns the list of entities linked by this association. * * @return The list of entities linked by this association. */ public List getEnds() { if (ends == null) { ends = new ArrayList(); } return ends; } /** * Returns the schema. * * @return The schema. */ public Schema getSchema() { return schema; } /** * Sets the list of entities linked by this association. * * @param ends * The list of entities linked by this association. */ public void setEnds(List ends) { this.ends = ends; } /** * Sets the schema. * * @param schema * The schema. */ public void setSchema(Schema schema) { this.schema = schema; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/EntityType.java0000664000175000017500000001443311757206344032402 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Defines a class or type of entity inside a schema. Note that composite keys * are not supported. * * @author Thierry Boileau * @see EntityType * Element (CSDL) */ public class EntityType extends ODataType { /** The list of associations. */ private List associations; /** Is this type a blob? */ private boolean blob; /** * The entity's member that stores the resource reference able to update the * blob value. */ private Property blobValueEditRefProperty; /** The property of the entity that stores the blob reference. */ private Property blobValueRefProperty; /** The list of properties that identifies an instance of this type. */ private List keys; /** * Constructor. * * @param name * The name of this entity type. */ public EntityType(String name) { super(name); } /** * Returns the list of associations. * * @return The list of associations. */ public List getAssociations() { if (associations == null) { associations = new ArrayList(); } return associations; } /** * Returns the parent type this type inherits from. * * @return The parent type this type inherits from. */ @Override public EntityType getBaseType() { return (EntityType) super.getBaseType(); } /** * Returns the entity's member that stores the resource reference able to * update the blob value. * * @return The entity's member that stores the resource reference able to * update the blob value. */ public Property getBlobValueEditRefProperty() { return blobValueEditRefProperty; } /** * Returns the name of the entity property that stores the blob reference. * * @return The name of the entity property that stores the blob reference. */ public Property getBlobValueRefProperty() { return blobValueRefProperty; } /** * Returns the set of imported Java classes. * * @return The set of imported Java classes. */ public Set getImportedJavaClasses() { Set result = super.getImportedJavaClasses(); for (NavigationProperty property : getAssociations()) { if (property.getToRole().isToMany()) { result.add("java.util.List"); break; } } return result; } /** * Returns the set of imported entity types. * * @return The set of imported entity types. */ @Override public Set getImportedTypes() { Set result = super.getImportedTypes(); for (NavigationProperty property : getAssociations()) { result.add(property.getToRole().getType()); } return result; } /** * Returns the "keys" property. * * @return The "keys" property. */ public List getKeys() { return keys; } /** * Returns true if this type a blob, that is to say it represents binary * data. * * @return True if this type a blob, that is to say it represents binary * data. */ public boolean isBlob() { return blob; } /** * Sets the list of associations. * * @param associations * The list of associations. */ public void setAssociations(List associations) { this.associations = associations; } /** * Indicates if this type a blob, that is to say it represents binary data. * * @param media * True if this type a blob, that is to say it represents binary * data. */ public void setBlob(boolean blob) { this.blob = blob; } /** * Sets the entity's member that stores the resource reference able to * update the blob value. * * @param blobValueEditRefProperty * The entity's member that stores the resource reference able to * update the blob value. */ public void setBlobValueEditRefProperty(Property blobValueEditRefProperty) { this.blobValueEditRefProperty = blobValueEditRefProperty; } /** * Sets the name of the entity property that stores the blob reference. * * @param blobValueRefProperty * The name of the entity property that stores the blob * reference. */ public void setBlobValueRefProperty(Property blobValueRefProperty) { this.blobValueRefProperty = blobValueRefProperty; } /** * Sets the "keys" property. * * @param keys * The "keys" property. */ public void setKeys(List keys) { this.keys = keys; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/AssociationSet.java0000664000175000017500000000574611757206344033223 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; /** * Represents an association inside an EntityContainer. * * @author Thierry Boileau * @see AssociationSet * Element (EntityContainer CSDL) */ public class AssociationSet extends NamedObject { /** The referenced schema's association. */ private Association association; /** The list of entities implied in this association. */ private List ends; /** * Constructor. * * @param name * The name of the association set. */ public AssociationSet(String name) { super(name); } /** * Returns the referenced schema's association. * * @return The referenced schema's association. */ public Association getAssociation() { return association; } /** * Returns the list of entities implied in this association. * * @return The list of entities implied in this association. */ public List getEnds() { if (ends == null) { ends = new ArrayList(); } return ends; } /** * Sets the referenced schema's association. * * @param association * The referenced schema's association. */ public void setAssociation(Association association) { this.association = association; } /** * Sets the list of entities implied in this association. * * @param ends * The list of entities implied in this association. */ public void setEnds(List ends) { this.ends = ends; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Mapping.java0000664000175000017500000001401011757206344031646 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Defines a property mapping used in customized feeds. It maps an XML element * of the feed to parse and a property of entity. * * @author Thierry Boileau * @see Atom * Feed Customization (ADO.NET Data Services) */ public class Mapping { /** Is the value taken from an attribute or not. */ private boolean attributeValue; /** The content type of the value of the mapped property. */ private String contentKind; /** The namespace prefix of the feed's XML element that stores the value. */ private String nsPrefix; /** The namespace URI of the feed's XML element that stores the value. */ private String nsUri; /** The path of the property to update. */ private String propertyPath; /** The type of the entity to update. */ private EntityType type; /** The path of the XML element of the feed that stores the value to set. */ private String valuePath; /** * Constructor. * * @param type * The type of the entity to update. * @param nsPrefix * The namespace prefix of the feed's XML element that stores the * value. * @param nsUri * The namespace URI of the feed's XML element that stores the * value. * @param propertyPath * The type of the entity to update. * @param valuePath * The path of the XML element of the feed that stores the value * to set. * @param contentKind * The content type of the value of the mapped property.. */ public Mapping(EntityType type, String nsPrefix, String nsUri, String propertyPath, String valuePath, String contentKind) { super(); this.type = type; this.nsPrefix = nsPrefix; this.nsUri = nsUri; this.propertyPath = propertyPath; this.valuePath = valuePath; this.contentKind = contentKind; this.attributeValue = false; if (this.valuePath != null) { int index = valuePath.lastIndexOf("/"); if (index != -1 && valuePath.length() > index) { attributeValue = ('@' == valuePath.charAt(index + 1)); } } } /** * Returns the content type of the value of the mapped property. * * @return The content type of the value of the mapped property. */ public String getContentKind() { return contentKind; } /** * Returns the namespace prefix of the feed's XML element that stores the * value. * * @return The namespace prefix of the feed's XML element that stores the * value. */ public String getNsPrefix() { return nsPrefix; } /** * Returns the namespace URI of the feed's XML element that stores the * value. * * @return The namespace URI of the feed's XML element that stores the * value. */ public String getNsUri() { return nsUri; } /** * Returns the path of the property to update. * * @return The path of the property to update. */ public String getPropertyPath() { return propertyPath; } /** * Returns the type of the entity to update. * * @return The type of the entity to update. */ public EntityType getType() { return type; } /** * Returns the name of the attribute that stores the value to set, if * pertinent, and null otherwise. * * @return The he name of the attribute that stores the value to set. */ public String getValueAttributeName() { String result = null; if (isAttributeValue()) { int index = valuePath.lastIndexOf("/"); result = valuePath.substring(index + 2, valuePath.length()); } return result; } /** * Returns the name of the attribute that stores the value to set, if * pertinent, and null otherwise. * * @return The he name of the attribute that stores the value to set. */ public String getValueNodePath() { return (isAttributeValue()) ? valuePath.substring(0, valuePath .lastIndexOf("/")) : valuePath; } /** * Returns the path of the XML element of the feed that stores the value to * set. * * @return The path of the XML element of the feed that stores the value to * set. */ public String getValuePath() { return valuePath; } /** * Returns true if the value is taken from an attribute. * * @return True if the value is taken from an attribute. */ public boolean isAttributeValue() { return attributeValue; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/AssociationEnd.java0000664000175000017500000000623511757206344033170 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Represents one entity implied in an association. * * @author Thierry Boileau * @see Association * Element (SSDL) */ public class AssociationEnd { /** The cardinality of the relation. */ private String multiplicity; /** The role of this entity relatively to this association. */ private final String role; /** The type of this entity. */ private EntityType type; /** * Constructor. * * @param role * The name of the role. */ public AssociationEnd(String role) { super(); this.role = role; } /** * Returns the cardinality of the relation. * * @return The cardinality of the relation. */ public String getMultiplicity() { return multiplicity; } /** * Returns the role of this entity relatively to this association. * * @return The role of this entity relatively to this association. */ public String getRole() { return role; } /** * Returns the type of this entity. * * @return The type of this entity. */ public EntityType getType() { return type; } /** * Returns true if the cardinality says that this is a one to many or many * to many relation. * * @return */ public boolean isToMany() { return "*".equals(getMultiplicity()); } /** * Sets the cardinality of the relation. * * @param multiplicity * The cardinality of the relation. */ public void setMultiplicity(String multiplicity) { this.multiplicity = multiplicity; } /** * Sets the type of this entity. * * @param type * The type of this entity. */ public void setType(EntityType type) { this.type = type; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/ComplexProperty.java0000664000175000017500000000420211757206344033431 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Represents a complex property of an EntityType. * * @author Thierry Boileau * @see Property * Element (EntityType CSDL) */ public class ComplexProperty extends Property { /** The type of the property. */ private ComplexType type; /** * Constructor. * * @param name * The name of this property. */ public ComplexProperty(String name) { super(name); } /** * Returns the type of the property. * * @return The type of the property. */ public ComplexType getComplexType() { return type; } /** * Sets the type of the property. * * @param type * The type of the property. */ public void setComplexType(ComplexType type) { this.type = type; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Property.java0000664000175000017500000001362711757206344032114 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import org.restlet.data.MediaType; import org.restlet.ext.odata.internal.reflect.ReflectUtils; /** * Represents a property of an EntityType. * * @author Thierry Boileau * @see Property * Element (EntityType CSDL) */ public class Property extends NamedObject { /** True if this property should be used for optimistic concurrency checks. */ private boolean concurrent; /** The default value. */ private String defaultValue; /** The access level modifier of the getter method. */ private String getterAccess; /** The media type stored in the content. */ private MediaType mediaType; /** True if this property is not mandatory. */ private boolean nullable; /** The access level modifier of the setter method. */ private String setterAccess; /** The type of the property. */ private Type type; /** * Constructor. * * @param name * The name of this property. */ public Property(String name) { super(name); } /** * Returns the default value. * * @return The default value. */ public String getDefaultValue() { return defaultValue; } /** * Returns the access level modifier of the getter method. * * @return The access level modifier of the getter method. */ public String getGetterAccess() { return getterAccess; } /** * Returns the media type stored in the content. * * @return The media type stored in the content. */ public MediaType getMediaType() { return mediaType; } /** * Returns the property name used as a class member. * * @return The property name used as a class member. */ public String getPropertyName() { String result = super.getNormalizedName(); if (ReflectUtils.isReservedWord(result)) { result = "_" + result; } return result; } /** * Returns the access level modifier of the setter method. * * @return The access level modifier of the setter method. */ public String getSetterAccess() { return setterAccess; } /** * Returns the type of the property. * * @return The type of the property. */ public Type getType() { return type; } /** * Returns true if this property should be used for optimistic concurrency * checks. * * @return True if this property should be used for optimistic concurrency * checks. */ public boolean isConcurrent() { return concurrent; } /** * Returns true if this property is not mandatory. * * @return True if this property is not mandatory. */ public boolean isNullable() { return nullable; } /** * Indicates if this property should be used for optimistic concurrency * checks. * * @param concurrent * True if this property should be used for optimistic * concurrency checks. */ public void setConcurrent(boolean concurrent) { this.concurrent = concurrent; } /** * Sets the default value. * * @param defaultValue * The default value. */ public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } /** * Sets the access level modifier of the getter method. * * @param getterAccess * The access level modifier of the getter method. */ public void setGetterAccess(String getterAccess) { this.getterAccess = getterAccess; } /** * Sets the media type stored in the content. * * @param mediaType * The media type stored in the content. */ public void setMediaType(MediaType mediaType) { this.mediaType = mediaType; } /** * Sets true if this property is not mandatory. * * @param nullable * True if this property is not mandatory. */ public void setNullable(boolean nullable) { this.nullable = nullable; } /** * Sets the access level modifier of the setter method. * * @param setterAccess * The access level modifier of the setter method. */ public void setSetterAccess(String setterAccess) { this.setterAccess = setterAccess; } /** * Sets the type of the property. * * @param type * The type of the property. */ public void setType(Type type) { this.type = type; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Metadata.java0000664000175000017500000003527311757206344032011 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.restlet.data.Reference; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.representation.Representation; /** * Represents the metadata of an OData service. * * @author Thierry Boileau */ public class Metadata extends SaxRepresentation { /** The list of entity containers. */ private List containers; /** The list of declared property mappings. */ private List mappings; /** The URI of the metadata resource. */ private Reference metadataRef; /** The data services schemas. */ private List schemas; /** * Constructor. * * @param metadata * The representation of the metadata. * @param metadataRef * Its optional URI. * @throws IOException */ public Metadata(Representation metadata, Reference metadataRef) throws IOException { super(metadata); setNamespaceAware(true); this.metadataRef = metadataRef; parse(new MetadataReader(this)); } /** * Returns the Association object that corresponds to the given property of * the given entity type. * * @param type * The entity type. * @param propertyName * The property name. * @return the Association object that corresponds to the given property of * the given entity type. */ public AssociationEnd getAssociation(EntityType type, String propertyName) { AssociationEnd result = null; for (NavigationProperty association : type.getAssociations()) { if (association.getNormalizedName().equals(propertyName)) { result = association.getToRole(); break; } } return result; } /** * Returns the list of entity containers. * * @return The list of entity containers. */ public List getContainers() { if (containers == null) { containers = new ArrayList(); } return containers; } /** * Returns the subpath of the entitySet of the given entity type. * * @param entity * The entity. * @return The subpath of the entitySet of the given entity type. */ public String getEntitySetSubpath(EntityType entityType) { String result = null; if (entityType == null) { return result; } // Try to match the entity class names (without package); for (EntityContainer entityContainer : getContainers()) { for (EntitySet entitySet : entityContainer.getEntities()) { EntityType type = entitySet.getType(); if (type.equals(entityType)) { result = "/" + entitySet.getName(); } } } return result; } /** * Returns the entityType that corresponds to a given entity class. * * @param entityClass * The entity class. * @return The entityType that corresponds to a given entity class. */ public EntityType getEntityType(Class entityClass) { EntityType result = null; // Try to match the entity class names (without package); String className = entityClass.getName(); int index = className.lastIndexOf("."); if (index != -1) { className = className.substring(index + 1); } for (Iterator iec = getContainers().iterator(); result == null && iec.hasNext();) { EntityContainer entityContainer = iec.next(); for (Iterator ies = entityContainer.getEntities() .iterator(); result == null && ies.hasNext();) { EntitySet entitySet = ies.next(); EntityType type = entitySet.getType(); if (type.getClassName().equals(className)) { result = type; } } } return result; } /** * Returns the complectType that corresponds to a given entity class. * * @param entityClass * The entity class. * @return The ComplexType that corresponds to a given entity class. */ public ComplexType getComplexType(Class entityClass) { ComplexType result = null; // Try to match the entity class names (without package); String className = entityClass.getName(); int index = className.lastIndexOf("."); if (index != -1) { className = className.substring(index + 1); } for (Iterator iec = getSchemas().iterator(); result == null && iec.hasNext();) { Schema schema = iec.next(); for (Iterator ies = schema.getComplexTypes() .iterator(); result == null && ies.hasNext();) { ComplexType type = ies.next(); if (type.getClassName().equals(className)) { result = type; } } } return result; } /** * Returns the String representation of the value of the key of the given * entity that should be used in all URIs. * * @param type * The type descriptor of the object. * @param entity * The entity. * @return The value of the key of the given entity or null in case of * error. */ public String getKeyValue(EntityType type, Object entity) { StringBuffer result = new StringBuffer(); if (type.getKeys() != null && !type.getKeys().isEmpty()) { if (type.getKeys().size() == 1) { Property key = type.getKeys().get(0); String keyName = key.getNormalizedName(); String getterName = "get" + keyName.substring(0, 1).toUpperCase() + keyName.substring(1); try { Method getter = entity.getClass().getDeclaredMethod( getterName, (Class[]) null); Object value = getter.invoke(entity, (Object[]) null); String strValue = TypeUtils.toEdmKey(value, key.getType()); if (strValue != null) { result.append(strValue); } else { result.append("''"); } } catch (Exception e) { // Nothing } } else { Iterator it = type.getKeys().iterator(); while (it.hasNext()) { Property key = it.next(); String keyName = key.getNormalizedName(); result.append(key.getName()).append("="); String getterName = "get" + keyName.substring(0, 1).toUpperCase() + keyName.substring(1); try { Method getter = entity.getClass().getDeclaredMethod( getterName, (Class[]) null); Object value = getter.invoke(entity, (Object[]) null); String strValue = TypeUtils.toEdmKey(value, key .getType()); if (strValue != null) { result.append(strValue); } else { result.append("''"); } } catch (Exception e) { // Nothing } if (it.hasNext()) { result.append(","); } } } } return result.toString(); } /** * Returns the value of the key of the given entity that should be used in * all URIs. * * @param entity * The entity. * @return The value of the key of the given entity or null in case of * error. */ public String getKeyValue(Object entity) { String result = null; if (entity != null) { result = getKeyValue(getEntityType(entity.getClass()), entity); } return result; } /** * Returns the list of declared property mappings. * * @return The list of declared property mappings. */ public List getMappings() { if (mappings == null) { mappings = new ArrayList(); } return mappings; } /** * Returns the URI of the metadata resource. * * @return The URI of the metadata resource. */ public Reference getMetadataRef() { return metadataRef; } /** * Returns the EDM type of the given property of the given entity. * * @param entity * The entity. * @param propertyName * The name of the property. * @return The EDM type of the given property of the given entity. */ public Property getProperty(Object entity, String propertyName) { Property result = null; if (entity != null) { EntityType et = getEntityType(entity.getClass()); if (et != null) { for (Property property : et.getProperties()) { if (property.getName().equals(propertyName) || property.getNormalizedName() .equals(propertyName)) { result = property; break; } } } else { ComplexType ct = getComplexType(entity.getClass()); if (ct != null) { for (Property property : ct.getProperties()) { if (property.getName().equals(propertyName) || property.getNormalizedName().equals( propertyName)) { result = property; break; } } } } } return result; } /** * Returns the data service schema. * * @return The data service schema. */ public List getSchemas() { if (schemas == null) { schemas = new ArrayList(); } return schemas; } /** * According to the metadata of the service, returns the path of the given * entity relatively to the current WCF service. * * @param entity * The entity. * @return The path of the given entity relatively to the current WCF * service. */ public String getSubpath(Object entity) { String result = null; if (entity == null) { return result; } // Try to match the entity class names (without package); String entityClass = entity.getClass().getName(); int index = entityClass.lastIndexOf("."); if (index != -1) { entityClass = entityClass.substring(index + 1); } for (EntityContainer entityContainer : getContainers()) { for (EntitySet entitySet : entityContainer.getEntities()) { EntityType type = entitySet.getType(); if (type.getClassName().equals(entityClass)) { String value = getKeyValue(type, entity); if (value != null) { result = "/" + entitySet.getName() + "(" + value + ")"; } } } } return result; } /** * According to the metadata of the service, returns the path of the given * entity's property relatively to the current WCF service. * * @param entity * The entity. * @param propertyName * The name of the property. * @return The path of the given entity's property relatively to the current * WCF service. */ public String getSubpath(Object entity, String propertyName) { return getSubpath(entity) + "/" + propertyName; } /** * According to the metadata of the service, returns the relative path of * the given target entity linked to the source entity via the source * property. * * @param source * The source entity to update. * @param sourceProperty * The name of the property of the source entity. * @param target * The entity linked to the source entity. * @return */ public String getSubpath(Object source, String sourceProperty, Object target) { return getSubpath(source) + "/" + sourceProperty + "(" + getKeyValue(target) + ")"; } /** * Sets the list of entity containers. * * @param containers * The list of entity containers. */ public void setContainers(List containers) { this.containers = containers; } /** * Sets the data service schemas * * @param schemas * The data service schemas. */ public void setSchemas(List schemas) { this.schemas = schemas; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Type.java0000664000175000017500000000610311757206344031200 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.Set; import java.util.TreeSet; /** * Represents an EDM simple type. * * @author Thierry Boileau * @see Simple * Types (EDM) */ public class Type extends NamedObject { /** * Constructor. * * @param typeName * The name of the type. */ public Type(String typeName) { super(typeName); } /** * Returns the name of the corresponding Java class or scalar type. * * @return The name of the corresponding Java class or scalar type. */ public String getClassName() { return TypeUtils.toJavaTypeName(getName()); } /** * Returns the set of imported Java classes. * * @return The set of imported Java classes. */ public Set getImportedJavaClasses() { Set result = new TreeSet(); if (getName().endsWith("DateTime")) { result.add(getJavaClass().getName()); } else if (getName().endsWith("DateTimeOffset")) { result.add(getJavaClass().getName()); } return result; } /** * Returns the corresponding Java class. * * @return The corresponding Java class. */ public Class getJavaClass() { return TypeUtils.toJavaClass(getName()); } /** * Returns the class name of the corresponding Java class. Returns null for * a scalar type. * * @return The class name of the corresponding Java class. */ public String getPackageName() { String result = null; if (getName().endsWith("DateTime")) { result = "java.util"; } else if (getName().endsWith("DateTimeOffset")) { result = "java.util"; } return result; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/TypeUtils.java0000664000175000017500000005333411757206344032231 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import org.restlet.Context; import org.restlet.engine.util.Base64; import org.restlet.engine.util.DateUtils; import org.restlet.ext.odata.internal.reflect.ReflectUtils; /** * Handle type operations. * * @author Thierry Boileau */ public class TypeUtils { /** Formater for the EDM DateTime type. */ public static final List dateTimeFormats = Arrays.asList( "yyyy-MM-dd'T'HH:mm:ssz", "yyyy-MM-dd'T'HH:mm:ss", "EEE, dd MMM yyyy HH:mm:ss zzz"); /** Formater for the EDM Decimal type. */ public static final NumberFormat decimalFormat = DecimalFormat .getNumberInstance(Locale.US); /** Formater for the EDM Double type. */ public static final NumberFormat doubleFormat = DecimalFormat .getNumberInstance(Locale.US); /** Formater for the EDM Single type. */ public static final NumberFormat singleFormat = DecimalFormat .getNumberInstance(Locale.US); /** Formater for the EDM Time type. */ public static final NumberFormat timeFormat = DecimalFormat .getIntegerInstance(Locale.US); /** * Converts the String representation of the target WCF type to its * corresponding value. * * @param value * The value to convert. * @param adoNetType * The target WCF type. * @return The converted value. */ public static Object fromEdm(String value, String adoNetType) { if (value == null) { return null; } Object result = null; try { if (adoNetType.endsWith("Binary")) { result = Base64.decode(value); } else if (adoNetType.endsWith("Boolean")) { result = Boolean.valueOf(value); } else if (adoNetType.endsWith("DateTime")) { result = DateUtils.parse(value, dateTimeFormats); } else if (adoNetType.endsWith("DateTimeOffset")) { result = DateUtils.parse(value, dateTimeFormats); } else if (adoNetType.endsWith("Time")) { result = timeFormat.parseObject(value); } else if (adoNetType.endsWith("Decimal")) { result = decimalFormat.parseObject(value); } else if (adoNetType.endsWith("Single")) { result = singleFormat.parseObject(value); } else if (adoNetType.endsWith("Double")) { result = doubleFormat.parseObject(value); } else if (adoNetType.endsWith("Guid")) { result = value; } else if (adoNetType.endsWith("Int16")) { result = Short.valueOf(value); } else if (adoNetType.endsWith("Int32")) { result = Integer.valueOf(value); } else if (adoNetType.endsWith("Int64")) { result = Long.valueOf(value); } else if (adoNetType.endsWith("Byte")) { result = Byte.valueOf(value); } else if (adoNetType.endsWith("String")) { result = value; } } catch (Exception e) { Context.getCurrentLogger().warning( "Cannot convert " + value + " from this EDM type " + adoNetType); } return result; } /** * Returns a correct full class name from the given name. Especially, it * ensures that the first character of each sub package is in lower case. * * @param name * The name. * @return The package name extracted from the given name. */ public static String getFullClassName(String name) { StringBuilder builder = new StringBuilder(); int index = name.lastIndexOf("."); if (index > -1) { builder.append(getPackageName(ReflectUtils.normalize(name .substring(0, index)))); builder.append(name.substring(index)); } else { builder.append(name); } return builder.toString(); } /** * Returns the Java class that corresponds to the given type according to * the naming rules. It looks for the schema namespace name taken as the * package name, then the name of this entity type is the class name. * * @param type * The entity type. * @return The Java class that corresponds to this type. */ public static Class getJavaClass(EntityType type) { Class result = null; String fullClassName = getPackageName(type.getSchema()) + "." + type.getClassName(); try { result = Class.forName(fullClassName); } catch (ClassNotFoundException e) { Context.getCurrentLogger().warning( "Can't find the following class in the class loader: " + fullClassName); } return result; } /** * Returns the literal form of the given value. * * @param value * The value to convert. * @param adoNetType * The type of the value. * @return The literal form of the given value. * @see Abstract * Type System */ public static String getLiteralForm(String value, String adoNetType) { if (value == null) { return null; } String result = null; try { if (adoNetType.endsWith("Binary")) { result = "'" + value + "'"; } else if (adoNetType.endsWith("DateTime")) { result = "datetime'" + value + "'"; } else if (adoNetType.endsWith("DateTimeOffset")) { result = "datetimeoffset'" + value + "'"; } else if (adoNetType.endsWith("Time")) { result = "time'" + value + "'"; } else if (adoNetType.endsWith("Guid")) { result = "guid'" + value + "'"; } else if (adoNetType.endsWith("String")) { result = "'" + value + "'"; } } catch (Exception e) { Context.getCurrentLogger().warning( "Cannot convert " + value + " from this EDM type " + adoNetType); } return result; } /** * Returns the package name related to the given schema. * * @param schema * The schema. * @return The package name related to the given schema. */ public static String getPackageName(Schema schema) { return getPackageName(schema.getNamespace().getName()); } /** * Returns a correct package name from the given name. Especially, it * ensures that the first character of each sub package is in lower case. * * @param name * The name. * @return The package name extracted from the given name. */ public static String getPackageName(String name) { StringBuilder builder = new StringBuilder(); String[] tab = name.split("\\."); for (int i = 0; i < tab.length; i++) { String string = tab[i]; if (i > 0) { builder.append("."); } builder.append(string.toLowerCase()); } return builder.toString(); } /** * Converts a value to the String representation of the target WCF type. * * @param value * The value to convert. * @param type * The target WCF type. * @return The converted value. */ public static String toEdm(Object value, Type type) { String adoNetType = type.getName(); if (value == null && adoNetType == null) { return null; } String result = null; if (adoNetType.endsWith("Binary")) { if ((byte[].class).isAssignableFrom(value.getClass())) { result = toEdmBinary((byte[]) value); } } else if (adoNetType.endsWith("Boolean")) { if ((Boolean.class).isAssignableFrom(value.getClass())) { result = toEdmBoolean((Boolean) value); } } else if (adoNetType.endsWith("DateTime")) { if ((Date.class).isAssignableFrom(value.getClass())) { result = toEdmDateTime((Date) value); } } else if (adoNetType.endsWith("DateTimeOffset")) { if ((Date.class).isAssignableFrom(value.getClass())) { result = toEdmDateTime((Date) value); } } else if (adoNetType.endsWith("Time")) { if ((Long.class).isAssignableFrom(value.getClass())) { result = toEdmTime((Long) value); } } else if (adoNetType.endsWith("Decimal")) { if ((Double.class).isAssignableFrom(value.getClass())) { result = toEdmDecimal((Double) value); } } else if (adoNetType.endsWith("Single")) { if ((Float.class).isAssignableFrom(value.getClass())) { result = toEdmSingle((Float) value); } else if ((Double.class).isAssignableFrom(value.getClass())) { result = toEdmSingle((Double) value); } } else if (adoNetType.endsWith("Double")) { if ((Double.class).isAssignableFrom(value.getClass())) { result = toEdmDouble((Double) value); } } else if (adoNetType.endsWith("Guid")) { result = value.toString(); } else if (adoNetType.endsWith("Int16")) { if ((Short.class).isAssignableFrom(value.getClass())) { result = toEdmInt16((Short) value); } } else if (adoNetType.endsWith("Int32")) { if ((Integer.class).isAssignableFrom(value.getClass())) { result = toEdmInt32((Integer) value); } } else if (adoNetType.endsWith("Int64")) { if ((Long.class).isAssignableFrom(value.getClass())) { result = toEdmInt64((Long) value); } } else if (adoNetType.endsWith("Byte")) { if ((Byte.class).isAssignableFrom(value.getClass())) { result = toEdmByte((Byte) value); } } else if (adoNetType.endsWith("String")) { result = value.toString(); } if (result == null) { result = value.toString(); } return result; } /** * Convert the given value to the String representation of a EDM Binary * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmBinary(byte[] value) { return Base64.encode(value, false); } /** * Convert the given value to the String representation of a EDM Boolean * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmBoolean(boolean value) { return Boolean.toString(value); } /** * Convert the given value to the String representation of a EDM Byte value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmByte(byte value) { return Byte.toString(value); } /** * Convert the given value to the String representation of a EDM DateTime * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmDateTime(Date value) { return DateUtils.format(value, dateTimeFormats.get(0)); } /** * Convert the given value to the String representation of a EDM Decimal * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmDecimal(double value) { return decimalFormat.format(value); } /** * Convert the given value to the String representation of a EDM Double * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmDouble(double value) { return doubleFormat.format(value); } /** * Convert the given value to the String representation of a EDM Int16 * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmInt16(short value) { return Short.toString(value); } /** * Convert the given value to the String representation of a EDM Int32 * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmInt32(int value) { return Integer.toString(value); } /** * Convert the given value to the String representation of a EDM Int64 * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmInt64(long value) { return Long.toString(value); } /** * Converts a value to the String representation of the target WCF type when * used a key in the URIs. * * @param value * The value to convert. * @param type * The target WCF type. * @return The converted value. */ public static String toEdmKey(Object value, Type type) { String adoNetType = type.getName(); if (value == null && adoNetType == null) { return null; } String result = null; if (adoNetType.endsWith("Binary")) { if ((byte[].class).isAssignableFrom(value.getClass())) { result = toEdmBinary((byte[]) value); } } else if (adoNetType.endsWith("Boolean")) { if ((Boolean.class).isAssignableFrom(value.getClass())) { result = toEdmBoolean((Boolean) value); } } else if (adoNetType.endsWith("DateTime")) { if ((Date.class).isAssignableFrom(value.getClass())) { result = toEdmDateTime((Date) value); } } else if (adoNetType.endsWith("DateTimeOffset")) { if ((Date.class).isAssignableFrom(value.getClass())) { result = toEdmDateTime((Date) value); } } else if (adoNetType.endsWith("Time")) { if ((Long.class).isAssignableFrom(value.getClass())) { result = toEdmTime((Long) value); } } else if (adoNetType.endsWith("Decimal")) { if ((Double.class).isAssignableFrom(value.getClass())) { result = toEdmDecimal((Double) value); } } else if (adoNetType.endsWith("Single")) { if ((Float.class).isAssignableFrom(value.getClass())) { result = toEdmSingle((Float) value); } else if ((Double.class).isAssignableFrom(value.getClass())) { result = toEdmSingle((Double) value); } } else if (adoNetType.endsWith("Double")) { if ((Double.class).isAssignableFrom(value.getClass())) { result = toEdmDouble((Double) value); } } else if (adoNetType.endsWith("Guid")) { result = value.toString(); } else if (adoNetType.endsWith("Int16")) { if ((Short.class).isAssignableFrom(value.getClass())) { result = toEdmInt16((Short) value); } } else if (adoNetType.endsWith("Int32")) { if ((Integer.class).isAssignableFrom(value.getClass())) { result = toEdmInt32((Integer) value); } } else if (adoNetType.endsWith("Int64")) { if ((Long.class).isAssignableFrom(value.getClass())) { result = toEdmInt64((Long) value); } } else if (adoNetType.endsWith("Byte")) { if ((Byte.class).isAssignableFrom(value.getClass())) { result = toEdmByte((Byte) value); } } else if (adoNetType.endsWith("String")) { result = "'" + value.toString() + "'"; } if (result == null) { result = value.toString(); } return result; } /** * Convert the given value to the String representation of a EDM Single * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmSingle(double value) { return singleFormat.format(value); } /** * Convert the given value to the String representation of a EDM Single * value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmSingle(float value) { return singleFormat.format(value); } /** * Convert the given value to the String representation of a EDM Time value. * * @param value * The value to convert. * @return The value converted as String object. */ public static String toEdmTime(long value) { return timeFormat.format(value); } /** * Returns the corresponding Java class or scalar type. * * @param edmTypeName * The type name. * @return The corresponding Java class or scalar type. */ public static Class toJavaClass(String edmTypeName) { Class result = Object.class; if (edmTypeName.endsWith("Binary")) { result = byte[].class; } else if (edmTypeName.endsWith("Boolean")) { result = Boolean.class; } else if (edmTypeName.endsWith("DateTime")) { result = Date.class; } else if (edmTypeName.endsWith("DateTimeOffset")) { result = Date.class; } else if (edmTypeName.endsWith("Time")) { result = Long.class; } else if (edmTypeName.endsWith("Decimal")) { result = Double.class; } else if (edmTypeName.endsWith("Single")) { result = Double.class; } else if (edmTypeName.endsWith("Double")) { result = Double.class; } else if (edmTypeName.endsWith("Guid")) { result = String.class; } else if (edmTypeName.endsWith("Int16")) { result = Short.class; } else if (edmTypeName.endsWith("Int32")) { result = Integer.class; } else if (edmTypeName.endsWith("Int64")) { result = Long.class; } else if (edmTypeName.endsWith("Byte")) { result = Byte.class; } else if (edmTypeName.endsWith("String")) { result = String.class; } return result; } /** * Returns the name of the corresponding Java class or scalar type. * * @param edmTypeName * The type name. * @return The name of the corresponding Java class or scalar type. */ public static String toJavaTypeName(String edmTypeName) { String result = "Object"; if (edmTypeName.endsWith("Binary")) { result = "byte[]"; } else if (edmTypeName.endsWith("Boolean")) { result = "boolean"; } else if (edmTypeName.endsWith("DateTime")) { result = "Date"; } else if (edmTypeName.endsWith("DateTimeOffset")) { result = "Date"; } else if (edmTypeName.endsWith("Time")) { result = "long"; } else if (edmTypeName.endsWith("Decimal")) { result = "double"; } else if (edmTypeName.endsWith("Single")) { result = "double"; } else if (edmTypeName.endsWith("Double")) { result = "double"; } else if (edmTypeName.endsWith("Guid")) { result = "String"; } else if (edmTypeName.endsWith("Int16")) { result = "short"; } else if (edmTypeName.endsWith("Int32")) { result = "int"; } else if (edmTypeName.endsWith("Int64")) { result = "long"; } else if (edmTypeName.endsWith("Byte")) { result = "byte"; } else if (edmTypeName.endsWith("String")) { result = "String"; } return result; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/EntitySet.java0000664000175000017500000000433411757206344032213 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Represents a set of entities, inside a EntityContainer. The type of these * entities is defined inside the current schema. * * @author Thierry Boileau * @see EntitySet * Element (EntityContainer CSDL) */ public class EntitySet extends NamedObject { /** The type of contained entities. */ private EntityType type; /** * Constructor. * * @param name * The name of the entity. */ public EntitySet(String name) { super(name); } /** * Returns the type of contained entities. * * @return The type of contained entities. */ public EntityType getType() { return type; } /** * Sets the type of contained entities. * * @param type * The type of contained entities. */ public void setType(EntityType type) { this.type = type; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Namespace.java0000664000175000017500000000410311757206344032151 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Represents a schema's namespace in the metadata descriptor of a OData * service. * * @author Thierry Boileau */ public class Namespace extends NamedObject { /** The short alias for this namespace. */ private String alias; /** * Constructor. * * @param name * The alias for this namespace. */ public Namespace(String name) { super(name); } /** * Returns the short alias for this namespace. * * @return The short alias for this namespace. */ public String getAlias() { return alias; } /** * Sets the short alias for this namespace. * * @param alias * The short alias for this namespace. */ public void setAlias(String alias) { this.alias = alias; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/AssociationSetEnd.java0000664000175000017500000000447411757206344033647 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Represents one entity implied in an AssociationSet. * * @author Thierry Boileau */ public class AssociationSetEnd { /** The role of this entity relatively to this association. */ private final String role; /** The type of this entity. */ private EntitySet type; /** * Constructor. * * @param role * The name of the role. */ public AssociationSetEnd(String role) { super(); this.role = role; } /** * Returns the role of this entity relatively to this association. * * @return The role of this entity relatively to this association. */ public String getRole() { return role; } /** * Returns the type of this entity. * * @return The type of this entity. */ public EntitySet getType() { return type; } /** * Sets the type of this entity. * * @param type * The type of this entity. */ public void setType(EntitySet type) { this.type = type; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/MetadataReader.java0000664000175000017500000007453611757206344033141 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.ext.odata.Service; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Used to parse a metadata descriptor of a given OData service and generate the * associated object's tree. * * @author Thierry Boileau */ public class MetadataReader extends DefaultHandler { /** The list of defined states of this parser. */ private enum State { ASSOCIATION, ASSOCIATION_END, ASSOCIATION_SET, ASSOCIATION_SET_END, COMPLEX_TYPE, COMPLEX_TYPE_PROPERTY, DOCUMENTATION, ENTITY_CONTAINER, ENTITY_SET, ENTITY_TYPE, ENTITY_TYPE_KEY, ENTITY_TYPE_PROPERTY, FUNCTION, FUNCTION_IMPORT, NAVIGATION_PROPERTY, NONE, ON_DELETE, PARAMETER, REFERENTIAL_CONSTRAINT, SCHEMA, USING } /** List of possible values for the blob reference member. */ private final String[] blobEditRefValues = { "blobEditReference", "blobEditReferenceValue" }; /** List of possible values for the blob reference member. */ private final String[] blobRefValues = { "blobReference", "blobReferenceValue" }; /** The current association. */ private Association currentAssociation; /** The current association set. */ private AssociationSet currentAssociationSet; /** The current complex type. */ private ComplexType currentComplexType; /** The current entity container. */ private EntityContainer currentEntityContainer; /** The current entity type. */ private EntityType currentEntityType; /** The current functionn import. */ private FunctionImport currentFunctionImport; /** The metadata objet to update. */ private Metadata currentMetadata; /** The current schema. */ private Schema currentSchema; /** The registered collection of associations. */ private Map registeredAssociations; /** The registered collection of complex types. */ private Map registeredComplexTypes; /** The registered collection of entity containers. */ private Map registeredContainers; /** The registered collection of entity sets. */ private Map registeredEntitySets; /** The registered collection of entity types. */ private Map registeredEntityTypes; /** The registered collection of namespaces. */ private List registeredNamespaces; /** The current heap of states. */ private List states; /** * Constructor. * * @param feed * The feed object to update during the parsing. */ public MetadataReader(Metadata metadata) { this.states = new ArrayList(); pushState(State.NONE); this.currentMetadata = metadata; } /** * Pick up the first method name among a given list of proposed names. * Returns null if the proposed values are already in the given entity type. * * @param type * The entity type to check. * @param values * The list of proposed values. * @return A method name. */ private String chooseAttributeName(EntityType type, String[] values) { String result = null; int index = 0; // Check that one of the possible names is not already set. for (int i = 0; i < type.getProperties().size() && (index < values.length); i++) { Property property = type.getProperties().get(i); if (values[index].equals(property.getName())) { index++; } } for (int i = 0; i < type.getAssociations().size() && (index < values.length); i++) { NavigationProperty property = type.getAssociations().get(i); if (values[index].equals(property.getName())) { index++; } } if (index != values.length) { result = values[index]; } return result; } /** * Explores the given attributes in order to get a declared property * mapping. * * @param type * The type of the mapped property. * @param property * The property that declares the mapping (is null if the mapping * is declared on the entity type tag). * @param metadata * The metadata instance to update. * @param attributes * The XML attributes to parse. */ private void discoverMapping(EntityType type, Property property, Metadata metadata, Attributes attributes) { String contentKind = null; String nsPrefix = null; String nsUri = null; String propertyPath = null; String valuePath = null; boolean keepInContent = true; contentKind = attributes.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_ContentKind"); if (contentKind == null) { contentKind = "text"; } nsPrefix = attributes.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_NsPrefix"); nsUri = attributes.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_NsUri"); String str = attributes .getValue(Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_KeepInContent"); if (str != null) { keepInContent = Boolean.parseBoolean(str); } if (property == null) { // mapping declared on the entity type, the "FC_SourcePath" // attribute is mandatory. propertyPath = attributes.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_SourcePath"); } else { propertyPath = property.getName(); } valuePath = attributes.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_TargetPath"); if (propertyPath != null && valuePath != null && !keepInContent) { // The mapping is really defined between a property and an XML // element, and the value is only available in a customized part of // the feed. if ((nsUri == null && nsPrefix == null) || (nsUri != null && nsPrefix != null)) { // The mapping is correctly declared (either in an ATOM or a // customized XML element). metadata.getMappings().add( new Mapping(type, nsPrefix, nsUri, propertyPath, valuePath, contentKind)); } } } @Override public void endDocument() throws SAXException { // Update references. for (Schema schema : currentMetadata.getSchemas()) { // - associations.ends.type for (Association association : schema.getAssociations()) { // association type for (AssociationEnd end : association.getEnds()) { end.setType((EntityType) resolve(end.getType(), registeredEntityTypes, schema)); } } for (EntityType entityType : schema.getEntityTypes()) { // entityType.key if (entityType.getKeys() != null) { List props = entityType.getKeys(); entityType.setKeys(new ArrayList()); for (Property prop : props) { for (Property property : entityType.getProperties()) { if (property.equals(prop)) { entityType.getKeys().add(property); break; } } } } // entityType.associations for (NavigationProperty navigationProperty : entityType .getAssociations()) { navigationProperty.setRelationship((Association) resolve( navigationProperty.getRelationship(), registeredAssociations, schema)); if (navigationProperty.getRelationship() != null) { // association's roles. for (AssociationEnd end : navigationProperty .getRelationship().getEnds()) { if (end.getRole().equals( navigationProperty.getFromRole().getRole())) { navigationProperty.setFromRole(end); } else if (end.getRole().equals( navigationProperty.getToRole().getRole())) { navigationProperty.setToRole(end); } } } else { navigationProperty.setFromRole(null); navigationProperty.setToRole(null); } } // entityType.baseType entityType.setBaseType((EntityType) resolve(entityType .getBaseType(), registeredEntityTypes, schema)); } for (ComplexType complexType : schema.getComplexTypes()) { // complexType.baseType complexType.setBaseType((ComplexType) resolve(complexType .getBaseType(), registeredComplexTypes, schema)); } } for (EntityContainer container : currentMetadata.getContainers()) { // - entityContainer.extended if (container.getExtended() != null) { container.setExtended(registeredContainers.get(container .getExtended().getName())); } for (AssociationSet associationSet : container.getAssociations()) { // - associationSet.association associationSet.setAssociation((Association) resolve( associationSet.getAssociation(), registeredAssociations, container.getSchema())); // - associationSet.ends.entitySet for (AssociationSetEnd end : associationSet.getEnds()) { for (EntitySet entitySet : container.getEntities()) { if (entitySet.equals(end.getType())) { end.setType(entitySet); break; } } } } // - entityContainer.entitySet.entityType for (EntitySet entitySet : container.getEntities()) { entitySet.setType((EntityType) resolve(entitySet.getType(), registeredEntityTypes, container.getSchema())); } // - entityContainer.functionImport.entitySet for (FunctionImport functionImport : container.getFunctionImports()) { functionImport.setEntitySet((EntitySet) resolve(functionImport .getEntitySet(), registeredEntitySets, container .getSchema())); } } for (Schema schema : currentMetadata.getSchemas()) { for (EntityType entityType : schema.getEntityTypes()) { // entityType.complexTypes for (ComplexProperty property : entityType .getComplexProperties()) { ComplexType type = (ComplexType) resolve(property .getComplexType(), registeredComplexTypes, schema); if (type != null) { property.setComplexType(type); } } } for (ComplexType complexType : schema.getComplexTypes()) { // entityType.complexTypes for (ComplexProperty property : complexType .getComplexProperties()) { ComplexType type = (ComplexType) resolve(property .getComplexType(), registeredComplexTypes, schema); if (type != null) { property.setComplexType(type); } } } } } @Override public void endElement(String uri, String localName, String name) throws SAXException { if ("schema".equalsIgnoreCase(localName)) { popState(); currentSchema = null; } else if ("using".equalsIgnoreCase(localName)) { popState(); } else if ("documentation".equalsIgnoreCase(localName)) { popState(); } else if ("entityType".equalsIgnoreCase(localName)) { if (currentEntityType.isBlob()) { String memberName = chooseAttributeName(currentEntityType, blobRefValues); if (memberName == null) { // Should not happen currentEntityType.setBlob(false); } else { Property property = new Property(memberName); currentEntityType.setBlobValueRefProperty(property); } // Sets the name of the property of the generated class that // contains the reference of resource that is able to update the // blob value. memberName = chooseAttributeName(currentEntityType, blobEditRefValues); if (memberName == null) { // Should not happen currentEntityType.setBlob(false); } else { Property property = new Property(memberName); currentEntityType.setBlobValueEditRefProperty(property); } } popState(); currentEntityType = null; } else if ("key".equalsIgnoreCase(localName)) { popState(); } else if ("property".equalsIgnoreCase(localName)) { popState(); } else if ("navigationProperty".equalsIgnoreCase(localName)) { popState(); } else if ("complexType".equalsIgnoreCase(localName)) { popState(); } else if ("association".equalsIgnoreCase(localName)) { popState(); currentAssociation = null; } else if ("end".equalsIgnoreCase(localName)) { popState(); } else if ("onDelete".equalsIgnoreCase(localName)) { popState(); } else if ("referentialConstraint".equalsIgnoreCase(localName)) { popState(); } else if ("functionImport".equalsIgnoreCase(localName)) { currentFunctionImport = null; popState(); } else if ("function".equalsIgnoreCase(localName)) { popState(); } else if ("entityContainer".equalsIgnoreCase(localName)) { popState(); currentEntityContainer = null; } else if ("entitySet".equalsIgnoreCase(localName)) { popState(); } else if ("associationSet".equalsIgnoreCase(localName)) { popState(); currentAssociationSet = null; } else if ("parameter".equalsIgnoreCase(localName)) { popState(); } } /** * Returns the current state when processing the document. * * @return the current state when processing the document. */ private State getState() { final State result = this.states.get(0); return result; } /** * Drops the current state from the stack and returns it. This state becomes * the former current state. * * @return the former current state. */ private State popState() { return this.states.remove(0); } /** * Adds the given state. * * @param state * The given state. */ private void pushState(State state) { this.states.add(0, state); } /** * Finds a namedObject inside a register. * * @param namedObject * The namedObject to find. * @param register * The register. * @param schema * The schema of the named object. * @return The namedObject if found inside the register, null otherwise. */ private NamedObject resolve(NamedObject namedObject, Map register, Schema currentSchema) { NamedObject result = null; if (namedObject != null && namedObject.getName() != null) { String key = null; int index = namedObject.getName().lastIndexOf("."); if (index != -1) { // Objects are named via the namespace alias or full name String nsName = namedObject.getName().substring(0, index); for (Namespace namespace : registeredNamespaces) { if (nsName.equals(namespace.getAlias()) || nsName.equals(namespace.getName())) { key = namespace.getName() + namedObject.getName().substring(index); break; } } } else { key = currentSchema.getNamespace().getName() + "." + namedObject.getName(); } result = register.get(key); } return result; } @Override public void startDocument() throws SAXException { registeredComplexTypes = new HashMap(); registeredEntityTypes = new HashMap(); registeredAssociations = new HashMap(); registeredEntitySets = new HashMap(); registeredNamespaces = new ArrayList(); registeredContainers = new HashMap(); } @Override public void startElement(String uri, String localName, String name, Attributes attrs) throws SAXException { if ("schema".equalsIgnoreCase(localName)) { pushState(State.SCHEMA); currentSchema = new Schema(); this.currentMetadata.getSchemas().add(currentSchema); Namespace namespace = new Namespace(attrs.getValue("Namespace")); namespace.setAlias(attrs.getValue("Alias")); this.currentSchema.setNamespace(namespace); registeredNamespaces.add(namespace); } else if ("using".equalsIgnoreCase(localName)) { pushState(State.USING); Namespace namespace = new Namespace(attrs.getValue("Namespace")); namespace.setAlias(attrs.getValue("Alias")); this.currentSchema.getReferencedNamespaces().add(namespace); } else if ("documentation".equalsIgnoreCase(localName)) { pushState(State.DOCUMENTATION); } else if ("entityType".equalsIgnoreCase(localName)) { pushState(State.ENTITY_TYPE); currentEntityType = new EntityType(attrs.getValue("Name")); currentEntityType.setSchema(this.currentSchema); currentEntityType.setAbstractType(Boolean.parseBoolean(attrs .getValue("Abstract"))); currentEntityType.setBlob(Boolean.parseBoolean(attrs.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HasStream"))); String value = attrs.getValue("BaseType"); if (value != null) { currentEntityType.setBaseType(new EntityType(value)); } this.currentSchema.getEntityTypes().add(currentEntityType); // Check the declaration of a property mapping. discoverMapping(currentEntityType, null, currentMetadata, attrs); // register the new type. registeredEntityTypes.put(currentSchema.getNamespace().getName() + "." + currentEntityType.getName(), currentEntityType); } else if ("key".equalsIgnoreCase(localName)) { pushState(State.ENTITY_TYPE_KEY); } else if ("propertyRef".equalsIgnoreCase(localName)) { if (getState() == State.ENTITY_TYPE_KEY) { if (currentEntityType.getKeys() == null) { currentEntityType.setKeys(new ArrayList()); } currentEntityType.getKeys().add( new Property(attrs.getValue("Name"))); } } else if ("property".equalsIgnoreCase(localName)) { String type = attrs.getValue("Type"); Property property; if (type.toLowerCase().startsWith("edm.")) { property = new Property(attrs.getValue("Name")); property.setType(new Type(attrs.getValue("Type"))); } else { ComplexProperty p = new ComplexProperty(attrs.getValue("Name")); p.setComplexType(new ComplexType(attrs.getValue("Type"))); property = p; } property.setDefaultValue(attrs.getValue("Default")); property.setNullable(Boolean.parseBoolean(attrs .getValue("Nullable"))); // ConcurrencyMode if ("fixed".equalsIgnoreCase(attrs.getValue("ConcurrencyMode"))) { property.setConcurrent(true); } else { property.setConcurrent(false); } property.setGetterAccess(attrs.getValue("GetterAccess")); property.setSetterAccess(attrs.getValue("SetterAccess")); String str = attrs.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "MimeType"); if (str != null) { property.setMediaType(MediaType.valueOf(str)); } if (getState() == State.ENTITY_TYPE) { pushState(State.ENTITY_TYPE_PROPERTY); if (property instanceof ComplexProperty) { this.currentEntityType.getComplexProperties().add( (ComplexProperty) property); } else { this.currentEntityType.getProperties().add(property); } } else { pushState(State.COMPLEX_TYPE_PROPERTY); if (property instanceof ComplexProperty) { this.currentComplexType.getComplexProperties().add( (ComplexProperty) property); } else { this.currentComplexType.getProperties().add(property); } } // Check the declaration of a property mapping. discoverMapping(this.currentEntityType, property, currentMetadata, attrs); } else if ("navigationProperty".equalsIgnoreCase(localName)) { pushState(State.NAVIGATION_PROPERTY); NavigationProperty property = new NavigationProperty(attrs .getValue("Name")); property .setFromRole(new AssociationEnd(attrs.getValue("FromRole"))); property.setRelationship(new Association(attrs .getValue("Relationship"))); property.setToRole(new AssociationEnd(attrs.getValue("ToRole"))); currentEntityType.getAssociations().add(property); } else if ("complexType".equalsIgnoreCase(localName)) { pushState(State.COMPLEX_TYPE); currentComplexType = new ComplexType(attrs.getValue("Name")); currentComplexType.setSchema(this.currentSchema); String value = attrs.getValue("BaseType"); if (value != null) { currentComplexType.setBaseType(new ComplexType(value)); } this.currentSchema.getComplexTypes().add(currentComplexType); // register the new type. registeredComplexTypes.put(currentSchema.getNamespace().getName() + "." + currentComplexType.getName(), currentComplexType); } else if ("association".equalsIgnoreCase(localName)) { pushState(State.ASSOCIATION); currentAssociation = new Association(attrs.getValue("Name")); currentSchema.getAssociations().add(currentAssociation); registeredAssociations.put(currentSchema.getNamespace().getName() + "." + currentAssociation.getName(), currentAssociation); } else if ("end".equalsIgnoreCase(localName)) { if (getState() == State.ASSOCIATION) { pushState(State.ASSOCIATION_END); AssociationEnd end = new AssociationEnd(attrs.getValue("Role")); end.setMultiplicity(attrs.getValue("Multiplicity")); end.setType(new EntityType(attrs.getValue("Type"))); currentAssociation.getEnds().add(end); } else { pushState(State.ASSOCIATION_SET_END); AssociationSetEnd end = new AssociationSetEnd(attrs .getValue("Role")); end.setType(new EntitySet(attrs.getValue("EntitySet"))); currentAssociationSet.getEnds().add(end); } } else if ("onDelete".equalsIgnoreCase(localName)) { pushState(State.ON_DELETE); } else if ("referentialConstraint".equalsIgnoreCase(localName)) { pushState(State.REFERENTIAL_CONSTRAINT); } else if ("functionImport".equalsIgnoreCase(localName)) { currentFunctionImport = new FunctionImport(attrs.getValue("Name")); currentFunctionImport.setReturnType(attrs.getValue("ReturnType")); currentFunctionImport.setEntitySet(new EntitySet(attrs .getValue("EntitySet"))); currentFunctionImport.setMethodAccess(attrs .getValue("MethodAccess")); currentFunctionImport.setMetadata(currentMetadata); String str = attrs.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HttpMethod"); if (str != null) { currentFunctionImport.setMethod(Method.valueOf(str)); } if (State.ENTITY_CONTAINER == getState()) { currentEntityContainer.getFunctionImports().add( currentFunctionImport); } pushState(State.FUNCTION_IMPORT); } else if ("parameter".equalsIgnoreCase(localName)) { if (State.FUNCTION_IMPORT == getState()) { Parameter parameter = new Parameter(attrs.getValue("Name")); parameter.setType(attrs.getValue("Type")); parameter.setMode(attrs.getValue("Mode")); String str = attrs.getValue("MaxLength"); if (str != null) { parameter.setMaxLength(Integer.parseInt(str)); } str = attrs.getValue("Precision"); if (str != null) { parameter.setPrecision(Integer.parseInt(str)); } str = attrs.getValue("Scale"); if (str != null) { parameter.setScale(Integer.parseInt(str)); } currentFunctionImport.getParameters().add(parameter); } pushState(State.PARAMETER); } else if ("function".equalsIgnoreCase(localName)) { pushState(State.FUNCTION); } else if ("entityContainer".equalsIgnoreCase(localName)) { pushState(State.ENTITY_CONTAINER); currentEntityContainer = new EntityContainer(attrs.getValue("Name")); currentEntityContainer.setDefaultEntityContainer(Boolean .parseBoolean(attrs.getValue( Service.WCF_DATASERVICES_METADATA_NAMESPACE, "IsDefaultEntityContainer"))); String value = attrs.getValue("Extends"); if (value != null) { currentEntityContainer.setExtended(new EntityContainer(value)); } currentEntityContainer.setSchema(currentSchema); currentMetadata.getContainers().add(currentEntityContainer); registeredContainers.put(currentSchema.getNamespace().getName() + "." + currentEntityContainer.getName(), currentEntityContainer); } else if ("entitySet".equalsIgnoreCase(localName)) { pushState(State.ENTITY_SET); EntitySet entitySet = new EntitySet(attrs.getValue("Name")); registeredEntitySets.put(currentSchema.getNamespace().getName() + "." + entitySet.getName(), entitySet); entitySet.setType(new EntityType(attrs.getValue("EntityType"))); currentEntityContainer.getEntities().add(entitySet); } else if ("associationSet".equalsIgnoreCase(localName)) { pushState(State.ASSOCIATION_SET); currentAssociationSet = new AssociationSet(attrs.getValue("Name")); currentAssociationSet.setAssociation(new Association(attrs .getValue("Association"))); currentEntityContainer.getAssociations().add(currentAssociationSet); } } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/FunctionImport.java0000664000175000017500000002035711757206344033246 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; import org.restlet.data.Method; /** * Represents an exposed stored procedure. * * @author Thierry Boileau * @see FunctionImport * Element (CSDL) */ public class FunctionImport extends NamedObject { /** The entity set returned by this function, if applicable. */ private EntitySet entitySet; /** The metadata. */ private Metadata metadata; /** The method used to invoke this function. */ private Method method; /** * The method access of this function (defined in the CSDL, but not * described). */ private String methodAccess; /** The list of parameters. */ private List parameters; /** The return type of this function. */ private String returnType; /** * Constructor. * * @param name * The name of the schema. */ public FunctionImport(String name) { super(name); } /** * Returns the entity set returned by this function, if applicable. * * @return The entity set returned by this function, if applicable. */ public EntitySet getEntitySet() { return entitySet; } /** * Returns the metadata. * * @return The metadata. */ public Metadata getMetadata() { return metadata; } /** * Returns the method used to invoke this function. * * @return The method used to invoke this function. */ public Method getMethod() { return method; } /** * Returns the method access of this function (defined in the CSDL, but not * described). * * @return The method access of this function (defined in the CSDL, but not * described). */ public String getMethodAccess() { return methodAccess; } /** * Returns the list of parameters. * * @return The list of parameters. */ public List getParameters() { if (parameters == null) { parameters = new ArrayList(); } return parameters; } /** * Returns the return type of this function. * * @return The return type of this function. */ public String getReturnType() { return returnType; } /** * Returns the return type as complex type, or null if it is not. * * @return The return type as complex type, or null if it is not. */ public ComplexType getReturnTypeAsComplexType() { ComplexType result = null; String rt = getSimpleReturnType(); if (getReturnType() != null && metadata != null) { for (Schema schema : metadata.getSchemas()) { for (ComplexType complexType : schema.getComplexTypes()) { if (rt.equalsIgnoreCase(complexType.getName())) { result = complexType; } } } } return result; } /** * Returns the return type as complex type, or null if it is not. * * @return The return type as complex type, or null if it is not. */ public EntityType getReturnTypeAsEntityType() { EntityType result = null; String rt = getSimpleReturnType(); if (getReturnType() != null && metadata != null) { for (Schema schema : metadata.getSchemas()) { for (EntityType entityType : schema.getEntityTypes()) { if (rt.equalsIgnoreCase(entityType.getName())) { result = entityType; } } } } return result; } /** * Returns the name of the return type, or if it's a collection, returns its * element's type. * * @return The name of the return type, or if it's a collection, returns its * element's type. */ public String getSimpleReturnType() { return returnType; } /** * Returns true if the result of the invocation of the service is a * collection. * * @return True if the result of the invocation of the service is a * collection. */ public boolean isReturningCollection() { return getReturnType() != null && getReturnType().toLowerCase().startsWith("collection("); } /** * Returns true if the result of the invocation of the service is a complex * type. * * @return True if the result of the invocation of the service is a complex * type. */ public boolean isReturningComplexType() { return getReturnTypeAsComplexType() != null; } /** * Returns true if the result of the invocation of the service is an EDM * simple type. * * @return True if the result of the invocation of the service is an EDM * simple type. */ public boolean isReturningEdmSimpleType() { return getReturnType() != null && getReturnType().toLowerCase().startsWith("edm."); } /** * Returns true if the result of the invocation of the service is an entity * type. * * @return True if the result of the invocation of the service is an entity * type. */ public boolean isReturningEntityType() { return getReturnType() != null && getReturnType().toLowerCase().startsWith("edm."); } /** * Sets the entity set returned by this function, if applicable. * * @param entitySet * The entity set returned by this function, if applicable. */ public void setEntitySet(EntitySet entitySet) { this.entitySet = entitySet; } /** * Sets the metadata. * * @param metadata * The metadata. */ public void setMetadata(Metadata metadata) { this.metadata = metadata; } /** * Sets the method used to invoke this function. * * @param method * The method used to invoke this function. */ public void setMethod(Method method) { this.method = method; } /** * Sets the method access of this function (defined in the CSDL, but not * described). * * @param methodAccess * The method access of this function (defined in the CSDL, but * not described). */ public void setMethodAccess(String methodAccess) { this.methodAccess = methodAccess; } /** * Sets the list of parameters. * * @param parameters * The list of parameters. */ public void setParameters(List parameters) { this.parameters = parameters; } /** * Sets the return type of this function. * * @param returnType * The return type of this function. */ public void setReturnType(String returnType) { this.returnType = returnType; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Schema.java0000664000175000017500000001122711757206344031462 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; /** * Defines a set of entity types and associations. * * @author Thierry Boileau * @see Schema * Element (CSDL) */ public class Schema { /** The list of defined associations. */ private List associations; /** The list of defined complex types. */ private List complexTypes; /** The list of defined entity types. */ private List entityTypes; /** The namespace of this schema. */ private Namespace namespace; /** The list of referenced namespaces. */ private List referencedNamespaces; /** * Returns the list of defined associations. * * @return The list of defined associations. */ public List getAssociations() { if (associations == null) { associations = new ArrayList(); } return associations; } /** * Returns the list of defined complex types. * * @return The list of defined complex types. */ public List getComplexTypes() { if (complexTypes == null) { complexTypes = new ArrayList(); } return complexTypes; } /** * Returns the list of defined entity types. * * @return The list of defined entity types. */ public List getEntityTypes() { if (entityTypes == null) { entityTypes = new ArrayList(); } return entityTypes; } /** * Returns the namespace of this schema. * * @return The namespace of this schema. */ public Namespace getNamespace() { return namespace; } /** * Returns the list of referenced namespaces. * * @return The list of referenced namespaces. */ public List getReferencedNamespaces() { if (referencedNamespaces == null) { referencedNamespaces = new ArrayList(); } return referencedNamespaces; } /** * Sets the list of defined associations. * * @param associations * The list of defined associations. */ public void setAssociations(List associations) { this.associations = associations; } /** * Sets the list of defined complex types. * * @param complexTypes * The list of defined complex types. */ public void setComplexTypes(List complexTypes) { this.complexTypes = complexTypes; } /** * Sets the list of defined entity types. * * @param types * The list of defined entity types. */ public void setEntityTypes(List types) { this.entityTypes = types; } /** * Sets the namespace of this schema. * * @param namespace * The namespace of this schema. */ public void setNamespace(Namespace namespace) { this.namespace = namespace; } /** * Sets the list of referenced namespaces. * * @param referencedNamespaces * The list of referenced namespaces. */ public void setReferencedNamespaces(List referencedNamespaces) { this.referencedNamespaces = referencedNamespaces; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/NamedObject.java0000664000175000017500000000544711757206344032444 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import org.restlet.ext.odata.internal.reflect.ReflectUtils; /** * Base class for all EDM concepts that have a name. * * @author Thierry Boileau */ public class NamedObject { /** The name of the EDM concept. */ private final String name; /** The name's value as a valid Java identifier. */ private final String normalizedName; /** * Constructor. * * @param name * The name of the entity. */ public NamedObject(String name) { super(); this.name = name; this.normalizedName = ReflectUtils.normalize(name); } /** * Returns the name. * * @return The name. */ public String getName() { return name; } /** * Returns the name following the the java naming rules. * * @see * Identifiers * @return The name following the the java naming rules. */ public String getNormalizedName() { return normalizedName; } @Override public boolean equals(Object obj) { boolean result = false; if (obj instanceof NamedObject) { NamedObject object = (NamedObject) obj; result = object.getName().equals(this.name); } return result; } @Override public int hashCode() { return this.name.hashCode(); } @Override public String toString() { return this.getClass() + " " + this.name; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/EntityContainer.java0000664000175000017500000001242311757206344033400 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; /** * Represents a set of entities and associations defined on a schema. * * @author Thierry Boileau * @see Entity * Containers (EDM) */ public class EntityContainer extends NamedObject { /** The list of associations. */ private List associations; /** Is this container the default one for a WCF Data Service? */ private boolean defaultEntityContainer; /** The list of entities. */ private List entities; /** The container this container inherits from. */ private EntityContainer extended; /** The list of function imports. */ private List functionImports; /** The schema. */ private Schema schema; /** * Constructor. * * @param name * The name of this entity container. */ public EntityContainer(String name) { super(name); } /** * Returns the list of associations. * * @return The list of associations. */ public List getAssociations() { if (associations == null) { associations = new ArrayList(); } return associations; } /** * Returns the list of entities. * * @return The list of entities. */ public List getEntities() { if (entities == null) { entities = new ArrayList(); } return entities; } /** * Returns the container this container inherits from. * * @return The container this container inherits from. */ public EntityContainer getExtended() { return extended; } /** * Returns the list of function imports. * * @return The list of function imports. */ public List getFunctionImports() { if (functionImports == null) { functionImports = new ArrayList(); } return functionImports; } /** * Returns the schema. * * @return The schema. */ public Schema getSchema() { return schema; } /** * Return true if this container is the default one for a WCF data service. * * @return True if this container is the default one for a WCF data service. */ public boolean isDefaultEntityContainer() { return defaultEntityContainer; } /** * Sets the list of associations. * * @param associations * The list of associations. */ public void setAssociations(List associations) { this.associations = associations; } /** * Indicates if this container is the default one for a WCF data service. * * @param defaultEntityContainer * True if this container is the default one for a WCF data * service. */ public void setDefaultEntityContainer(boolean defaultEntityContainer) { this.defaultEntityContainer = defaultEntityContainer; } /** * Sets the list of entities. * * @param entities * The list of entities. */ public void setEntities(List entities) { this.entities = entities; } /** * Sets the container this container inherits from. * * @param extended * The container this container inherits from. */ public void setExtended(EntityContainer extended) { this.extended = extended; } /** * Sets the list of function imports. * * @param functionImports * The list of function imports. */ public void setFunctionImports(List functionImports) { this.functionImports = functionImports; } /** * Sets the schema. * * @param schema * The schema. */ public void setSchema(Schema schema) { this.schema = schema; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/Parameter.java0000664000175000017500000001016011757206344032175 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Represents a parameter used when invoking a {@link FunctionImport}. * * @author Thierry Boileau * @see FunctionImport * Element (CSDL) */ public class Parameter extends NamedObject { /** The maximum length of the parameter value. */ private int maxLength; /** The mode of the parameter among "In", "Out", and "InOut". */ private String mode; /** The precision of the parameter value. */ private int precision; /** The scale of the parameter value. */ private int scale; /** The type of the parameter. */ private String type; /** * Constructor. * * @param name * The name of the parameter. */ public Parameter(String name) { super(name); } /** * Returns the maximum length of the parameter value. * * @return The maximum length of the parameter value. */ public int getMaxLength() { return maxLength; } /** * Returns the mode of the parameter among "In", "Out", and "InOut". * * @return The mode of the parameter among "In", "Out", and "InOut". */ public String getMode() { return mode; } /** * Returns the precision of the parameter value. * * @return The precision of the parameter value. */ public int getPrecision() { return precision; } /** * Returns the scale of the parameter value. * * @return The scale of the parameter value. */ public int getScale() { return scale; } /** * Returns the type of the parameter. * * @return The type of the parameter. */ public String getType() { return type; } /** * Sets the maximum length of the parameter value. * * @param maxLength * The maximum length of the parameter value. */ public void setMaxLength(int maxLength) { this.maxLength = maxLength; } /** * Sets the mode of the parameter. * * @param mode * The mode of the parameter. */ public void setMode(String mode) { this.mode = mode; } /** * Sets the precision of the parameter value. * * @param precision * The precision of the parameter value. */ public void setPrecision(int precision) { this.precision = precision; } /** * Sets the scale of the parameter value. * * @param scale * The scale of the parameter value. */ public void setScale(int scale) { this.scale = scale; } /** * Sets the type of the parameter. * * @param type * The type of the parameter. */ public void setType(String type) { this.type = type; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/ComplexType.java0000664000175000017500000000531311757206344032532 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; /** * Represents a kind of entity type, without "key", i.e. identifier. * * @author Thierry Boileau * @see Complex * Type (EDM) */ public class ComplexType extends ODataType { /** The list of complex types this type inherits from. */ private List complexTypes; /** * Constructor. * * @param name * The name of this type. */ public ComplexType(String name) { super(name); } /** * Returns the parent type this type inherits from. * * @return The parent type this type inherits from. */ @Override public ComplexType getBaseType() { return (ComplexType) super.getBaseType(); } /** * Returns the list of complex types this type inherits from. * * @return The list of complex types this type inherits from. */ public List getComplexTypes() { if (complexTypes == null) { complexTypes = new ArrayList(); } return complexTypes; } /** * Sets the list of complex types this type inherits from. * * @param complexTypes * The list of complex types this type inherits from. */ public void setComplexTypes(List complexTypes) { this.complexTypes = complexTypes; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/ODataType.java0000664000175000017500000001523011757206344032112 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Super class of complex and entity types. * * @author Thierry Boileau */ public class ODataType extends NamedObject implements Comparable { /** Is this type abstract? */ private boolean abstractType; /** The parent type this type inherits from. */ private ODataType baseType; /** The list of complex properties. */ private List complexProperties; /** The list of properties. */ private List properties; /** The schema. */ private Schema schema; /** * Constructor. * * @param name * The name of this entity type. */ public ODataType(String name) { super(name); } /** * Compares this object with the specified object for order. The comparison * is based on the computed full class name */ public int compareTo(ODataType o) { if (o == null) { return 1; } int result = 0; String s1 = getFullClassName(); String s2 = o.getFullClassName(); if (s1 != null) { result = s1.compareTo(s2); } else if (s2 != null) { result = -1 * s2.compareTo(s1); } return result; } /** * Returns the parent type this type inherits from. * * @return The parent type this type inherits from. */ public ODataType getBaseType() { return baseType; } /** * Returns the Java class name related to this entity type. * * @return The Java class name related to this entity type. */ public String getClassName() { return getNormalizedName().substring(0, 1).toUpperCase() + getNormalizedName().substring(1); } /** * Returns the list of complex properties. * * @return The list of complex properties. */ public List getComplexProperties() { if (complexProperties == null) { complexProperties = new ArrayList(); } return complexProperties; } /** * Returns the package name related to this entity type. * * @return The package name related to this entity type. */ public String getFullClassName() { return getPackageName() + "." + getClassName(); } /** * Returns the set of imported Java classes. * * @return The set of imported Java classes. */ public Set getImportedJavaClasses() { Set result = new TreeSet(); for (Property property : getProperties()) { if (property.getType() != null) { result.addAll(property.getType().getImportedJavaClasses()); } } for (ComplexProperty property : getComplexProperties()) { if (property.getComplexType() != null) { if (!property.getComplexType().getSchema().equals(getSchema())) { result.add(property.getComplexType().getFullClassName()); } } } return result; } /** * Returns the set of imported entity types. By default, returns an empty * set. * * @return The set of imported entity types. */ public Set getImportedTypes() { return new TreeSet(); } /** * Returns the package name related to this entity type. * * @return The package name related to this entity type. */ public String getPackageName() { return TypeUtils.getPackageName(getSchema()); } /** * Returns the list of properties. * * @return The list of properties. */ public List getProperties() { if (properties == null) { properties = new ArrayList(); } return properties; } /** * Returns the schema. * * @return The schema. */ public Schema getSchema() { return schema; } /** * Returns true if this type is abstract. * * @return True if this type is abstract */ public boolean isAbstractType() { return abstractType; } /** * Indicates if this type is abstract * * @param abstractType * True if this type is abstract */ public void setAbstractType(boolean abstractType) { this.abstractType = abstractType; } /** * Sets the parent type this type inherits from. * * @param baseType * The parent type this type inherits from. */ public void setBaseType(ODataType baseType) { this.baseType = baseType; } /** * Sets the list of complex properties. * * @param complexProperties * The list of complex properties. */ public void setComplexProperties(List complexProperties) { this.complexProperties = complexProperties; } /** * Sets the list of properties. * * @param properties * The list of properties. */ public void setProperties(List properties) { this.properties = properties; } /** * Sets the schema. * * @param schema * The schema. */ public void setSchema(Schema schema) { this.schema = schema; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/NavigationProperty.java0000664000175000017500000000630011757206344034122 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata.internal.edm; /** * Represents an association between two properties. * * @author Thierry Boileau * @see Navigation * Properties (EDM) */ public class NavigationProperty extends NamedObject { /** The start entity of the association. */ private AssociationEnd fromRole; /** The association. */ private Association relationship; /** The target entity of the association. */ private AssociationEnd toRole; /** * Constructor. * * @param name * The name of this navigation property. */ public NavigationProperty(String name) { super(name); } /** * Returns the start entity of the association. * * @return The start entity of the association. */ public AssociationEnd getFromRole() { return fromRole; } /** * Returns the association. * * @return The association. */ public Association getRelationship() { return relationship; } /** * Returns the target entity of the association. * * @return The target entity of the association. */ public AssociationEnd getToRole() { return toRole; } /** * Sets the start entity of the association. * * @param fromRole * The start entity of the association. */ public void setFromRole(AssociationEnd fromRole) { this.fromRole = fromRole; } /** * Sets the association. * * @param relationship * The association. */ public void setRelationship(Association relationship) { this.relationship = relationship; } /** * Sets the target entity of the association. * * @param toRole * The target entity of the association. */ public void setToRole(AssociationEnd toRole) { this.toRole = toRole; } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/Service.java0000664000175000017500000013215311757206344027303 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Preference; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Tag; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderReader; import org.restlet.ext.atom.Content; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Link; import org.restlet.ext.atom.Relation; import org.restlet.ext.odata.internal.EntryContentHandler; import org.restlet.ext.odata.internal.edm.AssociationEnd; import org.restlet.ext.odata.internal.edm.ComplexProperty; import org.restlet.ext.odata.internal.edm.EntityContainer; import org.restlet.ext.odata.internal.edm.EntityType; import org.restlet.ext.odata.internal.edm.FunctionImport; import org.restlet.ext.odata.internal.edm.Metadata; import org.restlet.ext.odata.internal.edm.Property; import org.restlet.ext.odata.internal.edm.TypeUtils; import org.restlet.ext.odata.internal.reflect.ReflectUtils; import org.restlet.ext.xml.DomRepresentation; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.util.Series; import org.w3c.dom.Node; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Acts as a manager for a specific remote OData service. OData services are * stateless, but {@link Service} instances are not. State on the client is * maintained between interactions in order to support features such as update * management.
    *
    * This Java class is more or less equivalent to the WCF DataServiceContext * class. * * @author Jerome Louvel * @see DataServiceContext * Class on MSDN */ public class Service { /** WCF data services metadata namespace. */ public final static String WCF_DATASERVICES_METADATA_NAMESPACE = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; /** WCF data services namespace. */ public final static String WCF_DATASERVICES_NAMESPACE = "http://schemas.microsoft.com/ado/2007/08/dataservices"; /** WCF data services scheme namespace. */ public final static String WCF_DATASERVICES_SCHEME_NAMESPACE = "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"; /** The client connector used in case the context does not deliver one. */ private Client clientConnector; /** * The version of the OData protocol extensions defined in every request * issued by this service. */ private String clientVersion; /** The credentials used to authenticate requests. */ private ChallengeResponse credentials; /** The latest request sent to the service. */ private Request latestRequest; /** The response to the latest request. */ private Response latestResponse; /** The internal logger. */ private Logger logger; /** * The maximum version of the OData protocol extensions the client can * accept in a response. */ private String maxClientVersion; /** The metadata of the WCF service. */ private Metadata metadata; /** * The version of the OData protocol extensions defined by the remote * service. */ private String serverVersion; /** The reference of the WCF service. */ private Reference serviceRef; /** * Constructor. * * @param serviceRef * The reference to the WCF service. */ public Service(Reference serviceRef) { try { // Test the given service URI which may be actually redirected. ClientResource cr = new ClientResource(serviceRef); if (cr.getNext() == null) { // The context does not provide a client connector. // Let instantiate our own. Protocol rProtocol = cr.getProtocol(); Reference rReference = cr.getReference(); Protocol protocol = (rProtocol != null) ? rProtocol : (rReference != null) ? rReference.getSchemeProtocol() : null; if (protocol != null) { this.clientConnector = new Client(protocol); // Set the next handler for reuse cr.setNext(this.clientConnector); } } cr.setFollowingRedirects(false); cr.get(); if (cr.getStatus().isRedirection()) { this.serviceRef = cr.getLocationRef(); } else { this.serviceRef = cr.getReference(); } } catch (Throwable e) { this.serviceRef = serviceRef; } } /** * Constructor. * * @param serviceUri * The URI of the WCF service. */ public Service(String serviceUri) { this(new Reference(serviceUri)); } /** * Adds an entity to an entity set. * * @param entitySetName * The path of the entity set relatively to the service URI. * @param entity * The entity to put. * @throws Exception */ public void addEntity(String entitySetName, Object entity) throws Exception { if (entity != null) { Entry entry = toEntry(entity); ClientResource resource = createResource(entitySetName); if (getMetadata() == null) { throw new Exception("Can't add entity to this entity set " + resource.getReference() + " due to the lack of the service's metadata."); } try { // TODO Fix chunked request with net client connector ByteArrayOutputStream o = new ByteArrayOutputStream(); entry.write(o); StringRepresentation r = new StringRepresentation(o.toString(), MediaType.APPLICATION_ATOM); Representation rep = resource.post(r); EntryContentHandler entryContentHandler = new EntryContentHandler( entity.getClass(), (Metadata) getMetadata(), getLogger()); Feed feed = new Feed(); feed.getEntries().add(new Entry(rep, entryContentHandler)); } catch (ResourceException re) { throw new ResourceException(re.getStatus(), "Can't add entity to this entity set " + resource.getReference()); } finally { this.latestRequest = resource.getRequest(); this.latestResponse = resource.getResponse(); } } } /** * Adds an association between the source and the target entity via the * given property name. * * @param source * The source entity to update. * @param sourceProperty * The name of the property of the source entity. * @param target * The entity to add to the source entity. * @throws Exception */ public void addLink(Object source, String sourceProperty, Object target) throws Exception { if (getMetadata() == null || source == null) { return; } if (target != null) { addEntity(getSubpath(source, sourceProperty), target); } } /** * Creates a query to a specific entity hosted by this service. * * @param * The class of the target entity. * @param subpath * The path to this entity relatively to the service URI. * @param entityClass * The target class of the entity. * @return A query object. */ public Query createQuery(String subpath, Class entityClass) { return new Query(this, subpath, entityClass); } /** * Returns an instance of {@link ClientResource} given an absolute * reference. This resource is completed with the service credentials. This * method can be overriden in order to complete the sent requests. * * @param reference * The reference of the target resource. * @return An instance of {@link ClientResource}. */ public ClientResource createResource(Reference reference) { ClientResource resource = new ClientResource(reference); if (clientConnector != null) { // We provide our own cient connector. resource.setNext(clientConnector); } resource.setChallengeResponse(getCredentials()); if (getClientVersion() != null || getMaxClientVersion() != null) { Form form = new Form(); if (getClientVersion() != null) { form.add("DataServiceVersion", getClientVersion()); } if (getMaxClientVersion() != null) { form.add("MaxDataServiceVersion", getMaxClientVersion()); } resource.getRequestAttributes().put( HeaderConstants.ATTRIBUTE_HEADERS, form); } return resource; } /** * Returns an instance of {@link ClientResource} given a path (relative to * the service reference). This resource is completed with the service * credentials. This method can be overriden in order to complete the sent * requests. * * @param relativePath * The relative reference of the target resource. * @return An instance of {@link ClientResource} given a path (relative to * the service reference). */ public ClientResource createResource(String relativePath) { String ref = getServiceRef().toString(); if (ref.endsWith("/")) { if (relativePath.startsWith("/")) { ref = ref + relativePath.substring(1); } else { ref = ref + relativePath; } } else { if (relativePath.startsWith("/")) { ref = ref + relativePath; } else { ref = ref + "/" + relativePath; } } return createResource(new Reference(ref)); } /** * Deletes an entity. * * @param entity * The entity to delete * @throws ResourceException */ public void deleteEntity(Object entity) throws ResourceException { if (getMetadata() == null) { return; } ClientResource resource = createResource(getSubpath(entity)); try { resource.delete(); } catch (ResourceException re) { throw new ResourceException(re.getStatus(), "Can't delete this entity " + resource.getReference()); } finally { this.latestRequest = resource.getRequest(); this.latestResponse = resource.getResponse(); } } /** * Deletes an entity. * * @param entitySubpath * The path of the entity to delete * @throws ResourceException */ public void deleteEntity(String entitySubpath) throws ResourceException { ClientResource resource = createResource(entitySubpath); try { resource.delete(); } catch (ResourceException re) { throw new ResourceException(re.getStatus(), "Can't delete this entity " + resource.getReference()); } finally { this.latestRequest = resource.getRequest(); this.latestResponse = resource.getResponse(); } } /** * Removes the association between a source entity and a target entity via * the given property name. * * @param source * The source entity to update. * @param sourceProperty * The name of the property of the source entity. * @param target * The entity to delete from the source entity. * @throws ResourceException */ public void deleteLink(Object source, String sourceProperty, Object target) throws ResourceException { if (getMetadata() == null) { return; } deleteEntity(getSubpath(source, sourceProperty, target)); } /** * Returns the version of the OData protocol extensions defined in every * request issued by this service. * * @return The version of the OData protocol extensions defined in every * request issued by this service. */ public String getClientVersion() { return clientVersion; } /** * Returns the credentials used to authenticate requests. * * @return The credentials used to authenticate requests. */ public ChallengeResponse getCredentials() { return credentials; } /** * Returns the latest request sent to the service. * * @return The latest request sent to the service. */ public Request getLatestRequest() { return latestRequest; } /** * Returns the response to the latest request. * * @return The response to the latest request. */ public Response getLatestResponse() { return latestResponse; } /** * Returns the current logger. * * @return The current logger. */ private Logger getLogger() { if (logger == null) { logger = Context.getCurrentLogger(); } return logger; } /** * Returns the maximum version of the OData protocol extensions the client * can accept in a response. * * @return The maximum version of the OData protocol extensions the client * can accept in a response. */ public String getMaxClientVersion() { return maxClientVersion; } /** * Returns the metadata document related to the current service. * * @return The metadata document related to the current service. */ protected Object getMetadata() { if (metadata == null) { ClientResource resource = createResource("$metadata"); try { getLogger().log( Level.INFO, "Get the metadata for " + getServiceRef() + " at " + resource.getReference()); Representation rep = resource.get(MediaType.APPLICATION_XML); this.metadata = new Metadata(rep, resource.getReference()); } catch (ResourceException e) { getLogger().log( Level.SEVERE, "Can't get the metadata for " + getServiceRef() + " (response's status: " + resource.getStatus() + ")"); } catch (Exception e) { getLogger().log(Level.SEVERE, "Can't get the metadata for " + getServiceRef(), e); } finally { this.latestRequest = resource.getRequest(); this.latestResponse = resource.getResponse(); } } return metadata; } /** * Returns the version of the OData protocol extensions supported by the * remote service. * * @return The version of the OData protocol extensions supported by the * remote service. */ @SuppressWarnings("unchecked") public String getServerVersion() { if (serverVersion == null) { // Get the version from the latest response. if (this.latestResponse != null) { Object o = this.latestResponse.getAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); if (o != null) { Series headers = (Series) o; String strHeader = headers .getFirstValue("DataServiceVersion"); if (strHeader != null) { HeaderReader reader = new HeaderReader( strHeader); this.serverVersion = reader.readToken(); } } } } return serverVersion; } /** * Returns the reference to the WCF service. * * @return The reference to the WCF service. */ public Reference getServiceRef() { return serviceRef; } /** * Extracts a String value from the Representation of a property or a * function, or a service operation, when this representation wraps an EDM * simple type. * * @param representation * The representation to parse * @param tagName * The name of the property or function. * @return The String value taken from the representation. * @throws Exception * Thrown when a parsing error occurs. */ private String getSimpleValue(Representation representation, String tagName) throws Exception { String result = null; if (representation == null) { return result; } if (MediaType.APPLICATION_ALL_XML.isCompatible(representation .getMediaType()) || MediaType.TEXT_XML.isCompatible(representation .getMediaType())) { DomRepresentation xmlRep = new DomRepresentation(representation); Node node = xmlRep.getNode("//" + tagName); if (node != null) { result = node.getTextContent(); } } else { result = representation.getText(); } return result; } /** * According to the metadata of the service, returns the path of the given * entity relatively to the current WCF service. * * @param entity * The entity. * @return The path of the given entity relatively to the current WCF * service. */ private String getSubpath(Object entity) { return ((Metadata) getMetadata()).getSubpath(entity); } /** * According to the metadata of the service, returns the path of the given * entity's property relatively to the current WCF service. * * @param entity * The entity. * @param propertyName * The name of the property. * @return The path of the given entity's property relatively to the current * WCF service. */ private String getSubpath(Object entity, String propertyName) { return ((Metadata) getMetadata()).getSubpath(entity, propertyName); } /** * According to the metadata of the service, returns the relative path of * the given target entity linked to the source entity via the source * property. * * @param source * The source entity to update. * @param sourceProperty * The name of the property of the source entity. * @param target * The entity linked to the source entity. * @return */ private String getSubpath(Object source, String sourceProperty, Object target) { return ((Metadata) getMetadata()).getSubpath(source, sourceProperty, target); } /** * Returns the ETag value for the given entity. * * @param entity * The given entity. * @return The ETag value for the given entity. */ private String getTag(Object entity) { String result = null; if (entity != null) { Metadata metadata = (Metadata) getMetadata(); EntityType type = metadata.getEntityType(entity.getClass()); StringBuilder sb = new StringBuilder(); boolean found = false; for (Property property : type.getProperties()) { if (property.isConcurrent()) { found = true; Object value = null; try { value = ReflectUtils.invokeGetter(entity, property .getName()); if (value != null) { sb.append(value); } } catch (Exception e) { getLogger().warning( "Cannot get the value of the property " + property.getName() + " on " + entity); } } } if (found) { result = Reference.encode(sb.toString(), CharacterSet.US_ASCII); } } return result; } /** * Returns the binary representation of the given media resource. If the * entity is not a media resource, it returns null. * * @param entity * The given media resource. * @return The binary representation of the given media resource. */ public Representation getValue(Object entity) throws ResourceException { Reference ref = getValueRef(entity); if (ref != null) { ClientResource cr = createResource(ref); return cr.get(); } return null; } /** * Returns the binary representation of the given media resource. If the * entity is not a media resource, it returns null. * * @param entity * The given media resource. * @param acceptedMediaTypes * The requested media types of the representation. * @return The given media resource. */ public Representation getValue(Object entity, List> acceptedMediaTypes) throws ResourceException { Reference ref = getValueRef(entity); if (ref != null) { ClientResource cr = createResource(ref); cr.getClientInfo().setAcceptedMediaTypes(acceptedMediaTypes); return cr.get(); } return null; } /** * Returns the binary representation of the given media resource. If the * entity is not a media resource, it returns null. * * @param entity * The given media resource. * @param mediaType * The requested media type of the representation * @return The given media resource. */ public Representation getValue(Object entity, MediaType mediaType) throws ResourceException { Reference ref = getValueRef(entity); if (ref != null) { ClientResource cr = createResource(ref); return cr.get(mediaType); } return null; } /** * Returns the reference used to edit the binary representation of the given * entity, if this is a media resource. It returns null otherwise. * * @param entity * The media resource. * @return Returns the reference used to edit the binary representation of * the given entity, if this is a media resource. It returns null * otherwise. */ private Reference getValueEditRef(Object entity) { if (entity != null) { Metadata metadata = (Metadata) getMetadata(); EntityType type = metadata.getEntityType(entity.getClass()); if (type.isBlob() && type.getBlobValueEditRefProperty() != null) { try { return (Reference) ReflectUtils.invokeGetter(entity, type .getBlobValueEditRefProperty().getName()); } catch (Exception e) { getLogger().warning( "Cannot get the value of the property " + type.getBlobValueEditRefProperty() .getName() + " on " + entity); } } else { getLogger().warning( "This entity is not a media resource " + entity); } } return null; } /** * Returns the reference of the binary representation of the given entity, * if this is a media resource. It returns null otherwise. * * @param entity * The media resource. * @return The reference of the binary representation of the given entity, * if this is a media resource. It returns null otherwise. */ public Reference getValueRef(Object entity) { if (entity != null) { Metadata metadata = (Metadata) getMetadata(); EntityType type = metadata.getEntityType(entity.getClass()); if (type.isBlob() && type.getBlobValueRefProperty() != null) { try { return (Reference) ReflectUtils.invokeGetter(entity, type .getBlobValueRefProperty().getName()); } catch (Exception e) { getLogger().warning( "Cannot get the value of the property " + type.getBlobValueRefProperty().getName() + " on " + entity); } } else { getLogger().warning( "This entity is not a media resource " + entity); } } return null; } /** * Invokes a service operation and return the raw representation sent back * by the service. * * @param service * The name of the service. * @param parameters * The list of required parameters. * @return The representation returned by the invocation of the service. * @throws ResourceException * Thrown when the service call is not successfull. * @see Service * Operations */ public Representation invokeComplex(String service, Series parameters) throws ResourceException { Representation result = null; Metadata metadata = (Metadata) getMetadata(); if (metadata != null && service != null) { // Look for the FunctionImport element. FunctionImport function = null; for (EntityContainer container : metadata.getContainers()) { for (FunctionImport f : container.getFunctionImports()) { if (service.equals(f.getName())) { function = f; break; } } if (function != null) { break; } } if (function != null) { ClientResource resource = createResource(service); resource.setMethod(function.getMethod()); if (parameters != null) { for (org.restlet.ext.odata.internal.edm.Parameter parameter : function .getParameters()) { resource.getReference().addQueryParameter( parameter.getName(), TypeUtils.getLiteralForm(parameters .getFirstValue(parameter.getName()), parameter.getType())); } } result = resource.handle(); this.latestRequest = resource.getRequest(); this.latestResponse = resource.getResponse(); if (resource.getStatus().isError()) { throw new ResourceException(resource.getStatus()); } } } return result; } /** * Invokes a service operation and return the String value sent back by the * service. * * @param service * The name of the service. * @param parameters * The list of required parameters. * @return The value returned by the invocation of the service as a String. * @throws ResourceException * Thrown when the service call is not successfull. * @throws Exception * Thrown when the value cannot be parsed. * @see Service * Operations */ public String invokeSimple(String service, Series parameters) throws ResourceException, Exception { return getSimpleValue(invokeComplex(service, parameters), service); } /** * Updates the given entity object with the value of the specified property. * * @param entity * The entity to update. * @param propertyName * The name of the property. */ public void loadProperty(Object entity, String propertyName) { if (getMetadata() == null || entity == null) { return; } Metadata metadata = (Metadata) getMetadata(); EntityType type = metadata.getEntityType(entity.getClass()); AssociationEnd association = metadata .getAssociation(type, propertyName); if (association != null) { EntityType propertyEntityType = association.getType(); try { Class propertyClass = ReflectUtils.getSimpleClass(entity, propertyName); if (propertyClass == null) { propertyClass = TypeUtils.getJavaClass(propertyEntityType); } Iterator iterator = createQuery( getSubpath(entity, propertyName), propertyClass) .iterator(); ReflectUtils.setProperty(entity, propertyName, association .isToMany(), iterator, propertyClass); } catch (Exception e) { getLogger().log( Level.WARNING, "Can't set the property " + propertyName + " of " + entity.getClass() + " for the service" + getServiceRef(), e); } } else { ClientResource resource = createResource(getSubpath(entity, propertyName)); try { Representation rep = resource.get(); try { String value = getSimpleValue(rep, propertyName); Property property = metadata.getProperty(entity, propertyName); ReflectUtils.setProperty(entity, property, value); } catch (Exception e) { getLogger().log( Level.WARNING, "Can't set the property " + propertyName + " of " + entity.getClass() + " for the service" + getServiceRef(), e); } } catch (ResourceException e) { getLogger().log( Level.WARNING, "Can't get the following resource " + resource.getReference() + " for the service" + getServiceRef(), e); } } } /** * Sets the version of the OData protocol extensions defined in every * request issued by this service. * * @param clientVersion * The version of the OData protocol extensions defined in every * request issued by this service. */ public void setClientVersion(String clientVersion) { this.clientVersion = clientVersion; } /** * Sets the credentials used to authenticate requests. * * @param credentials * The credentials used to authenticate requests. */ public void setCredentials(ChallengeResponse credentials) { this.credentials = credentials; } /** * Sets the latest request sent to the service. * * @param latestRequest * The latest request sent to the service. */ public void setLatestRequest(Request latestRequest) { this.latestRequest = latestRequest; } /** * Sets the response to the latest request. * * @param latestResponse * The response to the latest request. */ public void setLatestResponse(Response latestResponse) { this.latestResponse = latestResponse; } /** * Sets the association between the source and the target entity via the * given property name. If target is set to null, the call represents a * delete link operation. * * @param source * The source entity to update. * @param sourceProperty * The name of the property of the source entity. * @param target * The entity to add to the source entity. * @throws Exception */ public void setLink(Object source, String sourceProperty, Object target) throws Exception { if (getMetadata() == null || source == null) { return; } if (target != null) { // TODO Take into acount the case where the target does exist. Metadata metadata = (Metadata) getMetadata(); ClientResource resource = createResource(metadata .getSubpath(source) + "/$links/" + sourceProperty); try { // TODO Fix chunked request with net client connector StringBuilder sb = new StringBuilder(""); sb.append(getServiceRef().toString()); sb.append(metadata.getSubpath(target)); sb.append(""); StringRepresentation r = new StringRepresentation( sb.toString(), MediaType.APPLICATION_XML); resource.put(r); } catch (ResourceException re) { throw new ResourceException(re.getStatus(), "Can't set entity to this entity set " + resource.getReference()); } finally { this.latestRequest = resource.getRequest(); this.latestResponse = resource.getResponse(); } } else { ReflectUtils.invokeSetter(source, sourceProperty, null); updateEntity(source); } } /** * Sets the maximum version of the OData protocol extensions the client can * accept in a response. * * @param maxClientVersion * The maximum version of the OData protocol extensions the * client can accept in a response. */ public void setMaxClientVersion(String maxClientVersion) { this.maxClientVersion = maxClientVersion; } /** * Sets the value of the given media entry link. * * @param entity * The media entry link which value is to be updated * @param blob * The new representation. * @throws ResourceException */ public void setValue(Object entity, Representation blob) throws ResourceException { Reference ref = getValueEditRef(entity); if (ref != null) { ClientResource cr = createResource(ref); cr.put(blob); } } /** * Converts an entity to an Atom entry object. * * @param entity * The entity to wrap. * @return The Atom entry object that corresponds to the given entity. */ public Entry toEntry(final Object entity) { Entry result = null; if (entity != null) { Metadata metadata = (Metadata) getMetadata(); EntityType type = metadata.getEntityType(entity.getClass()); if (type != null) { final SaxRepresentation r = new SaxRepresentation( MediaType.APPLICATION_XML) { @Override public void write(XmlWriter writer) throws IOException { try { // Attribute for nullable values. AttributesImpl nullAttrs = new AttributesImpl(); nullAttrs.addAttribute( WCF_DATASERVICES_METADATA_NAMESPACE, "null", null, "boolean", "true"); writer.forceNSDecl( WCF_DATASERVICES_METADATA_NAMESPACE, "m"); writer.forceNSDecl(WCF_DATASERVICES_NAMESPACE, "d"); writer.startElement( WCF_DATASERVICES_METADATA_NAMESPACE, "properties"); write(writer, entity, nullAttrs); writer.endElement( WCF_DATASERVICES_METADATA_NAMESPACE, "properties"); } catch (SAXException e) { throw new IOException(e.getMessage()); } } private void write(XmlWriter writer, Object entity, AttributesImpl nullAttrs) throws SAXException { for (Field field : entity.getClass() .getDeclaredFields()) { String getter = "get" + field.getName().substring(0, 1) .toUpperCase() + field.getName().substring(1); Property prop = ((Metadata) getMetadata()) .getProperty(entity, field.getName()); if (prop != null) { writeProperty(writer, entity, prop, getter, nullAttrs); } } } private void writeProperty(XmlWriter writer, Object entity, Property prop, String getter, AttributesImpl nullAttrs) throws SAXException { for (Method method : entity.getClass() .getDeclaredMethods()) { if (method.getReturnType() != null && getter.equals(method.getName()) && method.getParameterTypes().length == 0) { Object value = null; try { value = method.invoke(entity, (Object[]) null); } catch (Exception e) { } if (value != null) { writer.startElement( WCF_DATASERVICES_NAMESPACE, prop .getName()); if (prop instanceof ComplexProperty) { write(writer, value, nullAttrs); } else { writer.characters(TypeUtils.toEdm( value, prop.getType())); } writer.endElement( WCF_DATASERVICES_NAMESPACE, prop .getName()); } else { if (prop.isNullable()) { writer.emptyElement( WCF_DATASERVICES_NAMESPACE, prop.getName(), prop.getName(), nullAttrs); } else { getLogger().warning( "The following property has a null value but is not marked as nullable: " + prop.getName()); writer.emptyElement( WCF_DATASERVICES_NAMESPACE, prop.getName()); } } break; } } } }; r.setNamespaceAware(true); if (type.isBlob()) { result = new Entry() { @Override public void writeInlineContent(XmlWriter writer) throws SAXException { try { r.write(writer); } catch (IOException e) { throw new SAXException(e); } } }; result.setNamespaceAware(true); Link editLink = new Link(getValueEditRef(entity), Relation.EDIT_MEDIA, null); result.getLinks().add(editLink); Content content = new Content(); // Get the external blob reference content.setExternalRef(getValueRef(entity)); content.setToEncode(false); result.setContent(content); } else { result = new Entry(); Content content = new Content(); content.setInlineContent(r); content.setToEncode(false); result.setContent(content); } } } return result; } /** * Updates an entity. * * @param entity * The entity to put. * @throws Exception */ public void updateEntity(Object entity) throws Exception { if (getMetadata() == null || entity == null) { return; } Entry entry = toEntry(entity); ClientResource resource = createResource(getSubpath(entity)); try { // TODO Fix chunked request with net client connector ByteArrayOutputStream o = new ByteArrayOutputStream(); entry.write(o); StringRepresentation r = new StringRepresentation(o.toString(), MediaType.APPLICATION_ATOM); String tag = getTag(entity); if (tag != null) { // Add a condition resource.getConditions().setMatch(Arrays.asList(new Tag(tag))); } resource.put(r); } catch (ResourceException re) { throw new ResourceException(re.getStatus(), "Can't update this entity " + resource.getReference()); } finally { this.latestRequest = resource.getRequest(); this.latestResponse = resource.getResponse(); } } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/package.html0000664000175000017500000000066211757206344027320 0ustar jamespagejamespage Support for the OData web protocol. This client-side extension helps accessing web services implementing the Open Data Protocol (OData). This protocol is typically powered by Microsoft's WCF Data Services technology. @since Restlet 2.0 @see Open Data Protocol (OData) @see WCF Data Services restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java0000664000175000017500000006131211757206344027006 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Link; import org.restlet.ext.atom.Relation; import org.restlet.ext.odata.internal.EntryContentHandler; import org.restlet.ext.odata.internal.FeedContentHandler; import org.restlet.ext.odata.internal.edm.EntityType; import org.restlet.ext.odata.internal.edm.Metadata; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.routing.Template; import org.restlet.routing.Variable; import org.restlet.util.Series; /** * Specific query to a OData service, represents a particular HTTP request to a * data service. This Java class is more or less equivalent to the WCF * DataServiceQuery class. * * @author Jerome Louvel * @see * @param */ public class Query implements Iterable { /** * Iterator that transparently supports sever-side paging. * * @author Thierry Boileau * * @param */ private class EntryIterator implements Iterator { /** The class of the listed objects. */ private Class entityClass; /** The inner iterator. */ private Iterator iterator; /** The reference to the next page. */ private Reference nextPage; /** The underlying service. */ private Service service; /** * Constructor. * * @param service * The underlying service. * @param iterator * The inner iterator. * @param nextPage * The reference to the next page. * @param entityClass * The class of the listed objects. */ public EntryIterator(Service service, Iterator iterator, Reference nextPage, Class entityClass) { super(); this.iterator = iterator; this.nextPage = nextPage; this.service = service; this.entityClass = entityClass; } @SuppressWarnings("unchecked") public boolean hasNext() { boolean result = false; if (iterator != null) { result = iterator.hasNext(); } if (!result && nextPage != null) { // Get the next page. Query query = service.createQuery(nextPage.toString(), (Class) entityClass); iterator = query.iterator(); if (iterator != null) { result = iterator.hasNext(); } // Set the reference to the next page nextPage = query.getNextPage(); } return result; } public E next() { E result = null; if (iterator != null) { if (iterator.hasNext()) { result = iterator.next(); } } return result; } public void remove() { if (iterator != null) { iterator.remove(); } } } // Defines the type of the current query. It has an impact on how to parse // the result. /** Type of query: complex type or property. */ public static final int TYPE_COMPLEX_TYPE_OR_PROPERTY = 3; /** Type of query: property. */ public static final int TYPE_COMPLEX_TYPE_PROPERTY = 4; /** Type of query: property bis?? */ public static final int TYPE_COMPLEX_TYPE_PROPERTY5 = 5; /** Type of query: entity. */ public static final int TYPE_ENTITY = 2; /** Type of query: entity set. */ public static final int TYPE_ENTITY_SET = 1; /** Type of query: links. */ public static final int TYPE_LINKS = 7; /** Type of query: property value. */ public static final int TYPE_PROPERTY_VALUE = 6; /** Type of query: unknown. */ public static final int TYPE_UNKNOWN = 0; /** The number of entities. */ private int count; private List entities; /** Class of the entities targeted by this query. */ private Class entityClass; /** The entity type of the entities targeted by this query. */ private EntityType entityType; /** Has the query been executed? */ private boolean executed; /** The atom feed object that wraps the data. */ private Feed feed; /** Is the inline asked for? */ private boolean inlineCount; /** Internal logger. */ private Logger logger; /** The reference to the next page (used in server-paging mode). */ private Reference nextPage; /** The query string. */ private String query; /** The parent client service. */ private Service service; /** The path of the targeted entity relatively to the data service URI. */ private String subpath; /** * Constructor. * * @param service * The data service requested by the query. * @param subpath * The path of the targeted entity relatively to the data service * URI. * @param entityClass * The class of the target entity. */ public Query(Service service, String subpath, Class entityClass) { this.count = -1; this.executed = false; this.entityClass = entityClass; if (service.getMetadata() != null) { this.entityType = ((Metadata) service.getMetadata()) .getEntityType(entityClass); } else { this.entityType = null; } this.service = service; Reference ref = new Reference(subpath); if (ref.isAbsolute()) { this.subpath = ref.getRelativeRef(service.getServiceRef()) .toString(true, true); } else { this.subpath = subpath; } } /** * Creates a new Query with the query parameter set in the URI generated * by the returned query. * * @param name * The string value that contains the name of the query string * option to add. * @param value * The value of the query string option. * @return A new Query with the query parameter set in the URI generated * by the returned query. */ @SuppressWarnings("unchecked") public Query addParameter(String name, String value) { Query result = new Query(this.getService(), this.getSubpath(), (Class) this.entityClass); if (getQuery() == null || "".equals(getQuery())) { result.setQuery(name + "=" + value); } else { result.setQuery(getQuery() + "&" + name + "=" + value); } return result; } /** * Creates a new Query with the query parameter set in the URI generated * by the returned query. * * @param params * the set of name/value pairs to add to the query string * @return A new Query with the query parameter set in the URI generated * by the returned query. */ @SuppressWarnings("unchecked") public Query addParameters(Series params) { Query result = new Query(this.getService(), this.getSubpath(), (Class) this.entityClass); StringBuilder builder = new StringBuilder(); if (params != null) { for (int i = 0; i < params.size(); i++) { Parameter param = params.get(i); if (i == 0) { builder.append(param.getName()); builder.append("="); builder.append(param.getValue()); } } } if (getQuery() == null || "".equals(getQuery())) { result.setQuery(builder.toString()); } else { result.setQuery(getQuery() + "&" + builder.toString()); } return result; } /** * Returns the complete target URI reference for this query. It is composed * of the data service base URI, the subpath and the query string. * * @return The complete target URI reference. */ protected String createTargetUri() { String service = getService().getServiceRef().toString(); StringBuilder result = new StringBuilder(service); String subpath = (getSubpath() == null) ? "" : getSubpath(); if (service.endsWith("/")) { if (subpath.startsWith("/")) { result.append(subpath.substring(1)); } else { result.append(subpath); } } else { if (subpath.startsWith("/")) { result.append(subpath); } else { result.append("/").append(subpath); } } if (getQuery() != null) { result.append("?").append(getQuery()); } return result.toString(); } /** * Executes the query. * * @throws Exception */ public void execute() throws Exception { if (!isExecuted()) { String targetUri = createTargetUri(); ClientResource resource = service.createResource(new Reference( targetUri)); Metadata metadata = (Metadata) service.getMetadata(); if (metadata == null) { throw new Exception( "Can't execute the query without the service's metadata."); } Representation result = null; try { result = resource.get(MediaType.APPLICATION_ATOM); } catch (ResourceException e) { getLogger().warning( "Can't execute the query for the following reference: " + targetUri + " due to " + e.getMessage()); throw e; } if (resource.getStatus().isSuccess()) { // Guess the type of query based on the URI structure switch (guessType(targetUri)) { case TYPE_ENTITY_SET: FeedContentHandler feedContentHandler = new FeedContentHandler( entityClass, entityType, metadata, getLogger()); setFeed(new Feed(result, feedContentHandler)); this.count = feedContentHandler.getCount(); this.entities = feedContentHandler.getEntities(); break; case TYPE_ENTITY: EntryContentHandler entryContentHandler = new EntryContentHandler( entityClass, entityType, metadata, getLogger()); Feed feed = new Feed(); feed.getEntries().add( new Entry(result, entryContentHandler)); setFeed(feed); entities = new ArrayList(); if (entryContentHandler.getEntity() != null) { entities.add(entryContentHandler.getEntity()); } break; case TYPE_UNKNOWN: // Guess the type of query based on the returned // representation Representation rep = new StringRepresentation(result .getText()); String string = rep.getText().substring(0, Math.min(100, rep.getText().length())); if (string.contains("( entityClass, entityType, metadata, getLogger()); setFeed(new Feed(rep, feedContentHandler)); this.count = feedContentHandler.getCount(); this.entities = feedContentHandler.getEntities(); } else if (string.contains("( entityClass, entityType, metadata, getLogger()); feed = new Feed(); feed.getEntries().add( new Entry(rep, entryContentHandler)); setFeed(feed); entities = new ArrayList(); if (entryContentHandler.getEntity() != null) { entities.add(entryContentHandler.getEntity()); } } default: // Can only guess entity and entity set, a priori. // TODO May we go a step further by analyzing the metadata // of the data services? // Do we support only those two types? // Another way is to guess from the result representation. // Sometimes, it returns a set, an entity, or a an XML // representation of a property. break; } } service.setLatestRequest(resource.getRequest()); service.setLatestResponse(resource.getResponse()); setExecuted(true); } } /** * Creates a new Query with the $expand option set in the URI generated * by the returned query. * * @param path * A string value that contains the requesting URI. * @return A new Query with the $expand option set in the URI generated * by the returned query. */ public Query expand(String path) { return addParameter("$expand", path); } /** * Creates a new Query with the $filter option set in the URI generated * by the returned query. * * @param predicate * A string value that contains the predicate used to filter the * data. * @return A new Query with the $filter option set in the URI generated * by the returned query. */ public Query filter(String predicate) { return addParameter("$filter", predicate); } /** * Returns the total number of elements in the entity set, or -1 if it is * available. * * @return The total number of elements in the entity set. * @throws Exception */ public int getCount() { if (inlineCount) { if (!isExecuted()) { // Execute the query which sets the count retrieved from the // Atom document. try { execute(); } catch (Exception e) { getLogger().warning( "Cannot retrieve inline count value due to: " + e.getMessage()); } } } else { // Send a request to a specific URI. String targetUri = createTargetUri(); if (guessType(targetUri) == TYPE_ENTITY) { targetUri = targetUri.substring(0, targetUri.lastIndexOf("(")); } targetUri += "/$count"; ClientResource resource = service.createResource(new Reference( targetUri)); try { Representation result = resource.get(); count = Integer.parseInt(result.getText()); } catch (Exception e) { getLogger().warning( "Cannot parse count value due to: " + e.getMessage()); } } return count; } /** * Returns the atom feed object that wrap the data. * * @return The atom feed object that wrap the data. */ private Feed getFeed() { return feed; } /** * Returns the current logger. * * @return The current logger. */ private Logger getLogger() { if (logger == null) { logger = Context.getCurrentLogger(); } return logger; } /** * Return the reference to the next page (used in server-paging mode). * * @return The reference to the next page (used in server-paging mode). */ private Reference getNextPage() { return nextPage; } /** * Returns the query string that may be completed by calls to * {@link Query#addParameter(String, String)} or * {@link Query#expand(String)}. * * @return The query string. */ private String getQuery() { return query; } /** * Returns the parent client service. * * @return The parent client service. */ public Service getService() { return service; } /** * Returns the path of the targeted entity relatively to the data service * URI. * * @return The path of the targeted entity relatively to the data service * URI. */ public String getSubpath() { return subpath; } /** * Tries to deduce the type of the query based on the analysis of the target * URI, and returns it. * * @param targetUri * The target URI to analyse. * @return The deduced type of query or {@link Query#TYPE_UNKNOWN} if it is * unknown. */ private int guessType(String targetUri) { // Remove the trailing query part String uri = targetUri; int index = targetUri.indexOf("?"); if (index != -1) { uri = uri.substring(0, index); } // Let's detect the type of query int type = TYPE_UNKNOWN; // Can only match entitySet and entity from the the target URI String entitySet = "{service}.svc/{entitySet}"; String entity = entitySet + "({keyPredicate})"; Template t = new Template(entity, Template.MODE_EQUALS); t.getVariables().put("entitySet", new Variable(Variable.TYPE_ALL, "", true, false)); t.getVariables().put("keyPredicate", new Variable(Variable.TYPE_ALL, "", true, false)); if (t.match(uri) != -1) { return TYPE_ENTITY; } t.setPattern(entitySet); if (t.match(uri) != -1) { return TYPE_ENTITY_SET; } return type; } /** * Creates a new Query with the $inlinecount option set in the URI * generated by the returned query. * * @param inlineCount * True if the total number of entities in the entity set must be * returned. * @return A new Query with the $inlinecount option set in the URI * generated by the returned query. */ public Query inlineCount(boolean inlineCount) { Query result = null; if (inlineCount) { result = addParameter("$inlinecount", "allpages"); } else { result = addParameter("$inlinecount", "none"); } result.inlineCount = inlineCount; return result; } /** * Returns true if the query has been executed. * * @return true if the query has been executed. */ private boolean isExecuted() { return executed; } /** * Returns an iterator over a set of elements of type T. It returns null if * the query does not retrieve elements. * * @return an Iterator or null if the query does not retrieve elements. */ public Iterator iterator() { Iterator result = null; try { execute(); result = entities.iterator(); // result = new FeedParser(getFeed(), this.entityClass, // ((Metadata) getService().getMetadata())).parse(); // Detect server-paging mode. nextPage = null; for (Link link : getFeed().getLinks()) { if (Relation.NEXT.equals(link.getRel())) { nextPage = link.getHref(); break; } } if (nextPage != null) { result = new EntryIterator(this.service, result, nextPage, entityClass); } } catch (Exception e) { getLogger().log(Level.WARNING, "Can't parse the content of " + createTargetUri(), e); } return result; } /** * Creates a new Query with the $orderby option set in the URI generated * by the returned query. * * @param criteria * A string value that contains the criteria used to order the * results. * @return A new Query with the $orderby option set in the URI generated * by the returned query. */ public Query orderBy(String criteria) { return addParameter("$orderby", criteria); } /** * Creates a new Query with the $select option set in the URI generated * by the returned query. * * @param select * A string value that contains the requesting URI. * @return A new Query with the $select option set in the URI generated * by the returned query. */ public Query select(String select) { return addParameter("$select", select); } /** * Indicates whether the query has been executed. * * @param executed * true if the query has been executed. */ private void setExecuted(boolean executed) { this.executed = executed; } /** * Sets the atom feed object that wraps the data. * * @param feed * The atom feed object that wraps the data. */ private void setFeed(Feed feed) { this.feed = feed; } /** * Sets the query string of the request. * * @param query * The query string of the request. */ public void setQuery(String query) { this.query = query; } /** * Creates a new Query with the $skip option set in the URI generated by * the returned query. * * @param rowsCount * A number of rows to skip. * @return A new Query with the $skip option set in the URI generated by * the returned query. */ public Query skip(int rowsCount) { return addParameter("$skip", Integer.toString(rowsCount)); } /** * Creates a new Query with the $skiptoken option set in the URI * generated by the returned query. * * @param token * A string value that contains the requesting URI. * @return A new Query with the $skiptoken option set in the URI * generated by the returned query. */ public Query skipToken(String token) { return addParameter("$skiptoken", token); } /** * Creates a new Query with the $top option set in the URI generated by * the returned query. * * @param rowsCount * A number of rows used to limit the number of results. * @return A new Query with the $top option set in the URI generated by * the returned query. */ public Query top(int rowsCount) { return addParameter("$top", Integer.toString(rowsCount)); } } restlet-2.0.14/org.restlet.ext.odata/src/org/restlet/ext/odata/Generator.java0000664000175000017500000003477511757206344027644 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.odata; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.ext.odata.internal.edm.ComplexType; import org.restlet.ext.odata.internal.edm.EntityContainer; import org.restlet.ext.odata.internal.edm.EntityType; import org.restlet.ext.odata.internal.edm.Metadata; import org.restlet.ext.odata.internal.edm.Schema; import org.restlet.ext.odata.internal.edm.TypeUtils; import org.restlet.ext.odata.internal.reflect.ReflectUtils; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import freemarker.template.Configuration; /** * Code generator for accessing OData services. The generator use metadata * exposed by an online service to generate client-side artifacts facilitating * the execution of queries on the available entities. * * @author Thierry Boileau */ public class Generator { /** * Takes two (or three) parameters:
    *
      *
    1. The URI of the OData service
    2. *
    3. The output directory (optional, used the current directory by * default)
    4. *
    5. The name of the generated service class name (optional)
    6. *
    * * @param args * The list of arguments. */ public static void main(String[] args) { System.out.println("---------------------------"); System.out.println("OData client code generator"); System.out.println("---------------------------"); System.out.println("step 1 - check parameters"); String errorMessage = null; if (args == null || args.length == 0) { errorMessage = "Missing mandatory argument: URI of the OData service."; } File outputDir = null; if (errorMessage == null) { if (args.length > 1) { outputDir = new File(args[1]); } else { try { outputDir = new File(".").getCanonicalFile(); } catch (IOException e) { errorMessage = "Unable to get the target directory. " + e.getMessage(); } } if (outputDir.exists()) { System.out.println("step 2 - check the ouput directory"); if (!outputDir.isDirectory()) { errorMessage = outputDir.getPath() + " is not a valid directory."; } } else { try { System.out.println("step 2 - create the ouput directory"); outputDir.mkdirs(); } catch (Throwable e) { errorMessage = "Cannot create " + outputDir.getPath() + " due to: " + e.getMessage(); } } } if (errorMessage == null) { System.out.println("step 3 - get the metadata descriptor"); String dataServiceUri = null; if (args[0].endsWith("$metadata")) { dataServiceUri = args[0].substring(0, args[0].length() - 10); } else if (args[0].endsWith("/")) { dataServiceUri = args[0].substring(0, args[0].length() - 1); } else { dataServiceUri = args[0]; } Service service = new Service(dataServiceUri); if (service.getMetadata() == null) { errorMessage = "Cannot retrieve the metadata."; } else { System.out.println("step 4 - generate source code"); Generator svcUtil = null; if (args.length == 3) { svcUtil = new Generator(service.getServiceRef(), args[2]); } else { svcUtil = new Generator(service.getServiceRef()); } try { svcUtil.generate(outputDir); System.out .print("The source code has been generated in directory: "); System.out.println(outputDir.getPath()); } catch (Exception e) { errorMessage = "Cannot generate the source code in directory: " + outputDir.getPath(); } } } if (errorMessage != null) { System.out.println("An error occurred: "); System.out.println(errorMessage); System.out.println(); System.out .println("Please check that you provide the following parameters:"); System.out.println(" - Valid URI for the remote service"); System.out .println(" - Valid directory path where to generate the files"); System.out .println(" - Valid name for the generated service class (optional)"); } } /** The name of the service class (in case there is only one in the schema). */ private String serviceClassName; /** The URI of the target data service. */ private Reference serviceRef; /** * Constructor. * * @param serviceRef * The URI of the OData service. */ public Generator(Reference serviceRef) { this(serviceRef, null); } /** * Constructor. The name of the service class can be provided if there is * only one service defined in the metadata. * * @param serviceRef * The URI of the OData service. * @param serviceClassName * The name of the service class (in case there is only one in * the metadata). */ public Generator(Reference serviceRef, String serviceClassName) { super(); this.serviceRef = serviceRef; if (serviceClassName != null) { this.serviceClassName = ReflectUtils.normalize(serviceClassName); this.serviceClassName = this.serviceClassName.substring(0, 1) .toUpperCase() + this.serviceClassName.substring(1); } } /** * Constructor. * * @param serviceUri * The URI of the OData service. */ public Generator(String serviceUri) { this(serviceUri, null); } /** * Constructor. The name of the service class can be provided if there is * only one service defined in the metadata. * * @param serviceUri * The URI of the OData service. * @param serviceClassName * The name of the service class (in case there is only one in * the metadata). */ public Generator(String serviceUri, String serviceClassName) { this(new Reference(serviceUri), serviceClassName); } /** * Generates the client code to the given output directory. * * @param outputDir * The output directory. * @throws Exception */ public void generate(File outputDir) throws Exception { Service service = new Service(serviceRef); Metadata metadata = (Metadata) service.getMetadata(); if (metadata == null) { throw new Exception("Can't get the metadata for this service: " + serviceRef); } Configuration fmc = new Configuration(); fmc.setDefaultEncoding(CharacterSet.UTF_8.getName()); // Generate classes String rootTemplates = "clap://class/org/restlet/ext/odata/internal/templates"; Representation complexTmpl = new StringRepresentation( new ClientResource(rootTemplates + "/complexType.ftl").get() .getText()); Representation entityTmpl = new StringRepresentation( new ClientResource(rootTemplates + "/entityType.ftl").get() .getText()); Representation serviceTmpl = new StringRepresentation( new ClientResource(rootTemplates + "/service.ftl").get() .getText()); for (Schema schema : metadata.getSchemas()) { if ((schema.getEntityTypes() != null && !schema.getEntityTypes() .isEmpty()) || (schema.getComplexTypes() != null && !schema .getComplexTypes().isEmpty())) { String packageName = TypeUtils.getPackageName(schema); File packageDir = new File(outputDir, packageName.replace(".", System.getProperty("file.separator"))); packageDir.mkdirs(); // For each entity type for (EntityType type : schema.getEntityTypes()) { String className = type.getClassName(); Map dataModel = new HashMap(); dataModel.put("type", type); dataModel.put("schema", schema); dataModel.put("metadata", metadata); dataModel.put("className", className); dataModel.put("packageName", packageName); TemplateRepresentation templateRepresentation = new TemplateRepresentation( entityTmpl, fmc, dataModel, MediaType.TEXT_PLAIN); templateRepresentation.setCharacterSet(CharacterSet.UTF_8); // Write the template representation as a Java class templateRepresentation.write(new FileOutputStream(new File( packageDir, type.getClassName() + ".java"))); } for (ComplexType type : schema.getComplexTypes()) { String className = type.getClassName(); Map dataModel = new HashMap(); dataModel.put("type", type); dataModel.put("schema", schema); dataModel.put("metadata", metadata); dataModel.put("className", className); dataModel.put("packageName", packageName); TemplateRepresentation templateRepresentation = new TemplateRepresentation( complexTmpl, fmc, dataModel, MediaType.TEXT_PLAIN); templateRepresentation.setCharacterSet(CharacterSet.UTF_8); // Write the template representation as a Java class templateRepresentation.write(new FileOutputStream(new File( packageDir, type.getClassName() + ".java"))); } } } if (metadata.getContainers() != null && !metadata.getContainers().isEmpty()) { for (EntityContainer entityContainer : metadata.getContainers()) { Schema schema = entityContainer.getSchema(); // Generate Service subclass StringBuffer className = new StringBuffer(); if (serviceClassName != null) { // Try to use the Client preference if (entityContainer.isDefaultEntityContainer()) { className.append(serviceClassName); } else if (metadata.getContainers().size() == 1) { className.append(serviceClassName); } else { className.append(schema.getNamespace() .getNormalizedName().substring(0, 1) .toUpperCase()); className.append(schema.getNamespace() .getNormalizedName().substring(1)); className.append("Service"); } } else { className.append(schema.getNamespace().getNormalizedName() .substring(0, 1).toUpperCase()); className.append(schema.getNamespace().getNormalizedName() .substring(1)); className.append("Service"); } Map dataModel = new HashMap(); dataModel.put("schema", schema); dataModel.put("metadata", metadata); dataModel.put("className", className); dataModel.put("dataServiceUri", this.serviceRef.getTargetRef()); dataModel.put("entityContainer", entityContainer); TemplateRepresentation templateRepresentation = new TemplateRepresentation( serviceTmpl, fmc, dataModel, MediaType.TEXT_PLAIN); templateRepresentation.setCharacterSet(CharacterSet.UTF_8); // Write the template representation as a Java class templateRepresentation.write(new FileOutputStream(new File( outputDir, className + ".java"))); } } } /** * Generates the client code to the given output directory. * * @param outputDir * The output directory. * @throws Exception */ public void generate(String outputDir) throws Exception { generate(new File(outputDir)); } } restlet-2.0.14/org.restlet.ext.jetty/0000775000175000017500000000000012001473177020143 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/pom.xml0000600000175000017500000000341112001473177021445 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.jetty Restlet Extension - Jetty Integration with Jetty. org.eclipse.jetty jetty-ajp 7.1.6.v20100715 org.eclipse.jetty jetty-continuation 7.1.6.v20100715 org.eclipse.jetty jetty-http 7.1.6.v20100715 org.eclipse.jetty jetty-io 7.1.6.v20100715 org.eclipse.jetty jetty-server 7.1.6.v20100715 org.eclipse.jetty jetty-util 7.1.6.v20100715 javax.servlet servlet-api 2.5 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.jetty/src/0000775000175000017500000000000012001473177020732 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/META-INF/0000775000175000017500000000000011757206452022101 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/META-INF/services/0000775000175000017500000000000011757206352023723 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/META-INF/services/org.restlet.engine.ServerHelper0000664000175000017500000000021511757206352031765 0ustar jamespagejamespageorg.restlet.ext.jetty.AjpServerHelper # AJP org.restlet.ext.jetty.HttpServerHelper # HTTP org.restlet.ext.jetty.HttpsServerHelper # HTTPS restlet-2.0.14/org.restlet.ext.jetty/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023532 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.jetty/src/org/0000775000175000017500000000000011757206352021527 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/0000775000175000017500000000000011757206352023211 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/0000775000175000017500000000000011757206352024011 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/0000775000175000017500000000000011757206352025150 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyServerHelper.java0000664000175000017500000002750411757206352031451 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jetty; import java.io.IOException; import javax.servlet.ServletException; import org.eclipse.jetty.server.AbstractConnector; import org.eclipse.jetty.server.HttpConnection; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.restlet.ext.jetty.internal.JettyCall; /** * Abstract Jetty Web server connector. Here is the list of parameters that are * supported. They should be set in the Server's context before it is started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    minThreadsint1Minimum threads waiting to service requests.
    maxThreadsint255Maximum threads that will service requests.
    threadMaxIdleTimeMsint60000Time for an idle thread to wait for a request or read.
    lowResourcesMaxIdleTimeMsint2500Time in ms that connections will persist if listener is low on resources. *
    acceptorThreadsint1Number of acceptor threads to set.
    acceptQueueSizeint0Size of the accept queue.
    requestHeaderSizeint4*1024Size of the buffer to be used for request headers.
    responseHeaderSizeint4*1024Size of the buffer to be used for response headers.
    requestBufferSizeint8*1024Size of the content buffer for receiving requests.
    responseBufferSizeint32*1024Size of the content buffer for sending responses.
    ioMaxIdleTimeMsint30000Maximum time to wait on an idle IO operation.
    soLingerTimeint1000SO linger time (see Jetty documentation).
    gracefulShutdownint0The time (in ms) to wait for existing requests to complete before fully * stopping the server.
    * * @see Jetty home page * @author Jerome Louvel */ public abstract class JettyServerHelper extends org.restlet.engine.http.HttpServerHelper { /** * Jetty server wrapped by a parent Restlet HTTP server connector. * * @author Jerome Louvel */ private static class WrappedServer extends org.eclipse.jetty.server.Server { JettyServerHelper helper; /** * Constructor. * * @param server * The Jetty HTTP server. */ public WrappedServer(JettyServerHelper server) { this.helper = server; } /** * Handler method converting a Jetty Connection into a Restlet Call. * * @param connection * The connection to handle. */ @Override public void handle(HttpConnection connection) throws IOException, ServletException { this.helper.handle(new JettyCall(this.helper.getHelped(), connection)); } } /** The wrapped Jetty server. */ private volatile Server wrappedServer; /** The internal Jetty connector. */ private volatile AbstractConnector connector; /** * Constructor. * * @param server * The server to help. */ public JettyServerHelper(org.restlet.Server server) { super(server); this.connector = null; this.wrappedServer = null; } /** * Configures the internal Jetty connector. * * @param connector * The internal Jetty connector. */ protected void configure(AbstractConnector connector) { if (getHelped().getAddress() != null) { connector.setHost(getHelped().getAddress()); } connector.setPort(getHelped().getPort()); connector.setLowResourcesMaxIdleTime(getLowResourcesMaxIdleTimeMs()); connector.setAcceptors(getAcceptorThreads()); connector.setAcceptQueueSize(getAcceptQueueSize()); connector.setRequestHeaderSize(getRequestHeaderSize()); connector.setResponseHeaderSize(getResponseHeaderSize()); connector.setRequestBufferSize(getRequestBufferSize()); connector.setResponseBufferSize(getResponseBufferSize()); connector.setMaxIdleTime(getIoMaxIdleTimeMs()); connector.setSoLingerTime(getSoLingerTime()); } /** * Creates a new internal Jetty connector. * * @return A new internal Jetty connector. */ protected abstract AbstractConnector createConnector(); /** * Returns the number of acceptor threads to set. * * @return The number of acceptor threads to set. */ public int getAcceptorThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( "acceptorThreads", "1")); } /** * Returns the size of the accept queue. * * @return The size of the accept queue. */ public int getAcceptQueueSize() { return Integer.parseInt(getHelpedParameters().getFirstValue( "acceptQueueSize", "0")); } /** * Returns the time (in ms) to wait for existing requests to complete before * fully stopping the server. * * @return The graceful shutdown delay. */ public int getGracefulShutdown() { return Integer.parseInt(getHelpedParameters().getFirstValue( "gracefulShutdown", "0")); } /** * Returns the maximum time to wait on an idle IO operation. * * @return The maximum time to wait on an idle IO operation. */ public int getIoMaxIdleTimeMs() { return Integer.parseInt(getHelpedParameters().getFirstValue( "ioMaxIdleTimeMs", "30000")); } /** * Returns the time in ms that connections will persist if listener is low * on resources. * * @return The time in ms that connections will persist if listener is low * on resources. */ public int getLowResourcesMaxIdleTimeMs() { return Integer.parseInt(getHelpedParameters().getFirstValue( "lowResourcesMaxIdleTimeMs", "2500")); } /** * Returns the maximum threads that will service requests. * * @return The maximum threads that will service requests. */ public int getMaxThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( "maxThreads", "255")); } /** * Returns the minimum threads waiting to service requests. * * @return The minimum threads waiting to service requests. */ public int getMinThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( "minThreads", "1")); } /** * Returns the size of the content buffer for receiving requests. * * @return The size of the content buffer for receiving requests. */ public int getRequestBufferSize() { return Integer.parseInt(getHelpedParameters().getFirstValue( "requestBufferSize", Integer.toString(8 * 1024))); } /** * Returns the size of the buffer to be used for request headers. * * @return The size of the buffer to be used for request headers. */ public int getRequestHeaderSize() { return Integer.parseInt(getHelpedParameters().getFirstValue( "requestHeaderSize", Integer.toString(4 * 1024))); } /** * Returns the size of the content buffer for sending responses. * * @return The size of the content buffer for sending responses. */ public int getResponseBufferSize() { return Integer.parseInt(getHelpedParameters().getFirstValue( "responseBufferSize", Integer.toString(32 * 1024))); } /** * Returns the size of the buffer to be used for response headers. * * @return The size of the buffer to be used for response headers. */ public int getResponseHeaderSize() { return Integer.parseInt(getHelpedParameters().getFirstValue( "responseHeaderSize", Integer.toString(4 * 1024))); } /** * Returns the SO linger time (see Jetty 6 documentation). * * @return The SO linger time (see Jetty 6 documentation). */ public int getSoLingerTime() { return Integer.parseInt(getHelpedParameters().getFirstValue( "soLingerTime", "1000")); } /** * Returns the time for an idle thread to wait for a request or read. * * @return The time for an idle thread to wait for a request or read. */ public int getThreadMaxIdleTimeMs() { return Integer.parseInt(getHelpedParameters().getFirstValue( "threadMaxIdleTimeMs", "60000")); } /** * Returns the wrapped Jetty server. * * @return The wrapped Jetty server. */ protected Server getWrappedServer() { if (this.wrappedServer == null) { this.wrappedServer = new WrappedServer(this); // Configuring the thread pool QueuedThreadPool btp = new QueuedThreadPool(); btp.setMaxIdleTimeMs(getThreadMaxIdleTimeMs()); btp.setMaxThreads(getMaxThreads()); btp.setMinThreads(getMinThreads()); getWrappedServer().setThreadPool(btp); if (getGracefulShutdown() > 0) { getWrappedServer().setGracefulShutdown(getGracefulShutdown()); } } return this.wrappedServer; } /** * Sets the wrapped Jetty server. * * @param wrappedServer * The wrapped Jetty server. */ protected void setWrappedServer(Server wrappedServer) { this.wrappedServer = wrappedServer; } @Override public void start() throws Exception { if (this.connector == null) { this.connector = createConnector(); configure(this.connector); getWrappedServer().addConnector(this.connector); } getWrappedServer().start(); setEphemeralPort(this.connector.getLocalPort()); } @Override public void stop() throws Exception { getWrappedServer().stop(); } } restlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/internal/0000775000175000017500000000000011757206352026764 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/internal/JettyCall.java0000664000175000017500000002320511757206352031524 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jetty.internal; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.security.cert.Certificate; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.server.HttpConnection; import org.restlet.Response; import org.restlet.Server; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.engine.http.ServerCall; import org.restlet.util.Series; /** * Call that is used by the Jetty HTTP server connectors. * * @author Jerome Louvel */ public class JettyCall extends ServerCall { /** The wrapped Jetty HTTP connection. */ private final HttpConnection connection; /** Indicates if the request headers were parsed and added. */ private volatile boolean requestHeadersAdded; /** * Constructor. * * @param server * The parent server. * @param connection * The wrapped Jetty HTTP connection. */ public JettyCall(Server server, HttpConnection connection) { super(server); this.connection = connection; this.requestHeadersAdded = false; } /** * Closes the end point. */ @Override public boolean abort() { try { getConnection().getEndPoint().close(); } catch (IOException e) { } return true; } @Override public void complete() { // Flush the response try { this.connection.flushResponse(); } catch (IOException ex) { getLogger().log(Level.FINE, "Unable to flush the response", ex); } // Fully complete the response try { this.connection.completeResponse(); } catch (IOException ex) { getLogger().log(Level.FINE, "Unable to complete the response", ex); } } @Override public String getClientAddress() { return getConnection().getRequest().getRemoteAddr(); } @Override public int getClientPort() { return getConnection().getRequest().getRemotePort(); } /** * Returns the wrapped Jetty HTTP connection. * * @return The wrapped Jetty HTTP connection. */ public HttpConnection getConnection() { return this.connection; } /** * Returns the request method. * * @return The request method. */ @Override public String getMethod() { return getConnection().getRequest().getMethod(); } @Override public ReadableByteChannel getRequestEntityChannel(long size) { return null; } @Override public InputStream getRequestEntityStream(long size) { try { return getConnection().getRequest().getInputStream(); } catch (IOException e) { getLogger().log(Level.WARNING, "Unable to get request entity stream", e); return null; } } @Override public ReadableByteChannel getRequestHeadChannel() { // Not available return null; } /** * Returns the list of request headers. * * @return The list of request headers. */ @Override public Series getRequestHeaders() { final Series result = super.getRequestHeaders(); if (!this.requestHeadersAdded) { // Copy the headers from the request object String headerName; String headerValue; for (final Enumeration names = getConnection() .getRequestFields().getFieldNames(); names .hasMoreElements();) { headerName = names.nextElement(); for (final Enumeration values = getConnection() .getRequestFields().getValues(headerName); values .hasMoreElements();) { headerValue = values.nextElement(); result.add(new Parameter(headerName, headerValue)); } } this.requestHeadersAdded = true; } return result; } @Override public InputStream getRequestHeadStream() { // Not available return null; } /** * Returns the URI on the request line (most like a relative reference, but * not necessarily). * * @return The URI on the request line. */ @Override public String getRequestUri() { return getConnection().getRequest().getUri().toString(); } /** * Returns the response channel if it exists. * * @return The response channel if it exists. */ @Override public WritableByteChannel getResponseEntityChannel() { return null; } /** * Returns the response stream if it exists. * * @return The response stream if it exists. */ @Override public OutputStream getResponseEntityStream() { try { return getConnection().getResponse().getOutputStream(); } catch (IOException e) { getLogger().log(Level.WARNING, "Unable to get response entity stream", e); return null; } } /** * Returns the response address.
    * Corresponds to the IP address of the responding server. * * @return The response address. */ @Override public String getServerAddress() { return getConnection().getRequest().getLocalAddr(); } @Override public String getSslCipherSuite() { return (String) getConnection().getRequest().getAttribute( "javax.servlet.request.cipher_suite"); } @Override public List getSslClientCertificates() { final Certificate[] certificateArray = (Certificate[]) getConnection() .getRequest().getAttribute( "javax.servlet.request.X509Certificate"); if (certificateArray != null) { return Arrays.asList(certificateArray); } return null; } @Override public Integer getSslKeySize() { Integer keySize = (Integer) getConnection().getRequest().getAttribute( "javax.servlet.request.key_size"); if (keySize == null) { keySize = super.getSslKeySize(); } return keySize; } @Override public String getSslSessionId() { Object sessionId = getConnection().getRequest().getAttribute( "javax.servlet.request.ssl_session_id"); if (sessionId instanceof String) { return (String) sessionId; } return null; } /** * Indicates if the request was made using a confidential mean.
    * * @return True if the request was made using a confidential mean.
    */ @Override public boolean isConfidential() { return getConnection().getRequest().isSecure(); } @Override public boolean isConnectionBroken(Throwable exception) { return (exception instanceof EofException) || super.isConnectionBroken(exception); } @Override public void sendResponse(Response response) throws IOException { // Add call headers Parameter header; for (final Iterator iter = getResponseHeaders().iterator(); iter .hasNext();) { header = iter.next(); getConnection().getResponse().addHeader(header.getName(), header.getValue()); } // Set the status code in the response. We do this after adding the // headers because when we have to rely on the 'sendError' method, // the Servlet containers are expected to commit their response. if (Status.isError(getStatusCode()) && (response.getEntity() == null)) { try { getConnection().getResponse().sendError(getStatusCode(), getReasonPhrase()); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to set the response error status", ioe); } } else { // Send the response entity getConnection().getResponse().setStatus(getStatusCode()); super.sendResponse(response); } } } restlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/internal/JettyHandler.java0000664000175000017500000000774011757206352032234 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jetty.internal; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.HttpConnection; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.restlet.Server; import org.restlet.ext.jetty.HttpServerHelper; import org.restlet.ext.jetty.HttpsServerHelper; import org.restlet.ext.jetty.JettyServerHelper; /** * Jetty handler that knows how to convert Jetty calls into Restlet calls. This * handler isn't a full server, if you use it you need to manually setup the * Jetty server connector and add this handler to a Jetty server. * * @author Valdis Rigdon * @author Jerome Louvel */ public class JettyHandler extends AbstractHandler { /** The Restlet server helper. */ private final JettyServerHelper helper; /** * Constructor for HTTP server connectors. * * @param server * Restlet HTTP server connector. */ public JettyHandler(Server server) { this(server, false); } /** * Constructor for HTTP server connectors. * * @param server * Restlet server connector. * @param secure * Indicates if the server supports HTTP or HTTPS. */ public JettyHandler(Server server, boolean secure) { if (secure) { this.helper = new HttpsServerHelper(server); } else { this.helper = new HttpServerHelper(server); } } @Override protected void doStart() throws Exception { super.doStart(); this.helper.start(); } @Override protected void doStop() throws Exception { super.doStop(); this.helper.stop(); } /** * Handles a Jetty call by converting it to a Restlet call and giving it for * processing to the Restlet server. * * @param target * The target of the request, either a URI or a name. * @param request * The Jetty request. * @param servletRequest * The Servlet request. * @param servletResponse * The Servlet response. */ public void handle(String target, Request arg1, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException { final Request baseRequest = (servletRequest instanceof Request) ? (Request) servletRequest : HttpConnection.getCurrentConnection().getRequest(); this.helper.handle(new JettyCall(this.helper.getHelped(), HttpConnection.getCurrentConnection())); baseRequest.setHandled(true); } } restlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/package.html0000664000175000017500000000035611757206352027435 0ustar jamespagejamespage Integration with Jetty 7.1 which is a new implementation of the popular Jetty HTTP server able to leverage NIO. @since Restlet 1.0 @see Jetty HTTP server restlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpsServerHelper.java0000664000175000017500000002331611757206352031451 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jetty; import java.io.File; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import org.eclipse.jetty.server.AbstractConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSocketConnector; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.security.SslUtils; import org.restlet.engine.security.SslContextFactory; /** * Jetty HTTPS server connector. Here is the list of additional parameters that * are supported. They should be set in the Server's context before it is * started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    sslContextFactoryStringnullLet you specify a {@link SslContextFactory} class name as a parameter, or * an instance as an attribute for a more complete and flexible SSL context * setting. If set, it takes precedance over the other SSL parameters below.
    keystorePathString${user.home}/.keystoreSSL keystore path
    keystorePasswordStringSSL keystore password
    keystoreTypeStringJKSSSL keystore type
    keyPasswordString${keystorePassword}SSL key password
    certAlgorithmStringSunX509SSL certificate algorithm
    disabledCipherSuitesStringnullWhitespace-separated list of disabled cipher suites and/or can be * specified multiple times
    needClientAuthenticationbooleanfalseIndicates if we require client certificate authentication
    secureRandomAlgorithmStringnull (see java.security.SecureRandom)Name of the RNG algorithm. (see java.security.SecureRandom class)
    securityProviderStringnull (see javax.net.ssl.SSLContext)Java security provider name (see java.security.Provider class)
    sslProtocolStringTLSSSL protocol
    typeint2The type of Jetty connector to use.
    * 1 : Selecting NIO connector (Jetty's SslSelectChannelConnector class).
    * 2 : Blocking BIO connector (Jetty's SslSocketConnector class)
    wantClientAuthenticationbooleanfalseIndicates if we would like client certificate authentication (only for * the BIO connector type)
    * * @see How * to configure SSL for Jetty * @author Jerome Louvel */ public class HttpsServerHelper extends JettyServerHelper { /** * Constructor. * * @param server * The server to help. */ public HttpsServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTPS); } /** * Creates a new internal Jetty connector. * * @return A new internal Jetty connector. */ @Override protected AbstractConnector createConnector() { AbstractConnector result = null; final SslContextFactory sslContextFactory = SslUtils .getSslContextFactory(this); final String[] excludedCipherSuites = SslUtils .getDisabledCipherSuites(this); // Create and configure the Jetty HTTP connector switch (getType()) { case 1: // Selecting NIO connector SslSelectChannelConnector nioResult; nioResult = new SslSelectChannelConnector() { @Override protected SSLContext createSSLContext() throws Exception { return sslContextFactory.createSslContext(); } }; if (isNeedClientAuthentication()) { nioResult.setNeedClientAuth(true); } else if (isWantClientAuthentication()) { nioResult.setWantClientAuth(true); } if (excludedCipherSuites != null) { nioResult.setExcludeCipherSuites(excludedCipherSuites); } result = nioResult; break; case 2: // Blocking BIO connector SslSocketConnector bioResult = new SslSocketConnector() { @Override protected SSLServerSocketFactory createFactory() throws Exception { final SSLContext sslContext = sslContextFactory .createSslContext(); return sslContext.getServerSocketFactory(); } }; if (isNeedClientAuthentication()) { bioResult.setNeedClientAuth(true); } else if (isWantClientAuthentication()) { bioResult.setWantClientAuth(true); } if (excludedCipherSuites != null) { bioResult.setExcludeCipherSuites(excludedCipherSuites); } result = bioResult; break; } return result; } /** * Returns the SSL certificate algorithm. * * @return The SSL certificate algorithm. */ @Deprecated public String getCertAlgorithm() { return getHelpedParameters().getFirstValue("certAlgorithm", "SunX509"); } /** * Returns the SSL key password. * * @return The SSL key password. */ @Deprecated public String getKeyPassword() { return getHelpedParameters().getFirstValue("keyPassword", getKeystorePassword()); } /** * Returns the SSL keystore password. * * @return The SSL keystore password. */ @Deprecated public String getKeystorePassword() { return getHelpedParameters().getFirstValue("keystorePassword", ""); } /** * Returns the SSL keystore path. * * @return The SSL keystore path. */ @Deprecated public String getKeystorePath() { return getHelpedParameters().getFirstValue("keystorePath", System.getProperty("user.home") + File.separator + ".keystore"); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getKeystoreType() { return getHelpedParameters().getFirstValue("keystoreType", "JKS"); } /** * Returns the name of the RNG algorithm. * * @return The name of the RNG algorithm. */ @Deprecated public String getSecureRandomAlgorithm() { return getHelpedParameters().getFirstValue("secureRandomAlgorithm", null); } /** * Returns the Java security provider name. * * @return The Java security provider name. */ @Deprecated public String getSecurityProvider() { return getHelpedParameters().getFirstValue("securityProvider", null); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getSslProtocol() { return getHelpedParameters().getFirstValue("sslProtocol", "TLS"); } /** * Returns the type of Jetty connector to use. * * @return The type of Jetty connector to use. */ public int getType() { return Integer.parseInt(getHelpedParameters() .getFirstValue("type", "2")); } /** * Indicates if we require client certificate authentication. * * @return True if we require client certificate authentication. */ public boolean isNeedClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "needClientAuthentication", "false")); } /** * Indicates if we would like client certificate authentication. * * @return True if we would like client certificate authentication. */ public boolean isWantClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "wantClientAuthentication", "false")); } } restlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/AjpServerHelper.java0000664000175000017500000000405111757206352031054 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jetty; import org.eclipse.jetty.ajp.Ajp13SocketConnector; import org.eclipse.jetty.server.AbstractConnector; import org.restlet.Server; import org.restlet.data.Protocol; /** * Jetty AJP server connector. * * @see Jetty home page * @author Jerome Louvel */ public class AjpServerHelper extends JettyServerHelper { /** * Constructor. * * @param server * The server to help. */ public AjpServerHelper(Server server) { super(server); getProtocols().add(Protocol.AJP); } /** * Creates a new internal Jetty connector. * * @return A new internal Jetty connector. */ @Override protected AbstractConnector createConnector() { return new Ajp13SocketConnector(); } } restlet-2.0.14/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpServerHelper.java0000664000175000017500000000675711757206352031300 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jetty; import org.eclipse.jetty.server.AbstractConnector; import org.eclipse.jetty.server.bio.SocketConnector; import org.eclipse.jetty.server.nio.BlockingChannelConnector; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.restlet.Server; import org.restlet.data.Protocol; /** * Jetty HTTP server connector. Here is the list of additional parameters that * are supported. They should be set in the Server's context before it is * started: * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    typeint1The type of Jetty connector to use.
    * 1 : Selecting NIO connector (Jetty's SelectChannelConnector class).
    * 2 : Blocking NIO connector (Jetty's BlockingChannelConnector class).
    * 3 : Blocking BIO connector (Jetty's SocketConnector class).
    * * @see Jetty home page * @author Jerome Louvel */ public class HttpServerHelper extends JettyServerHelper { /** * Constructor. * * @param server * The server to help. */ public HttpServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTP); } /** * Creates a new internal Jetty connector. * * @return A new internal Jetty connector. */ @Override protected AbstractConnector createConnector() { AbstractConnector result = null; // Create and configure the Jetty HTTP connector switch (getType()) { case 1: // Selecting NIO connector result = new SelectChannelConnector(); break; case 2: // Blocking NIO connector result = new BlockingChannelConnector(); break; case 3: // Blocking BIO connector result = new SocketConnector(); break; } return result; } /** * Returns the type of Jetty connector to use. * * @return The type of Jetty connector to use. */ public int getType() { return Integer.parseInt(getHelpedParameters() .getFirstValue("type", "1")); } } restlet-2.0.14/org.restlet.ext.xml/0000775000175000017500000000000012001473133017574 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/pom.xml0000600000175000017500000000134512001473133021102 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.xml Restlet Extension - XML Support for the XML documents. org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.xml/src/0000775000175000017500000000000012001473133020363 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/src/META-INF/0000775000175000017500000000000011757206452021542 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/src/META-INF/services/0000775000175000017500000000000011757206344023365 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.xml/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.xml/src/META-INF/services/org.restlet.engine.converter.ConverterHelpe0000664000175000017500000000004011757206344033750 0ustar jamespagejamespageorg.restlet.ext.xml.XmlConverterrestlet-2.0.14/org.restlet.ext.xml/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023173 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.xml/src/org/0000775000175000017500000000000011757206344021171 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/src/org/restlet/0000775000175000017500000000000011757206344022653 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/0000775000175000017500000000000011757206344023453 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/0000775000175000017500000000000011757206344024253 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/NodeSet.java0000664000175000017500000000444211757206344026463 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.util.AbstractList; import org.w3c.dom.Node; /** * DOM nodes set that implements the standard List interface for easier * iteration. * * @author Jerome Louvel * @deprecated Use {@link NodeList} instead. */ @Deprecated public class NodeSet extends AbstractList implements org.w3c.dom.NodeList { /** The wrapped node list. */ private volatile org.w3c.dom.NodeList nodes; /** * Constructor. * * @param nodes * The node list to wrap. */ public NodeSet(org.w3c.dom.NodeList nodes) { this.nodes = nodes; } @Override public Node get(int index) { return this.nodes.item(index); } /** * {@inheritDoc org.w3c.dom.NodeList#getLength()} */ public int getLength() { return this.nodes.getLength(); } /** * {@inheritDoc org.w3c.dom.NodeList#item(int)} */ public Node item(int index) { return this.nodes.item(index); } @Override public int size() { return this.nodes.getLength(); } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/internal/0000775000175000017500000000000011757206344026067 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/internal/ContextResolver.java0000664000175000017500000000671111757206344032105 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml.internal; import java.io.IOException; import java.util.logging.Level; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.data.Reference; /** * URI resolver based on a Restlet Context instance. * * @author Jerome Louvel */ public class ContextResolver implements URIResolver { /** The Restlet context. */ private final Context context; /** * Constructor. * * @param context * The Restlet context. */ public ContextResolver(Context context) { this.context = context; } /** * Resolves a target reference into a Source document. * * @see javax.xml.transform.URIResolver#resolve(java.lang.String, * java.lang.String) */ public Source resolve(String href, String base) throws TransformerException { Source result = null; if (this.context != null) { Reference targetRef = null; if ((base != null) && !base.equals("")) { // Potentially a relative reference Reference baseRef = new Reference(base); targetRef = new Reference(baseRef, href); } else { // No base, assume "href" is an absolute URI targetRef = new Reference(href); } String targetUri = targetRef.getTargetRef().toString(); Response response = this.context.getClientDispatcher().handle( new Request(Method.GET, targetUri)); if (response.getStatus().isSuccess() && response.isEntityAvailable()) { try { result = new StreamSource(response.getEntity().getStream()); result.setSystemId(targetUri); } catch (IOException e) { this.context.getLogger().log(Level.WARNING, "I/O error while getting the response stream", e); } } } return result; } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/internal/AbstractXmlReader.java0000664000175000017500000001357011757206344032307 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml.internal; import java.util.HashMap; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; /** * Abstract SAX XML Reader. * * @author Warren Janssens */ public abstract class AbstractXmlReader implements XMLReader { /** The features map. */ private final HashMap features; /** The properties map. */ private final HashMap properties; /** The entity resolver. */ private EntityResolver entityResolver; /** The DTD handler. */ private DTDHandler handler; /** The content handler. */ private ContentHandler contentHandler; /** The error handler. */ private ErrorHandler errorHandler; /** * Default constructor. */ public AbstractXmlReader() { this.features = new HashMap(); this.properties = new HashMap(); this.contentHandler = null; this.entityResolver = null; this.errorHandler = null; this.handler = null; } /** * Return the content handler. * * @return The content handler. * @see XMLReader#getContentHandler() */ public ContentHandler getContentHandler() { return contentHandler; } /** * Return the DTD handler. * * @return The DTD handler. * @see XMLReader#getDTDHandler() */ public DTDHandler getDTDHandler() { return handler; } /** * Return the entity resolver. * * @return The entity resolver. * @see XMLReader#getEntityResolver() */ public EntityResolver getEntityResolver() { return entityResolver; } /** * Return the error handler. * * @return The error handler. * @see XMLReader#getErrorHandler() */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * Returns the feature by name. * * @param name * The feature name. * @return The feature. * @see XMLReader#getFeature(String) */ public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { final Boolean result = features.get(name); return result == null ? false : result.booleanValue(); } /** * Returns the property by name. * * @param name * The property name. * @return The property. * @see XMLReader#getProperty(String) */ public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return properties.get(name); } /** * Sets the content handler. * * @param contentHandler * The content handler. * @see XMLReader#setContentHandler(ContentHandler) */ public void setContentHandler(ContentHandler contentHandler) { this.contentHandler = contentHandler; } /** * Sets the DTD handler. * * @param handler * The DTD handler. * @see XMLReader#setDTDHandler(DTDHandler) */ public void setDTDHandler(DTDHandler handler) { this.handler = handler; } /** * Sets the entity resolver. * * @param entityResolver * The entity resolver. * @see XMLReader#setEntityResolver(EntityResolver) */ public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } /** * Sets the error handler. * * @param errorHandler * The error handler. * @see XMLReader#setErrorHandler(ErrorHandler) */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Sets a feature. * * @param name * The feature name. * @param value * The feature value. * @see XMLReader#setFeature(String, boolean) */ public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { this.features.put(name, value); } /** * Sets a property. * * @param name * The property name. * @param value * The property value. * @see XMLReader#setProperty(String, Object) */ public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { this.properties.put(name, value); } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/SaxRepresentation.java0000664000175000017500000002373611757206344030607 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.io.IOException; import java.io.Writer; import javax.xml.XMLConstants; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Result; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXSource; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.w3c.dom.Document; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * XML representation for SAX events processing. The purpose is to create a * streamable content based on a custom Java object model instead of a neutral * DOM tree. This domain object can then be directly modified and efficiently * serialized at a later time.
    *
    * Subclasses only need to override the ContentHandler methods required for the * reading and also the write(XmlWriter writer) method when serialization is * requested. * * @author Jerome Louvel */ public class SaxRepresentation extends XmlRepresentation { /** Limits potential XML overflow attacks. */ private boolean secureProcessing; /** The SAX source. */ private volatile SAXSource source; /** The source XML representation. */ private volatile Representation xmlRepresentation; /** * Default constructor. Uses the {@link MediaType#TEXT_XML} media type. */ public SaxRepresentation() { this(MediaType.TEXT_XML); } /** * Constructor. * * @param mediaType * The representation media type. */ public SaxRepresentation(MediaType mediaType) { super(mediaType); this.secureProcessing = false; } /** * Constructor. * * @param mediaType * The representation's media type. * @param xmlDocument * A DOM document to parse. */ public SaxRepresentation(MediaType mediaType, Document xmlDocument) { super(mediaType); this.secureProcessing = false; this.source = new SAXSource( SAXSource.sourceToInputSource(new DOMSource(xmlDocument))); } /** * Constructor. * * @param mediaType * The representation's media type. * @param xmlSource * A SAX input source to parse. */ public SaxRepresentation(MediaType mediaType, InputSource xmlSource) { super(mediaType); this.secureProcessing = false; this.source = new SAXSource(xmlSource); } /** * Constructor. * * @param mediaType * The representation's media type. * @param xmlSource * A JAXP source to parse. */ public SaxRepresentation(MediaType mediaType, SAXSource xmlSource) { super(mediaType); this.secureProcessing = false; this.source = xmlSource; } /** * Constructor. * * @param xmlRepresentation * A source XML representation to parse. */ public SaxRepresentation(Representation xmlRepresentation) { super((xmlRepresentation == null) ? null : xmlRepresentation .getMediaType()); this.secureProcessing = false; this.xmlRepresentation = xmlRepresentation; } @Override public InputSource getInputSource() throws IOException { return (getSaxSource() == null) ? null : getSaxSource() .getInputSource(); } /** * Returns the SAX source that can be parsed by the * {@link #parse(ContentHandler)} method or used for an XSLT transformation. */ @Override public SAXSource getSaxSource() throws IOException { if (this.source == null && this.xmlRepresentation != null) { if (xmlRepresentation instanceof XmlRepresentation) { this.source = ((XmlRepresentation) xmlRepresentation) .getSaxSource(); } else { try { SAXParserFactory spf = SAXParserFactory.newInstance(); // Keep before the external entity preferences spf.setValidating(isValidatingDtd()); javax.xml.validation.Schema xsd = getSchema(); if (xsd != null) { spf.setSchema(xsd); } spf.setNamespaceAware(isNamespaceAware()); spf.setXIncludeAware(isXIncludeAware()); spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isSecureProcessing()); spf.setFeature( "http://xml.org/sax/features/external-general-entities", isExpandingEntityRefs()); spf.setFeature( "http://xml.org/sax/features/external-parameter-entities", isExpandingEntityRefs()); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); this.source = new SAXSource(xmlReader, new InputSource( xmlRepresentation.getReader())); } catch (Exception e) { throw new IOException( "Unable to create customized SAX source"); } } if (xmlRepresentation.getLocationRef() != null) { this.source.setSystemId(xmlRepresentation.getLocationRef() .getTargetRef().toString()); } } return this.source; } /** * Indicates if it limits potential XML overflow attacks. * * @return True if it limits potential XML overflow attacks. */ public boolean isSecureProcessing() { return secureProcessing; } /** * Parses the source and sends SAX events to a content handler. * * @param contentHandler * The SAX content handler to use for parsing. */ public void parse(ContentHandler contentHandler) throws IOException { if (contentHandler != null) { try { Result result = new SAXResult(contentHandler); TransformerFactory.newInstance().newTransformer() .transform(getSaxSource(), result); } catch (TransformerConfigurationException tce) { throw new IOException( "Couldn't parse the source representation: " + tce.getMessage()); } catch (TransformerException te) { te.printStackTrace(); throw new IOException( "Couldn't parse the source representation: " + te.getMessage()); } catch (TransformerFactoryConfigurationError tfce) { throw new IOException( "Couldn't parse the source representation: " + tfce.getMessage()); } } else { throw new IOException( "Couldn't parse the source representation: no content restlet defined."); } } /** * Releases the namespaces map. */ @Override public void release() { if (this.source != null) { this.source = null; } if (this.xmlRepresentation != null) { this.xmlRepresentation.release(); } super.release(); } /** * Sets a SAX source that can be parsed by the * {@link #parse(ContentHandler)} method. * * @param source * A SAX source. */ public void setSaxSource(SAXSource source) { this.source = source; } /** * Indicates if it limits potential XML overflow attacks. * * @param secureProcessing * True if it limits potential XML overflow attacks. */ public void setSecureProcessing(boolean secureProcessing) { this.secureProcessing = secureProcessing; } @Override public void write(Writer writer) throws IOException { XmlWriter xmlWriter = new XmlWriter(writer); write(xmlWriter); } /** * Writes the representation to a XML writer. The default implementation * calls {@link #parse(ContentHandler)} using the {@link XmlWriter} * parameter as the content handler. This behavior is intended to be * overridden. * * @param writer * The XML writer to write to. * @throws IOException */ public void write(XmlWriter writer) throws IOException { parse(writer); } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/XmlWriter.java0000664000175000017500000014447711757206344027074 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.Enumeration; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.NamespaceSupport; import org.xml.sax.helpers.XMLFilterImpl; /** * XML writer doing the opposite work of a SAX-based XML reader. The * implementation is based on the work of David Megginson, the creator of SAX * who placed the original code in the public domain. * *

    * This class can be used by itself or as part of a SAX event stream: it takes * as input a series of SAX2 ContentHandler events and uses the information in * those events to write an XML document. Since this class is a filter, it can * also pass the events on down a filter chain for further processing (you can * use the XmlWriter to take a snapshot of the current state at any point in a * filter chain), and it can be used directly as a ContentHandler for a SAX2 * XMLReader. *

    * *

    * The client creates a document by invoking the methods for standard SAX2 * events, always beginning with the {@link #startDocument startDocument} method * and ending with the {@link #endDocument endDocument} method. There are * convenience methods provided so that clients to not have to create empty * attribute lists or provide empty strings as parameters; for example, the * method invocation *

    * *
     * w.startElement("foo");
     * 
    * *

    * is equivalent to the regular SAX2 ContentHandler method *

    * *
     * w.startElement("", "foo", "", new AttributesImpl());
     * 
    * *

    * Except that it is more efficient because it does not allocate a new empty * attribute list each time. The following code will send a simple XML document * to standard output: *

    * *
     * XmlWriter w = new XmlWriter();
     * 
     * w.startDocument();
     * w.startElement("greeting");
     * w.characters("Hello, world!");
     * w.endElement("greeting");
     * w.endDocument();
     * 
    * *

    * The resulting document will look like this: *

    * *
     *           <?xml version="1.0" standalone='yes'?>
     *          
     *           <greeting>Hello, world!</greeting>
     * 
    * *

    * In fact, there is an even simpler convenience method, dataElement, * designed for writing elements that contain only character data, so the code * to generate the document could be shortened to *

    * *
     * XmlWriter w = new XmlWriter();
     * 
     * w.startDocument();
     * w.dataElement("greeting", "Hello, world!");
     * w.endDocument();
     * 
    * *

    Whitespace

    * *

    * According to the XML Recommendation, all whitespace in an XML * document is potentially significant to an application, so this class never * adds newlines or indentation. If you insert three elements in a row, as in *

    * *
     * w.dataElement("item", "1");
     * w.dataElement("item", "2");
     * w.dataElement("item", "3");
     * 
    * *

    * you will end up with *

    * *
     *           <item>1</item><item>3</item><item>3</item>
     * 
    * *

    * You need to invoke one of the characters methods explicitly to add * newlines or indentation. Alternatively, you can use the data format mode (set * the "dataFormat" property) which is optimized for writing purely * data-oriented (or field-oriented) XML, and does automatic linebreaks and * indentation (but does not support mixed content properly). See details below. *

    * *

    Namespace Support

    * *

    * The writer contains extensive support for XML Namespaces, so that a client * application does not have to keep track of prefixes and supply * xmlns attributes. By default, the XML writer will generate * Namespace declarations in the form _NS1, _NS2, etc., wherever they are * needed, as in the following example: *

    * *
     * w.startDocument();
     * w.emptyElement("http://www.foo.com/ns/", "foo");
     * w.endDocument();
     * 
    * *

    * The resulting document will look like this: *

    * *
     *           <?xml version="1.0" standalone='yes'?>
     *          
     *           <_NS1:foo xmlns:_NS1="http://www.foo.com/ns/"/>
     * 
    * *

    * In many cases, document authors will prefer to choose their own prefixes * rather than using the (ugly) default names. The XML writer allows two methods * for selecting prefixes: *

    * *
      *
    1. the qualified name
    2. *
    3. the {@link #setPrefix setPrefix} method.
    4. *
    * *

    * Whenever the XML writer finds a new Namespace URI, it checks to see if a * qualified (prefixed) name is also available; if so it attempts to use the * name's prefix (as long as the prefix is not already in use for another * Namespace URI). *

    * *

    * Before writing a document, the client can also pre-map a prefix to a * Namespace URI with the setPrefix method: *

    * *
     * w.setPrefix("http://www.foo.com/ns/", "foo");
     * w.startDocument();
     * w.emptyElement("http://www.foo.com/ns/", "foo");
     * w.endDocument();
     * 
    * *

    * The resulting document will look like this: *

    * *
     *           <?xml version="1.0" standalone='yes'?>
     *          
     *           <foo:foo xmlns:foo="http://www.foo.com/ns/"/>
     * 
    * *

    * The default Namespace simply uses an empty string as the prefix: *

    * *
     * w.setPrefix("http://www.foo.com/ns/", "");
     * w.startDocument();
     * w.emptyElement("http://www.foo.com/ns/", "foo");
     * w.endDocument();
     * 
    * *

    * The resulting document will look like this: *

    * *
     *           <?xml version="1.0" standalone='yes'?>
     *          
     *           <foo xmlns="http://www.foo.com/ns/"/>
     * 
    * *

    * By default, the XML writer will not declare a Namespace until it is actually * used. Sometimes, this approach will create a large number of Namespace * declarations, as in the following example: *

    * *
     *           <xml version="1.0" standalone='yes'?>
     *          
     *           <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
     *            <rdf:Description about="http://www.foo.com/ids/books/12345">
     *             <dc:title xmlns:dc="http://www.purl.org/dc/">A Dark Night</dc:title>
     *             <dc:creator xmlns:dc="http://www.purl.org/dc/">Jane Smith</dc:title>
     *             <dc:date xmlns:dc="http://www.purl.org/dc/">2000-09-09</dc:title>
     *            </rdf:Description>
     *           </rdf:RDF>
     * 
    * *

    * The "rdf" prefix is declared only once, because the RDF Namespace is used by * the root element and can be inherited by all of its descendants; the "dc" * prefix, on the other hand, is declared three times, because no higher element * uses the Namespace. To solve this problem, you can instruct the XML writer to * predeclare Namespaces on the root element even if they are not used there: *

    * *
     * w.forceNSDecl("http://www.purl.org/dc/");
     * 
    * *

    * Now, the "dc" prefix will be declared on the root element even though it's * not needed there, and can be inherited by its descendants: *

    * *
     *           <xml version="1.0" standalone='yes'?>
     *          
     *           <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     *                       xmlns:dc="http://www.purl.org/dc/">
     *            <rdf:Description about="http://www.foo.com/ids/books/12345">
     *             <dc:title>A Dark Night</dc:title>
     *             <dc:creator>Jane Smith</dc:title>
     *             <dc:date>2000-09-09</dc:title>
     *            </rdf:Description>
     *           </rdf:RDF>
     * 
    * *

    * This approach is also useful for declaring Namespace prefixes that be used by * qualified names appearing in attribute values or character data. *

    * *

    Data Format

    * *

    * This mode, enabled by the "dataFormat" property, pretty-prints field-oriented * XML without mixed content. All added indentation and newlines will be passed * on down the filter chain (if any). *

    * *

    * In general, all whitespace in an XML document is potentially significant, so * a general-purpose XML writing tool cannot add newlines or indentation. *

    * *

    * There is, however, a large class of XML documents where information is * strictly fielded: each element contains either character data or other * elements, but not both. For this special case, it is possible for a writing * tool to provide automatic indentation and newlines without requiring extra * work from the user. Note that this class will likely not yield appropriate * results for document-oriented XML like XHTML pages, which mix character data * and elements together. *

    * *

    * This writer mode will automatically place each start tag on a new line, * optionally indented if an indent step is provided (by default, there is no * indentation). If an element contains other elements, the end tag will also * appear on a new line with leading indentation. Consider, for example, the * following code: *

    * *
     * XmlWriter w = new XmlWriter();
     * w.setDataFormat(true);
     * w.setIndentStep(2);
     * w.startDocument();
     * w.startElement("Person");
     * w.dataElement("name", "Jane Smith");
     * w.dataElement("date-of-birth", "1965-05-23");
     * w.dataElement("citizenship", "US");
     * w.endElement("Person");
     * w.endDocument();
     * 
    * *

    * This code will produce the following document: *

    * *
     *           <?xml version="1.0" standalone='yes'?>
     *          
     *           <Person>
     *             <name>Jane Smith</name>
     *             <date-of-birth>1965-05-23</date-of-birth>
     *             <citizenship>US</citizenship>
     *           </Person>
     * 
    * * @see org.xml.sax.XMLFilter * @see org.xml.sax.ContentHandler * @author David Megginson, Jerome Louvel (contact@restlet.com) */ public final class XmlWriter extends XMLFilterImpl { private static final Object SEEN_NOTHING = new Object(); private static final Object SEEN_ELEMENT = new Object(); private static final Object SEEN_DATA = new Object(); /** * Constant representing empty attributes. */ private final Attributes EMPTY_ATTS = new AttributesImpl(); /** * The prefixes table. */ private volatile Map prefixTable; /** * The forced declarations table. */ private volatile Map forcedDeclTable; /** * The document declarations table. */ private volatile Map doneDeclTable; /** * The element level. */ private volatile int elementLevel = 0; /** * The namespace support. */ private volatile NamespaceSupport nsSupport; /** * The prefix counter. */ private volatile int prefixCounter = 0; /** * The underlying writer. */ private volatile Writer output; private volatile Object state = SEEN_NOTHING; private volatile Stack stateStack = new Stack(); private volatile boolean dataFormat = false; private volatile int indentStep = 0; private volatile int depth = 0; /** * Create a new XML writer. *

    * Write to standard output. *

    */ public XmlWriter() { init(null); } /** * Constructor. * * @param out * The underlying output stream. */ public XmlWriter(OutputStream out) { this(new OutputStreamWriter(out)); } /** * Constructor. * * @param out * The underlying output stream. */ public XmlWriter(OutputStream out, Charset cs) { this(new OutputStreamWriter(out, cs)); } /** * Constructor. * * @param out * The underlying output stream. */ public XmlWriter(OutputStream out, CharsetEncoder enc) { this(new OutputStreamWriter(out, enc)); } /** * Constructor. * * @param out * The underlying output stream. */ public XmlWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException { this(new OutputStreamWriter(out, charsetName)); } /** * Create a new XML writer. *

    * Write to the writer provided. *

    * * @param writer * The output destination, or null to use standard output. */ public XmlWriter(Writer writer) { init(writer); } /** * Create a new XML writer. *

    * Use the specified XML reader as the parent. *

    * * @param xmlreader * The parent in the filter chain, or null for no parent. */ public XmlWriter(XMLReader xmlreader) { super(xmlreader); init(null); } /** * Create a new XML writer. *

    * Use the specified XML reader as the parent, and write to the specified * writer. *

    * * @param xmlreader * The parent in the filter chain, or null for no parent. * @param writer * The output destination, or null to use standard output. */ public XmlWriter(XMLReader xmlreader, Writer writer) { super(xmlreader); init(writer); } /** * Write character data. Pass the event on down the filter chain for further * processing. * * @param ch * The array of characters to write. * @param start * The starting position in the array. * @param len * The number of characters to write. * @exception org.xml.sax.SAXException * If there is an error writing the characters, or if a * restlet further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#characters */ private void characters(boolean dataFormat, char ch[], int start, int len) throws SAXException { if (dataFormat) { this.state = SEEN_DATA; } writeEsc(ch, start, len, false); super.characters(ch, start, len); } // ////////////////////////////////////////////////////////////////// // Public methods. // ////////////////////////////////////////////////////////////////// /** * Write a string of character data, with XML escaping. *

    * This is a convenience method that takes an XML String, converts it to a * character array, then invokes {@link #characters(char[], int, int)}. *

    * * @param data * The character data. * @exception org.xml.sax.SAXException * If there is an error writing the string, or if a restlet * further down the filter chain raises an exception. * @see #characters(char[], int, int) */ private void characters(boolean dataFormat, String data) throws SAXException { final char ch[] = data.toCharArray(); characters(dataFormat, ch, 0, ch.length); } /** * Write character data. Pass the event on down the filter chain for further * processing. * * @param ch * The array of characters to write. * @param start * The starting position in the array. * @param len * The number of characters to write. * @exception org.xml.sax.SAXException * If there is an error writing the characters, or if a * restlet further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#characters */ @Override public void characters(char ch[], int start, int len) throws SAXException { characters(isDataFormat(), ch, start, len); } /** * Write a string of character data, with XML escaping. *

    * This is a convenience method that takes an XML String, converts it to a * character array, then invokes {@link #characters(char[], int, int)}. *

    * * @param data * The character data. * @exception org.xml.sax.SAXException * If there is an error writing the string, or if a restlet * further down the filter chain raises an exception. * @see #characters(char[], int, int) */ public void characters(String data) throws SAXException { characters(false, data); } /** * Write an element with character data content but no attributes or * Namespace URI. * *

    * This is a convenience method to write a complete element with character * data content, including the start tag and end tag. The method provides an * empty string for the Namespace URI, and empty string for the qualified * name, and an empty attribute list. *

    * *

    * This method invokes * {@link #startElement(String, String, String, Attributes)}, followed by * {@link #characters(String)}, followed by * {@link #endElement(String, String, String)}. *

    * * @param localName * The element's local name. * @param content * The character data content. * @exception org.xml.sax.SAXException * If there is an error writing the empty tag, or if a * restlet further down the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) * @see #characters(String) * @see #endElement(String, String, String) */ public void dataElement(String localName, String content) throws SAXException { dataElement("", localName, "", this.EMPTY_ATTS, content); } /** * Write an element with character data content but no attributes. * *

    * This is a convenience method to write a complete element with character * data content, including the start tag and end tag. This method provides * an empty string for the qname and an empty attribute list. *

    * *

    * This method invokes * {@link #startElement(String, String, String, Attributes)}, followed by * {@link #characters(String)}, followed by * {@link #endElement(String, String, String)}. *

    * * @param uri * The element's Namespace URI. * @param localName * The element's local name. * @param content * The character data content. * @exception org.xml.sax.SAXException * If there is an error writing the empty tag, or if a * restlet further down the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) * @see #characters(String) * @see #endElement(String, String, String) */ public void dataElement(String uri, String localName, String content) throws SAXException { dataElement(uri, localName, "", this.EMPTY_ATTS, content); } /** * Write an element with character data content. * *

    * This is a convenience method to write a complete element with character * data content, including the start tag and end tag. *

    * *

    * This method invokes * {@link #startElement(String, String, String, Attributes)}, followed by * {@link #characters(String)}, followed by * {@link #endElement(String, String, String)}. *

    * * @param uri * The element's Namespace URI. * @param localName * The element's local name. * @param qName * The element's default qualified name. * @param atts * The element's attributes. * @param content * The character data content. * @exception org.xml.sax.SAXException * If there is an error writing the empty tag, or if a * restlet further down the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) * @see #characters(String) * @see #endElement(String, String, String) */ public void dataElement(String uri, String localName, String qName, Attributes atts, String content) throws SAXException { startElement(uri, localName, qName, atts); characters(content); endElement(uri, localName, qName); } /** * Print indentation for the current level. * * @exception org.xml.sax.SAXException * If there is an error writing the indentation characters, * or if a filter further down the chain raises an exception. */ private void doIndent() throws SAXException { if ((this.indentStep > 0) && (this.depth > 0)) { final int n = this.indentStep * this.depth; final char ch[] = new char[n]; for (int i = 0; i < n; i++) { ch[i] = ' '; } characters(ch, 0, n); } } /** * Determine the prefix for an element or attribute name. TODO: this method * probably needs some cleanup. * * @param uri * The Namespace URI. * @param qName * The qualified name (optional); this will be used to indicate * the preferred prefix if none is currently bound. * @param isElement * true if this is an element name, false if it is an attribute * name (which cannot use the default Namespace). */ private String doPrefix(String uri, String qName, boolean isElement) { final String defaultNS = this.nsSupport.getURI(""); if ("".equals(uri) || uri == null) { if (isElement && (defaultNS != null)) { this.nsSupport.declarePrefix("", ""); } return null; } String prefix; if (isElement && (defaultNS != null) && uri.equals(defaultNS)) { prefix = ""; } else { prefix = this.nsSupport.getPrefix(uri); } if (prefix != null) { return prefix; } prefix = this.doneDeclTable.get(uri); if ((prefix != null) && (((!isElement || (defaultNS != null)) && "".equals(prefix)) || (this.nsSupport .getURI(prefix) != null))) { prefix = null; } if (prefix == null) { prefix = this.prefixTable.get(uri); if ((prefix != null) && (((!isElement || (defaultNS != null)) && "" .equals(prefix)) || (this.nsSupport.getURI(prefix) != null))) { prefix = null; } } if ((prefix == null) && (qName != null) && !"".equals(qName)) { final int i = qName.indexOf(':'); if (i == -1) { if (isElement && (defaultNS == null)) { prefix = ""; } } else { prefix = qName.substring(0, i); } } for (; (prefix == null) || (this.nsSupport.getURI(prefix) != null); prefix = "__NS" + ++this.prefixCounter) { // Do nothing } this.nsSupport.declarePrefix(prefix, uri); this.doneDeclTable.put(uri, prefix); return prefix; } // ////////////////////////////////////////////////////////////////// // Methods from org.xml.sax.ContentHandler. // ////////////////////////////////////////////////////////////////// /** * Add an empty element without a Namespace URI, qname or attributes. * *

    * This method will supply an empty string for the qname, and empty string * for the Namespace URI, and an empty attribute list. It invokes * {@link #emptyElement(String, String, String, Attributes)} directly. *

    * * @param localName * The element's local name. * @exception org.xml.sax.SAXException * If there is an error writing the empty tag, or if a * restlet further down the filter chain raises an exception. * @see #emptyElement(String, String, String, Attributes) */ public void emptyElement(String localName) throws SAXException { emptyElement("", localName, "", this.EMPTY_ATTS); } /** * Add an empty element without a qname or attributes. * *

    * This method will supply an empty string for the qname and an empty * attribute list. It invokes * {@link #emptyElement(String, String, String, Attributes)} directly. *

    * * @param uri * The element's Namespace URI. * @param localName * The element's local name. * @exception org.xml.sax.SAXException * If there is an error writing the empty tag, or if a * restlet further down the filter chain raises an exception. * @see #emptyElement(String, String, String, Attributes) */ public void emptyElement(String uri, String localName) throws SAXException { emptyElement(uri, localName, "", this.EMPTY_ATTS); } /** * Write an empty element. This method writes an empty element tag rather * than a start tag followed by an end tag. Both a {@link #startElement * startElement} and an {@link #endElement endElement} event will be passed * on down the filter chain. * * @param uri * The element's Namespace URI, or the empty string if the * element has no Namespace or if Namespace processing is not * being performed. * @param localName * The element's local name (without prefix). This parameter must * be provided. * @param qName * The element's qualified name (with prefix), or the empty * string if none is available. This parameter is strictly * advisory: the writer may or may not use the prefix attached. * @param atts * The element's attribute list. * @exception org.xml.sax.SAXException * If there is an error writing the empty tag, or if a * restlet further down the filter chain raises an exception. * @see #startElement * @see #endElement */ public void emptyElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (isDataFormat()) { this.state = SEEN_ELEMENT; if (this.depth > 0) { characters(false, "\n"); } doIndent(); } this.nsSupport.pushContext(); write('<'); writeName(uri, localName, qName, true); writeAttributes(atts); if (this.elementLevel == 1) { forceNSDecls(); } writeNSDecls(); write("/>"); super.startElement(uri, localName, qName, atts); super.endElement(uri, localName, qName); } /** * Write a newline at the end of the document. Pass the event on down the * filter chain for further processing. * * @exception org.xml.sax.SAXException * If there is an error writing the newline, or if a restlet * further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#endDocument */ @Override public void endDocument() throws SAXException { write('\n'); super.endDocument(); try { flush(); } catch (IOException e) { throw new SAXException(e); } } /** * End an element without a Namespace URI or qname. * *

    * This method will supply an empty string for the qName and an empty string * for the Namespace URI. It invokes * {@link #endElement(String, String, String)} directly. *

    * * @param localName * The element's local name. * @exception org.xml.sax.SAXException * If there is an error writing the end tag, or if a restlet * further down the filter chain raises an exception. * @see #endElement(String, String, String) */ public void endElement(String localName) throws SAXException { endElement("", localName, ""); } /** * End an element without a qname. * *

    * This method will supply an empty string for the qName. It invokes * {@link #endElement(String, String, String)} directly. *

    * * @param uri * The element's Namespace URI. * @param localName * The element's local name. * @exception org.xml.sax.SAXException * If there is an error writing the end tag, or if a restlet * further down the filter chain raises an exception. * @see #endElement(String, String, String) */ public void endElement(String uri, String localName) throws SAXException { endElement(uri, localName, ""); } /** * Write an end tag. Pass the event on down the filter chain for further * processing. * * @param uri * The Namespace URI, or the empty string if none is available. * @param localName * The element's local (unprefixed) name (required). * @param qName * The element's qualified (prefixed) name, or the empty string * is none is available. This method will use the qName as a * template for generating a prefix if necessary, but it is not * guaranteed to use the same qName. * @exception org.xml.sax.SAXException * If there is an error writing the end tag, or if a restlet * further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#endElement */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (isDataFormat()) { this.depth--; if (this.state == SEEN_ELEMENT) { characters(false, "\n"); doIndent(); } } write("'); if (this.elementLevel == 1) { write('\n'); } super.endElement(uri, localName, qName); this.nsSupport.popContext(); this.elementLevel--; if (isDataFormat()) { this.state = this.stateStack.pop(); } } /** * Flush the output. *

    * This method flushes the output stream. It is especially useful when you * need to make certain that the entire document has been written to output * but do not want to close the output stream. *

    *

    * This method is invoked automatically by the {@link #endDocument * endDocument} method after writing a document. *

    * * @see #reset */ public void flush() throws IOException { this.output.flush(); } // ////////////////////////////////////////////////////////////////// // Additional markup. // ////////////////////////////////////////////////////////////////// /** * Force a Namespace to be declared on the root element. *

    * By default, the XMLWriter will declare only the Namespaces needed for an * element; as a result, a Namespace may be declared many places in a * document if it is not used on the root element. *

    *

    * This method forces a Namespace to be declared on the root element even if * it is not used there, and reduces the number of xmlns attributes in the * document. *

    * * @param uri * The Namespace URI to declare. * @see #forceNSDecl(java.lang.String,java.lang.String) * @see #setPrefix */ public void forceNSDecl(String uri) { this.forcedDeclTable.put(uri, Boolean.TRUE); } // ////////////////////////////////////////////////////////////////// // Convenience methods. // ////////////////////////////////////////////////////////////////// /** * Force a Namespace declaration with a preferred prefix. *

    * This is a convenience method that invokes {@link #setPrefix setPrefix} * then {@link #forceNSDecl(java.lang.String) forceNSDecl}. *

    * * @param uri * The Namespace URI to declare on the root element. * @param prefix * The preferred prefix for the Namespace, or "" for the default * Namespace. * @see #setPrefix * @see #forceNSDecl(java.lang.String) */ public void forceNSDecl(String uri, String prefix) { setPrefix(uri, prefix); forceNSDecl(uri); } /** * Force all Namespaces to be declared. This method is used on the root * element to ensure that the predeclared Namespaces all appear. */ private void forceNSDecls() { for (final String prefix : this.forcedDeclTable.keySet()) { doPrefix(prefix, null, true); } } /** * Return the current indent step. *

    * Return the current indent step: each start tag will be indented by this * number of spaces times the number of ancestors that the element has. *

    * * @return The number of spaces in each indentation step, or 0 or less for * no indentation. */ public int getIndentStep() { return this.indentStep; } /** * Get the current or preferred prefix for a Namespace URI. * * @param uri * The Namespace URI. * @return The preferred prefix, or "" for the default Namespace. * @see #setPrefix */ public String getPrefix(String uri) { return this.prefixTable.get(uri); } /** * Returns the underlying writer. * * @return The underlying writer. */ public Writer getWriter() { return this.output; } /** * Write ignorable whitespace. Pass the event on down the filter chain for * further processing. * * @param ch * The array of characters to write. * @param start * The starting position in the array. * @param length * The number of characters to write. * @exception org.xml.sax.SAXException * If there is an error writing the whitespace, or if a * restlet further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#ignorableWhitespace */ @Override public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { writeEsc(ch, start, length, false); super.ignorableWhitespace(ch, start, length); } /** * Internal initialization method. * *

    * All of the public constructors invoke this method. * * @param writer * The output destination, or null to use standard output. */ private void init(Writer writer) { setOutput(writer); this.nsSupport = new NamespaceSupport(); this.prefixTable = new TreeMap(); this.forcedDeclTable = new TreeMap(); this.doneDeclTable = new TreeMap(); } public boolean isDataFormat() { return this.dataFormat; } /** * Write a processing instruction. Pass the event on down the filter chain * for further processing. * * @param target * The PI target. * @param data * The PI data. * @exception org.xml.sax.SAXException * If there is an error writing the PI, or if a restlet * further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#processingInstruction */ @Override public void processingInstruction(String target, String data) throws SAXException { write(""); if (this.elementLevel < 1) { write('\n'); } super.processingInstruction(target, data); } /** * Reset the writer. * *

    * This method is especially useful if the writer throws an exception before * it is finished, and you want to reuse the writer for a new document. It * is usually a good idea to invoke {@link #flush flush} before resetting * the writer, to make sure that no output is lost. *

    * *

    * This method is invoked automatically by the {@link #startDocument * startDocument} method before writing a new document. *

    * *

    * Note: this method will not clear the prefix or * URI information in the writer or the selected output writer. *

    * * @see #flush */ public void reset() { if (isDataFormat()) { this.depth = 0; this.state = SEEN_NOTHING; this.stateStack = new Stack(); } this.elementLevel = 0; this.prefixCounter = 0; this.nsSupport.reset(); } public void setDataFormat(boolean dataFormat) { this.dataFormat = dataFormat; } // ////////////////////////////////////////////////////////////////// // Internal methods. // ////////////////////////////////////////////////////////////////// /** * Set the current indent step. * * @param indentStep * The new indent step (0 or less for no indentation). */ public void setIndentStep(int indentStep) { this.indentStep = indentStep; } /** * Set a new output destination for the document. * * @param writer * The output destination, or null to use standard output. * @see #flush */ public void setOutput(Writer writer) { if (writer == null) { this.output = new OutputStreamWriter(System.out); } else { this.output = writer; } } /** * Specify a preferred prefix for a Namespace URI. *

    * Note that this method does not actually force the Namespace to be * declared; to do that, use the {@link #forceNSDecl(java.lang.String) * forceNSDecl} method as well. *

    * * @param uri * The Namespace URI. * @param prefix * The preferred prefix, or "" to select the default Namespace. * @see #getPrefix * @see #forceNSDecl(java.lang.String) * @see #forceNSDecl(java.lang.String,java.lang.String) */ public void setPrefix(String uri, String prefix) { this.prefixTable.put(uri, prefix); } /** * Write the XML declaration at the beginning of the document. Pass the * event on down the filter chain for further processing. * * @exception org.xml.sax.SAXException * If there is an error writing the XML declaration, or if a * restlet further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#startDocument */ @Override public void startDocument() throws SAXException { reset(); write("\n"); super.startDocument(); } /** * Start a new element without a qname, attributes or a Namespace URI. * *

    * This method will provide an empty string for the Namespace URI, and empty * string for the qualified name, and a default empty attribute list. It * invokes #startElement(String, String, String, Attributes)} directly. *

    * * @param localName * The element's local name. * @exception org.xml.sax.SAXException * If there is an error writing the start tag, or if a * restlet further down the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) */ public void startElement(String localName) throws SAXException { startElement("", localName, "", this.EMPTY_ATTS); } /** * Start a new element without a qname or attributes. * *

    * This method will provide a default empty attribute list and an empty * string for the qualified name. It invokes * {@link #startElement(String, String, String, Attributes)} directly. *

    * * @param uri * The element's Namespace URI. * @param localName * The element's local name. * @exception org.xml.sax.SAXException * If there is an error writing the start tag, or if a * restlet further down the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) */ public void startElement(String uri, String localName) throws SAXException { startElement(uri, localName, "", this.EMPTY_ATTS); } /** * Write a start tag. Pass the event on down the filter chain for further * processing. * * @param uri * The Namespace URI, or the empty string if none is available. * @param localName * The element's local (unprefixed) name (required). * @param qName * The element's qualified (prefixed) name, or the empty string * is none is available. This method will use the qName as a * template for generating a prefix if necessary, but it is not * guaranteed to use the same qName. * @param atts * The element's attribute list (must not be null). * @exception org.xml.sax.SAXException * If there is an error writing the start tag, or if a * restlet further down the filter chain raises an exception. * @see org.xml.sax.ContentHandler#startElement */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (isDataFormat()) { this.stateStack.push(SEEN_ELEMENT); this.state = SEEN_NOTHING; if (this.depth > 0) { characters("\n"); } doIndent(); } this.elementLevel++; this.nsSupport.pushContext(); write('<'); writeName(uri, localName, qName, true); writeAttributes(atts); if (this.elementLevel == 1) { forceNSDecls(); } writeNSDecls(); write('>'); super.startElement(uri, localName, qName, atts); if (isDataFormat()) { this.depth++; } } /** * Write a raw character. * * @param c * The character to write. * @exception org.xml.sax.SAXException * If there is an error writing the character, this method * will throw an IOException wrapped in a SAXException. */ private void write(char c) throws SAXException { try { this.output.write(c); } catch (IOException e) { throw new SAXException(e); } } /** * Write a raw string. * * @param s * @exception org.xml.sax.SAXException * If there is an error writing the string, this method will * throw an IOException wrapped in a SAXException */ private void write(String s) throws SAXException { try { this.output.write(s); } catch (IOException e) { throw new SAXException(e); } } /** * Write out an attribute list, escaping values. The names will have * prefixes added to them. * * @param atts * The attribute list to write. * @exception org.xml.SAXException * If there is an error writing the attribute list, this * method will throw an IOException wrapped in a * SAXException. */ private void writeAttributes(Attributes atts) throws SAXException { final int len = atts.getLength(); for (int i = 0; i < len; i++) { if ("xmlns".equals(atts.getQName(i))) { // Redefines the default namespace. forceNSDecl(atts.getValue(i)); } else if (atts.getQName(i) != null && atts.getQName(i).startsWith("xmlns")) { // Defines the namespace using its prefix. forceNSDecl(atts.getValue(i), atts.getLocalName(i)); } else { final char ch[] = atts.getValue(i).toCharArray(); write(' '); writeName(atts.getURI(i), atts.getLocalName(i), atts.getQName(i), false); write("=\""); writeEsc(ch, 0, ch.length, true); write('"'); } } } /** * Write an array of data characters with escaping. * * @param ch * The array of characters. * @param start * The starting position. * @param length * The number of characters to use. * @param isAttVal * true if this is an attribute value literal. * @exception org.xml.SAXException * If there is an error writing the characters, this method * will throw an IOException wrapped in a SAXException. */ private void writeEsc(char ch[], int start, int length, boolean isAttVal) throws SAXException { for (int i = start; i < start + length; i++) { switch (ch[i]) { case '&': write("&"); break; case '<': write("<"); break; case '>': write(">"); break; case '\"': if (isAttVal) { write("""); } else { write('\"'); } break; default: if (ch[i] > '\u007f') { write("&#"); write(Integer.toString(ch[i])); write(';'); } else { write(ch[i]); } } } } /** * Write an element or attribute name. * * @param uri * The Namespace URI. * @param localName * The local name. * @param qName * The prefixed name, if available, or the empty string. * @param isElement * true if this is an element name, false if it is an attribute * name. * @exception org.xml.sax.SAXException * This method will throw an IOException wrapped in a * SAXException if there is an error writing the name. */ private void writeName(String uri, String localName, String qName, boolean isElement) throws SAXException { final String prefix = doPrefix(uri, qName, isElement); if ((prefix != null) && !"".equals(prefix)) { write(prefix); write(':'); } write(localName); } /** * Write out the list of Namespace declarations. * * @exception org.xml.sax.SAXException * This method will throw an IOException wrapped in a * SAXException if there is an error writing the Namespace * declarations. */ @SuppressWarnings("unchecked") private void writeNSDecls() throws SAXException { final Enumeration prefixes = this.nsSupport .getDeclaredPrefixes(); while (prefixes.hasMoreElements()) { final String prefix = prefixes.nextElement(); String uri = this.nsSupport.getURI(prefix); if (uri == null) { uri = ""; } final char ch[] = uri.toCharArray(); write(' '); if ("".equals(prefix)) { write("xmlns=\""); } else { write("xmlns:"); write(prefix); write("=\""); } writeEsc(ch, 0, ch.length, true); write('\"'); } } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/XmlConverter.java0000664000175000017500000001462211757206344027553 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.io.IOException; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; import org.w3c.dom.Document; /** * Converter between the XML APIs and XML Representation classes. * * @author Jerome Louvel */ public class XmlConverter extends ConverterHelper { private static final VariantInfo VARIANT_APPLICATION_ALL_XML = new VariantInfo( MediaType.APPLICATION_ALL_XML); private static final VariantInfo VARIANT_APPLICATION_XML = new VariantInfo( MediaType.APPLICATION_XML); private static final VariantInfo VARIANT_TEXT_XML = new VariantInfo( MediaType.TEXT_XML); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_APPLICATION_ALL_XML.isCompatible(source) || VARIANT_APPLICATION_XML.isCompatible(source) || VARIANT_TEXT_XML.isCompatible(source)) { result = addObjectClass(result, Document.class); result = addObjectClass(result, DomRepresentation.class); result = addObjectClass(result, SaxRepresentation.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (Document.class.isAssignableFrom(source) || DomRepresentation.class.isAssignableFrom(source) || SaxRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_APPLICATION_ALL_XML); result = addVariant(result, VARIANT_APPLICATION_XML); result = addVariant(result, VARIANT_TEXT_XML); } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source instanceof Document) { if (target == null) { result = 0.5F; } else if (MediaType.APPLICATION_ALL_XML.isCompatible(target .getMediaType())) { result = 0.8F; } else if (MediaType.APPLICATION_XML.isCompatible(target .getMediaType())) { result = 0.9F; } else if (MediaType.TEXT_XML.isCompatible(target.getMediaType())) { result = 0.9F; } else { result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if ((target != null) && (Document.class.isAssignableFrom(target) || DomRepresentation.class.isAssignableFrom(target) || SaxRepresentation.class .isAssignableFrom(target))) { if (MediaType.APPLICATION_ALL_XML.isCompatible(source .getMediaType())) { result = 0.8F; } else if (MediaType.APPLICATION_XML.isCompatible(source .getMediaType())) { result = 0.9F; } else if (MediaType.TEXT_XML.isCompatible(source.getMediaType())) { result = 0.9F; } else { result = 0.5F; } } return result; } @SuppressWarnings("unchecked") @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (Document.class.isAssignableFrom(target)) { result = new DomRepresentation(source).getDocument(); } else if (DomRepresentation.class.isAssignableFrom(target)) { result = new DomRepresentation(source); } else if (SaxRepresentation.class.isAssignableFrom(target)) { result = new SaxRepresentation(source); } return (T) result; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { Representation result = null; if (source instanceof Document) { result = new DomRepresentation(target.getMediaType(), (Document) source); } else if (source instanceof Representation) { result = (Representation) source; } return result; } @Override public void updatePreferences(List> preferences, Class entity) { if (Document.class.isAssignableFrom(entity) || DomRepresentation.class.isAssignableFrom(entity) || SaxRepresentation.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_ALL_XML, 0.8F); updatePreferences(preferences, MediaType.APPLICATION_XML, 0.9F); updatePreferences(preferences, MediaType.TEXT_XML, 0.9F); } } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/DomRepresentation.java0000664000175000017500000002322611757206344030565 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.engine.Edition; import org.restlet.representation.Representation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * XML representation based on a DOM document. DOM is a standard XML object * model defined by the W3C. * * @author Jerome Louvel */ public class DomRepresentation extends XmlRepresentation { /** The wrapped DOM document. */ private volatile Document document; /** Indicates if the XML serialization should be indented. */ private volatile boolean indenting; /** The source XML representation. */ private volatile Representation xmlRepresentation; /** * Default constructor. Uses the {@link MediaType#TEXT_XML} media type. */ public DomRepresentation() throws IOException { this(MediaType.TEXT_XML); } /** * Constructor for an empty document. * * @param mediaType * The representation's media type. */ public DomRepresentation(MediaType mediaType) throws IOException { super(mediaType); this.document = getDocumentBuilder().newDocument(); } /** * Constructor from an existing DOM document. * * @param mediaType * The representation's media type. * @param xmlDocument * The source DOM document. */ public DomRepresentation(MediaType mediaType, Document xmlDocument) { super(mediaType); this.document = xmlDocument; } /** * Constructor. * * @param xmlRepresentation * A source XML representation to parse. */ public DomRepresentation(Representation xmlRepresentation) { super((xmlRepresentation == null) ? null : xmlRepresentation .getMediaType()); this.setAvailable(xmlRepresentation.isAvailable()); this.xmlRepresentation = xmlRepresentation; } /** * Creates a new JAXP Transformer object that will be used to serialize this * DOM. This method may be overridden in order to set custom properties on * the Transformer. * * @return The transformer to be used for serialization. */ protected javax.xml.transform.Transformer createTransformer() throws IOException { try { javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory .newInstance().newTransformer(); transformer.setOutputProperty( javax.xml.transform.OutputKeys.METHOD, "xml"); transformer.setOutputProperty( javax.xml.transform.OutputKeys.INDENT, isIndenting() ? "yes" : "no"); if (getCharacterSet() != null) { transformer.setOutputProperty( javax.xml.transform.OutputKeys.ENCODING, getCharacterSet().getName()); } else { transformer.setOutputProperty( javax.xml.transform.OutputKeys.ENCODING, CharacterSet.ISO_8859_1.getName()); } DocumentType docType = getDocument().getDoctype(); if (docType != null) { if (docType.getSystemId() != null) { transformer.setOutputProperty( javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM, getDocument().getDoctype().getSystemId()); } if (docType.getPublicId() != null) { transformer.setOutputProperty( javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC, getDocument().getDoctype().getPublicId()); } } return transformer; } catch (javax.xml.transform.TransformerConfigurationException tce) { throw new IOException("Couldn't write the XML representation: " + tce.getMessage()); } } /** * Returns the wrapped DOM document. If no document is defined yet, it * attempts to parse the XML representation eventually given at construction * time. Otherwise, it just creates a new document. * * @return The wrapped DOM document. */ @Override public Document getDocument() throws IOException { if (this.document == null) { if (this.xmlRepresentation != null) { try { this.document = getDocumentBuilder() .parse(getInputSource()); } catch (SAXException se) { throw new IOException( "Couldn't read the XML representation. " + se.getMessage()); } } else { this.document = getDocumentBuilder().newDocument(); } } return this.document; } /** * Returns a DOM source. * * @return A DOM source. */ @Override public javax.xml.transform.dom.DOMSource getDomSource() throws IOException { return new javax.xml.transform.dom.DOMSource(getDocument()); } @Override public InputSource getInputSource() throws IOException { if (this.xmlRepresentation.isAvailable()) { return new InputSource(this.xmlRepresentation.getStream()); } return new InputSource((InputStream) null); } /** * Indicates if the XML serialization should be indented. False by default. * * @return True if the XML serialization should be indented. * @deprecated Use {@link #isIndenting()} instead. */ @Deprecated public boolean isIndent() { return indenting; } /** * Indicates if the XML serialization should be indented. False by default. * * @return True if the XML serialization should be indented. */ public boolean isIndenting() { return isIndent(); } /** * Releases the wrapped DOM document and the source XML representation if * they have been defined. */ @Override public void release() { setDocument(null); if (this.xmlRepresentation != null) { this.xmlRepresentation.release(); } super.release(); } /** * Sets the wrapped DOM document. * * @param dom * The wrapped DOM document. */ public void setDocument(Document dom) { this.document = dom; } /** * Indicates if the XML serialization should be indented. * * @param indenting * True if the XML serialization should be indented. * @deprecated Use {@link #setIndenting(boolean)} instead. */ @Deprecated public void setIndent(boolean indenting) { this.indenting = indenting; } /** * Indicates if the XML serialization should be indented. * * @param indenting * True if the XML serialization should be indented. */ public void setIndenting(boolean indenting) { setIndent(indenting); } @Override public void write(Writer writer) throws IOException { if (Edition.CURRENT == Edition.ANDROID) { throw new UnsupportedOperationException( "Instances of DomRepresentation cannot be written at this time."); } try { if (getDocument() != null) { final javax.xml.transform.Transformer transformer = createTransformer(); transformer.transform(new javax.xml.transform.dom.DOMSource( getDocument()), new javax.xml.transform.stream.StreamResult(writer)); } } catch (javax.xml.transform.TransformerConfigurationException tce) { throw new IOException("Couldn't write the XML representation: " + tce.getMessage()); } catch (javax.xml.transform.TransformerException te) { throw new IOException("Couldn't write the XML representation: " + te.getMessage()); } catch (javax.xml.transform.TransformerFactoryConfigurationError tfce) { throw new IOException("Couldn't write the XML representation: " + tfce.getMessage()); } } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/package.html0000664000175000017500000000014111757206344026530 0ustar jamespagejamespage Support for XML and XSLT representations. @since Restlet 2.0 restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/TransformRepresentation.java0000664000175000017500000004533011757206344032021 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.URIResolver; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.restlet.Context; import org.restlet.ext.xml.internal.AbstractXmlReader; import org.restlet.ext.xml.internal.ContextResolver; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; /** * Representation able to apply an XSLT transformation. The internal JAXP * transformer is created when the getTransformer() method is first called. So, * if you need to specify a custom URI resolver, do it before actually using the * representation for a transformation.
    *
    * This representation should be viewed as a wrapper representation that applies * a transform sheet on a source representation when it is read or written out. * Therefore, it isn't intended to be reused on different sources. For this use * case, you should instead use the {@link org.restlet.routing.Transformer} * filter. * * @author Jerome Louvel */ public class TransformRepresentation extends WriterRepresentation { /** * Wraps a source representation into a {@link SAXSource}. This method can * detect other {@link XmlRepresentation} instances to use their * {@link XmlRepresentation#getSaxSource()} method as well as other * {@link TransformRepresentation} instances to support transformation * chaining. * * @param representation * The source representation. * @return The SAX source. * @throws IOException */ public static SAXSource toSaxSource(Representation representation) throws IOException { SAXSource result = null; if (representation instanceof XmlRepresentation) { result = ((XmlRepresentation) representation).getSaxSource(); } else if (representation instanceof TransformRepresentation) { final TransformRepresentation source = (TransformRepresentation) representation; XMLReader reader = new AbstractXmlReader() { /** * Parses the input source by sending the result event to the * XML reader's content handler. * * @param input * The input source. */ public void parse(InputSource input) throws IOException, SAXException { try { source.getTransformer().transform( source.getSaxSource(), new SAXResult(getContentHandler())); } catch (TransformerException te) { throw new IOException("Transformer exception. " + te.getMessage()); } } public void parse(String systemId) throws IOException, SAXException { throw new IllegalStateException("Not implemented"); } }; result = new SAXSource(reader, null); } else { // Prepare the source and result documents result = new SAXSource(new InputSource(representation.getStream())); } // Copy the representation's URI as an XML system ID. if (representation.getLocationRef() != null) { result.setSystemId(representation.getLocationRef().getTargetRef() .toString()); } return result; } /** The JAXP transformer output properties. */ private volatile Map outputProperties; /** The JAXP transformer parameters. */ private volatile Map parameters; /** The source representation to transform. */ private volatile Representation sourceRepresentation; /** The template to be used and reused. */ private volatile Templates templates; /** The XSLT transform sheet to apply to message entities. */ private volatile Representation transformSheet; /** The URI resolver. */ private volatile URIResolver uriResolver; /** * Constructor. Note that a default URI resolver will be created based on * the given context. * * @param context * The parent context. * @param source * The source representation to transform. * @param transformSheet * The XSLT transform sheet to apply. */ public TransformRepresentation(Context context, Representation source, Representation transformSheet) { this((context == null) ? null : new ContextResolver(context), source, transformSheet); } /** * Default constructor. * * @param source * The source representation to transform. * @param transformSheet * The XSLT transform sheet to apply. */ public TransformRepresentation(Representation source, Representation transformSheet) { this((URIResolver) null, source, transformSheet); } /** * Constructor. Note that a default URI resolver will be created based on * the given context. * * @param uriResolver * The JAXP URI resolver. * @param source * The source representation to transform. * @param transformSheet * The XSLT transform sheet to apply. */ public TransformRepresentation(URIResolver uriResolver, Representation source, Representation transformSheet) { this(uriResolver, source, transformSheet, null); } /** * Constructor. * * @param uriResolver * The optional JAXP URI resolver. * @param source * The source representation to transform. * @param templates * The precompiled JAXP template. */ private TransformRepresentation(URIResolver uriResolver, Representation source, Representation transformSheet, Templates templates) { super(null); this.sourceRepresentation = source; this.templates = templates; this.transformSheet = transformSheet; this.uriResolver = uriResolver; this.parameters = new HashMap(); this.outputProperties = new HashMap(); } /** * Constructor. * * @param uriResolver * The optional JAXP URI resolver. * @param source * The source representation to transform. * @param templates * The precompiled JAXP template. */ public TransformRepresentation(URIResolver uriResolver, Representation source, Templates templates) { this(uriResolver, source, null, templates); } /** * Returns the modifiable map of JAXP transformer output properties. * * @return The JAXP transformer output properties. */ public Map getOutputProperties() { return this.outputProperties; } /** * Returns the modifiable map of JAXP transformer parameters. * * @return The JAXP transformer parameters. */ public Map getParameters() { return this.parameters; } /** * Returns the SAX source associated to the source representation. * * @return The SAX source associated to the source representation. * @throws IOException */ public SAXSource getSaxSource() throws IOException { return toSaxSource(getSourceRepresentation()); } /** * Returns the default SAX transformer factory. * * @return The default SAX transformer factory. */ private SAXTransformerFactory getSaxTransformerFactory() { SAXTransformerFactory result = (SAXTransformerFactory) TransformerFactory .newInstance(); return result; } /** * Returns the source representation to transform. * * @return The source representation to transform. */ public Representation getSourceRepresentation() { return this.sourceRepresentation; } /** * Returns the templates to be used and reused. If no one exists, it creates * a new one based on the transformSheet representation and on the URI * resolver. * * @return The templates to be used and reused. */ public Templates getTemplates() throws IOException { if (this.templates == null) { if (getTransformSheet() != null) { try { // Prepare the XSLT transformer documents final StreamSource transformSource = new StreamSource( getTransformSheet().getStream()); if (getTransformSheet().getLocationRef() != null) { transformSource.setSystemId(getTransformSheet() .getLocationRef().getTargetRef().toString()); } // Create the transformer factory final TransformerFactory transformerFactory = TransformerFactory .newInstance(); // Set the URI resolver if (getUriResolver() != null) { transformerFactory.setURIResolver(getUriResolver()); } // Create a new transformer this.templates = transformerFactory .newTemplates(transformSource); } catch (TransformerConfigurationException tce) { throw new IOException( "Transformer configuration exception. " + tce.getMessage()); } } } return this.templates; } /** * Returns a new transformer to be used. Creation is based on the * {@link #getTemplates()}.newTransformer() method. * * @return The new transformer to be used. */ public Transformer getTransformer() throws IOException { Transformer result = null; try { Templates templates = getTemplates(); if (templates != null) { result = templates.newTransformer(); if (this.uriResolver != null) { result.setURIResolver(getUriResolver()); } // Set the parameters for (final String name : getParameters().keySet()) { result.setParameter(name, getParameters().get(name)); } // Set the output properties for (String name : getOutputProperties().keySet()) { result.setOutputProperty(name, getOutputProperties().get( name)); } } } catch (TransformerConfigurationException tce) { throw new IOException("Transformer configuration exception. " + tce.getMessage()); } catch (TransformerFactoryConfigurationError tfce) { throw new IOException( "Transformer factory configuration exception. " + tfce.getMessage()); } return result; } /** * Returns the SAX transformer handler associated to the transform sheet. * * @return The SAX transformer handler. * @throws IOException */ public TransformerHandler getTransformerHandler() throws IOException { TransformerHandler result = null; Templates templates = getTemplates(); if (templates != null) { try { result = getSaxTransformerFactory().newTransformerHandler( templates); } catch (TransformerConfigurationException tce) { throw new IOException("Transformer configuration exception. " + tce.getMessage()); } } return result; } /** * Returns the XSLT transform sheet to apply to the source representation. * * @return The XSLT transform sheet to apply. */ public Representation getTransformSheet() { return this.transformSheet; } /** * Returns the URI resolver. * * @return The URI resolver. */ public URIResolver getUriResolver() { return this.uriResolver; } /** * Returns the SAX XML filter applying the transform sheet to its input. * * @return The SAX XML filter. * @throws IOException */ public XMLFilter getXmlFilter() throws IOException { XMLFilter result = null; final Templates templates = getTemplates(); if (templates != null) { try { result = getSaxTransformerFactory().newXMLFilter(templates); } catch (TransformerConfigurationException tce) { throw new IOException("Transformer configuration exception. " + tce.getMessage()); } } return result; } /** * Releases the source and transform sheet representations, the transformer * and the URI resolver. */ @Override public void release() { if (this.sourceRepresentation != null) { this.sourceRepresentation.release(); this.sourceRepresentation = null; } if (this.templates != null) { this.templates = null; } if (this.transformSheet != null) { this.transformSheet.release(); this.transformSheet = null; } if (this.uriResolver != null) { this.uriResolver = null; } super.release(); } /** * Sets the modifiable map of JAXP transformer output properties. * * @param outputProperties * The JAXP transformer output properties. */ public void setOutputProperties(Map outputProperties) { this.outputProperties = outputProperties; } /** * Sets the JAXP transformer parameters. * * @param parameters * The JAXP transformer parameters. */ public void setParameters(Map parameters) { this.parameters = parameters; } /** * Sets the source representation to transform. * * @param source * The source representation to transform. */ public void setSourceRepresentation(Representation source) { this.sourceRepresentation = source; } /** * Sets the templates to be used and reused. * * @param templates * The templates to be used and reused. */ public void setTemplates(Templates templates) { this.templates = templates; } /** * Sets the XSLT transform sheet to apply to message entities. * * @param transformSheet * The XSLT transform sheet to apply to message entities. */ public void setTransformSheet(Representation transformSheet) { this.transformSheet = transformSheet; } /** * Sets the URI resolver. * * @param uriResolver * The URI resolver. */ public void setUriResolver(URIResolver uriResolver) { this.uriResolver = uriResolver; } /** * Transforms the given JAXP source into the given result. * * @param source * The JAXP source object. * @param result * The JAXP result object. * @throws IOException */ public void transform(Source source, Result result) throws IOException { if (getTransformer() == null) { Context .getCurrentLogger() .warning( "Unable to apply the transformation. No transformer found!"); } else { try { // Generates the result of the transformation getTransformer().transform(source, result); } catch (TransformerException te) { throw new IOException("Transformer exception. " + te.getMessage()); } } } /** * Writes the transformed source into the given output stream. By default, * it leverages the {@link #write(Result)} method using a * {@link StreamResult} object. */ @Override public void write(Writer writer) throws IOException { write(new StreamResult(writer)); } /** * Writes the transformed source into the given JAXP result. The source is * retrieved using the {@link #getSaxSource()} method. * * @param result * The JAXP result object. * @throws IOException */ public void write(Result result) throws IOException { transform(getSaxSource(), result); } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/XmlRepresentation.java0000664000175000017500000006464711757206344030622 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Representation based on an XML document. It knows how to evaluate XPath * expressions and how to manage a namespace context. This class also offers * convenient methods to validate the document against a specified XML scheme. * * @author Jerome Louvel */ public abstract class XmlRepresentation extends WriterRepresentation implements javax.xml.namespace.NamespaceContext { /** * Returns a SAX source. * * @param xmlRepresentation * The XML representation to wrap. * @return A SAX source. * @throws IOException */ public static javax.xml.transform.sax.SAXSource getSaxSource( Representation xmlRepresentation) throws IOException { javax.xml.transform.sax.SAXSource result = null; if (xmlRepresentation != null) { result = new javax.xml.transform.sax.SAXSource(new InputSource( xmlRepresentation.getStream())); if (xmlRepresentation.getLocationRef() != null) { result.setSystemId(xmlRepresentation.getLocationRef() .getTargetRef().toString()); } } return result; } /** * Returns the wrapped schema. * * @return The wrapped schema. * @throws IOException */ private static javax.xml.validation.Schema getSchema( Representation schemaRepresentation) throws Exception { javax.xml.validation.Schema result = null; if (schemaRepresentation != null) { final javax.xml.transform.stream.StreamSource streamSource = new javax.xml.transform.stream.StreamSource( schemaRepresentation.getStream()); result = javax.xml.validation.SchemaFactory.newInstance( getSchemaLanguageUri(schemaRepresentation)).newSchema( streamSource); } return result; } /** * Returns the schema URI for the current schema media type. * * @return The schema URI. */ private static String getSchemaLanguageUri( Representation schemaRepresentation) { String result = null; if (schemaRepresentation != null) { if (MediaType.APPLICATION_W3C_SCHEMA.equals(schemaRepresentation .getMediaType())) { result = XMLConstants.W3C_XML_SCHEMA_NS_URI; } else if (MediaType.APPLICATION_RELAXNG_COMPACT .equals(schemaRepresentation.getMediaType())) { result = XMLConstants.RELAXNG_NS_URI; } else if (MediaType.APPLICATION_RELAXNG_XML .equals(schemaRepresentation.getMediaType())) { result = XMLConstants.RELAXNG_NS_URI; } } return result; } /** * A SAX {@link EntityResolver} to use when resolving external entity * references while parsing this type of XML representations. * * @see DocumentBuilder#setEntityResolver(EntityResolver) */ private volatile EntityResolver entityResolver; /** * A SAX {@link ErrorHandler} to use for signaling SAX exceptions while * parsing this type of XML representations. * * @see DocumentBuilder#setErrorHandler(ErrorHandler) */ private volatile ErrorHandler errorHandler; /** Indicates if processing is namespace aware. */ private volatile boolean namespaceAware; /** Internal map of namespaces. */ private volatile Map namespaces; /** * A (compiled) {@link javax.xml.validation.Schema} to use when validating * this type of XML representations. * * @see DocumentBuilderFactory#setSchema(javax.xml.validation.Schema) */ private volatile javax.xml.validation.Schema schema; /** * Indicates the desire for validating this type of XML representations * against a DTD. Note that for XML schema or Relax NG validation, use the * "schema" property instead. * * @see DocumentBuilderFactory#setValidating(boolean) */ private volatile boolean validatingDtd; /** * Specifies that the parser will convert CDATA nodes to text nodes and * append it to the adjacent (if any) text node. By default the value of * this is set to false. */ private volatile boolean coalescing; /** * Specifies that the parser will expand entity reference nodes. By default * the value of this is set to true. */ private volatile boolean expandingEntityRefs; /** * Indicates if the parser will ignore comments. By default the value of * this is set to false. */ private volatile boolean ignoringComments; /** * Indicates if the parser will ignore extra white spaces in element * content. By default the value of this is set to false. */ private volatile boolean ignoringExtraWhitespaces; /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @see DocumentBuilderFactory#setXIncludeAware(boolean) */ private volatile boolean xIncludeAware; /** * Constructor. * * @param mediaType * The representation's mediaType. */ public XmlRepresentation(MediaType mediaType) { this(mediaType, UNKNOWN_SIZE); } /** * Constructor. * * @param mediaType * The representation's mediaType. * @param expectedSize * The expected input stream size. */ public XmlRepresentation(MediaType mediaType, long expectedSize) { super(mediaType, expectedSize); this.coalescing = false; this.entityResolver = null; this.errorHandler = null; this.expandingEntityRefs = false; this.ignoringComments = false; this.ignoringExtraWhitespaces = false; this.namespaceAware = false; this.namespaces = null; this.validatingDtd = false; this.xIncludeAware = false; this.schema = null; } /** * Evaluates an XPath expression and returns the result as in the given * return type. * * @param returnType * The qualified name of the return type. * @return The evaluation result. * @see javax.xml.xpath.XPathException * @see javax.xml.xpath.XPathConstants * @deprecated Use the {@link #getBoolean(String)}, * {@link #getNumber(String)}, {@link #getText(String)}, * {@link #getNode(String)} and {@link #getNodes(String)} * methods instead. */ @Deprecated public Object evaluate(String expression, javax.xml.namespace.QName returnType) throws Exception { Object result = null; XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(this); Document xmlDocument = getDocument(); if (xmlDocument != null) { result = xpath.evaluate(expression, xmlDocument, returnType); } else { throw new Exception( "Unable to obtain a DOM document for the XML representation. " + "XPath evaluation cancelled."); } return result; } /** * Evaluates an XPath expression as a boolean. If the evaluation fails, null * will be returned. * * @return The evaluation result. */ public Boolean getBoolean(String expression) { return (Boolean) internalEval(expression, javax.xml.xpath.XPathConstants.BOOLEAN); } /** * Returns the XML representation as a DOM document. * * @return The DOM document. */ protected Document getDocument() throws Exception { return getDocumentBuilder().parse(getInputSource()); } /** * Returns a document builder properly configured. * * @return A document builder properly configured. */ protected DocumentBuilder getDocumentBuilder() throws IOException { DocumentBuilder result = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(isNamespaceAware()); dbf.setValidating(isValidatingDtd()); dbf.setCoalescing(isCoalescing()); dbf.setExpandEntityReferences(isExpandingEntityRefs()); dbf.setIgnoringComments(isIgnoringComments()); dbf .setIgnoringElementContentWhitespace(isIgnoringExtraWhitespaces()); try { dbf.setXIncludeAware(isXIncludeAware()); } catch (UnsupportedOperationException uoe) { Context.getCurrentLogger().log(Level.FINE, "The JAXP parser doesn't support XInclude.", uoe); } javax.xml.validation.Schema xsd = getSchema(); if (xsd != null) { dbf.setSchema(xsd); } result = dbf.newDocumentBuilder(); result.setEntityResolver(getEntityResolver()); result.setErrorHandler(getErrorHandler()); } catch (ParserConfigurationException pce) { throw new IOException("Couldn't create the empty document: " + pce.getMessage()); } return result; } /** * Returns a DOM source. * * @return A DOM source. * @throws IOException */ public javax.xml.transform.dom.DOMSource getDomSource() throws IOException { javax.xml.transform.dom.DOMSource result = null; Node document = null; try { document = getDocumentBuilder().parse(getInputSource()); } catch (SAXException se) { throw new IOException("Couldn't read the XML representation. " + se.getMessage()); } if (document != null) { result = new javax.xml.transform.dom.DOMSource(document); if (getLocationRef() != null) { result.setSystemId(getLocationRef().getTargetRef().toString()); } } return result; } /** * Return the possibly null current SAX {@link EntityResolver}. * * @return The possibly null current SAX {@link EntityResolver}. */ public EntityResolver getEntityResolver() { return entityResolver; } /** * Return the possibly null current SAX {@link ErrorHandler}. * * @return The possibly null current SAX {@link ErrorHandler}. */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * Returns the XML representation as a SAX input source. * * @return The SAX input source. */ public abstract InputSource getInputSource() throws IOException; /** * Returns the map of namespaces. Namespace prefixes are keys and URI * references are values. * * @return The map of namespaces. */ public Map getNamespaces() { if (this.namespaces == null) { this.namespaces = new HashMap(); } return this.namespaces; } /** * {@inheritDoc * javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String} */ public String getNamespaceURI(String prefix) { return (this.namespaces == null) ? null : this.namespaces.get(prefix); } /** * Evaluates an XPath expression as a DOM Node. If the evaluation fails, * null will be returned. * * @return The evaluation result. */ public Node getNode(String expression) { return (Node) internalEval(expression, javax.xml.xpath.XPathConstants.NODE); } /** * Evaluates an XPath expression as a DOM NodeList. If the evaluation fails, * null will be returned. * * @return The evaluation result. */ public NodeList getNodes(String expression) { final org.w3c.dom.NodeList nodes = (org.w3c.dom.NodeList) internalEval( expression, javax.xml.xpath.XPathConstants.NODESET); return (nodes == null) ? null : new NodeList(nodes); } /** * Evaluates an XPath expression as a number. If the evaluation fails, null * will be returned. * * @return The evaluation result. */ public Double getNumber(String expression) { return (Double) internalEval(expression, javax.xml.xpath.XPathConstants.NUMBER); } /** * {@inheritDoc * javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String} */ public String getPrefix(String namespaceURI) { String result = null; boolean found = false; for (Iterator iterator = getNamespaces().keySet().iterator(); iterator .hasNext() && !found;) { String key = iterator.next(); if (getNamespaces().get(key).equals(namespaceURI)) { found = true; result = key; } } return result; } /** * {@inheritDoc * javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String} */ public Iterator getPrefixes(String namespaceURI) { final List result = new ArrayList(); for (Iterator iterator = getNamespaces().keySet().iterator(); iterator .hasNext();) { String key = iterator.next(); if (getNamespaces().get(key).equals(namespaceURI)) { result.add(key); } } return Collections.unmodifiableList(result).iterator(); } /** * Returns a SAX source. * * @return A SAX source. * @throws IOException */ public javax.xml.transform.sax.SAXSource getSaxSource() throws IOException { return getSaxSource(this); } /** * Return the possibly null {@link javax.xml.validation.Schema} to use for * this type of XML representations. * * @return the {@link javax.xml.validation.Schema} object of this type of * XML representations. */ public javax.xml.validation.Schema getSchema() { return schema; } /** * Returns a stream of XML markup. * * @return A stream of XML markup. * @throws IOException */ public javax.xml.transform.stream.StreamSource getStreamSource() throws IOException { final javax.xml.transform.stream.StreamSource result = new javax.xml.transform.stream.StreamSource( getStream()); if (getLocationRef() != null) { result.setSystemId(getLocationRef().getTargetRef().toString()); } return result; } /** * Evaluates an XPath expression as a string. * * @return The evaluation result. */ public String getText(String expression) { return (String) internalEval(expression, javax.xml.xpath.XPathConstants.STRING); } /** * Evaluates an XPath expression and returns the result as in the given * return type. * * @param returnType * The qualified name of the return type. * @return The evaluation result. */ private Object internalEval(String expression, javax.xml.namespace.QName returnType) { try { return evaluate(expression, returnType); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Indicates if the parser should be coalescing text. If true the parser * will convert CDATA nodes to text nodes and append it to the adjacent (if * any) text node. By default the value of this is set to false. * * @return True if parser should be coalescing text. */ public boolean isCoalescing() { return coalescing; } /** * Indicates if the parser will expand entity reference nodes. By default * the value of this is set to true. * * @return True if the parser will expand entity reference nodes. */ public boolean isExpandingEntityRefs() { return expandingEntityRefs; } /** * Indicates if the parser will ignore comments. By default the value of * this is set to false. * * @return True if the parser will ignore comments. */ public boolean isIgnoringComments() { return ignoringComments; } /** * Indicates if the parser will ignore extra white spaces in element * content. Note that the {@link #isValidatingDtd()} must be true when this * property is 'true' as validation is needed for it to work. By default the * value of this is set to false. * * @return True if the parser will ignore extra white spaces. */ public boolean isIgnoringExtraWhitespaces() { return ignoringExtraWhitespaces; } /** * Indicates if processing is namespace aware. * * @return True if processing is namespace aware. */ public boolean isNamespaceAware() { return this.namespaceAware; } /** * Indicates the desire for validating this type of XML representations * against an XML schema if one is referenced within the contents. * * @return True if the schema-based validation is enabled. */ public boolean isValidatingDtd() { return validatingDtd; } /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @return The current value of the xIncludeAware flag. */ public boolean isXIncludeAware() { return xIncludeAware; } /** * Puts a new mapping between a prefix and a namespace URI. * * @param prefix * The namespace prefix. * @param namespaceURI * The namespace URI. * @deprecated Use the modifiable map returned by {@link #getNamespaces()} */ @Deprecated public void putNamespace(String prefix, String namespaceURI) { getNamespaces().put(prefix, namespaceURI); } /** * Releases the namespaces map. */ @Override public void release() { if (this.namespaces != null) { this.namespaces.clear(); this.namespaces = null; } super.release(); } /** * Indicates if the parser should be coalescing text. If true the parser * will convert CDATA nodes to text nodes and append it to the adjacent (if * any) text node. By default the value of this is set to false. * * @param coalescing * True if parser should be coalescing text. */ public void setCoalescing(boolean coalescing) { this.coalescing = coalescing; } /** * Set the {@link EntityResolver} to use when resolving external entity * references encountered in this type of XML representations. * * @param entityResolver * the {@link EntityResolver} to set. */ public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } /** * Set the {@link ErrorHandler} to use when signaling SAX event exceptions. * * @param errorHandler * the {@link ErrorHandler} to set. */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Indicates if the parser will expand entity reference nodes. By default * the value of this is set to true. * * @param expandEntityRefs * True if the parser will expand entity reference nodes. */ public void setExpandingEntityRefs(boolean expandEntityRefs) { this.expandingEntityRefs = expandEntityRefs; } /** * Indicates if the parser will ignore comments. By default the value of * this is set to false. * * @param ignoringComments * True if the parser will ignore comments. */ public void setIgnoringComments(boolean ignoringComments) { this.ignoringComments = ignoringComments; } /** * Indicates if the parser will ignore extra white spaces in element * content. Note that the {@link #setValidatingDtd(boolean)} will be invoked * with 'true' if setting this property to 'true' as validation is needed * for it to work. * * @param ignoringExtraWhitespaces * True if the parser will ignore extra white spaces in element * content. */ public void setIgnoringExtraWhitespaces(boolean ignoringExtraWhitespaces) { if (this.ignoringExtraWhitespaces != ignoringExtraWhitespaces) { if (ignoringExtraWhitespaces) { setValidatingDtd(true); } this.ignoringExtraWhitespaces = ignoringExtraWhitespaces; } } /** * Indicates if processing is namespace aware. * * @param namespaceAware * Indicates if processing is namespace aware. */ public void setNamespaceAware(boolean namespaceAware) { this.namespaceAware = namespaceAware; } /** * Sets the map of namespaces. * * @param namespaces * The map of namespaces. */ public void setNamespaces(Map namespaces) { this.namespaces = namespaces; } /** * Set a (compiled) {@link javax.xml.validation.Schema} to use when parsing * and validating this type of XML representations. * * @param schema * The (compiled) {@link javax.xml.validation.Schema} object to * set. */ public void setSchema(javax.xml.validation.Schema schema) { this.schema = schema; } /** * Set a schema representation to be compiled and used when parsing and * validating this type of XML representations. * * @param schemaRepresentation * The schema representation to set. */ public void setSchema(Representation schemaRepresentation) { try { this.schema = getSchema(schemaRepresentation); } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to compile the schema representation", e); } } /** * Indicates the desire for validating this type of XML representations * against an XML schema if one is referenced within the contents. * * @param validating * The new validation flag to set. */ public void setValidatingDtd(boolean validating) { this.validatingDtd = validating; } /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @param includeAware * The new value of the xIncludeAware flag. */ public void setXIncludeAware(boolean includeAware) { xIncludeAware = includeAware; } /** * Validates the XML representation against a given schema. * * @param schema * The XML schema to use. */ public void validate(javax.xml.validation.Schema schema) throws Exception { validate(schema, null); } /** * Validates the XML representation against a given schema. * * @param schema * The XML schema to use. * @param result * The Result object that receives (possibly augmented) XML. */ public void validate(javax.xml.validation.Schema schema, javax.xml.transform.Result result) throws Exception { schema.newValidator().validate(getSaxSource(), result); } /** * Validates the XML representation against a given schema. * * @param schemaRepresentation * The XML schema representation to use. */ public void validate(Representation schemaRepresentation) throws Exception { validate(schemaRepresentation, null); } /** * Validates the XML representation against a given schema. * * @param schemaRepresentation * The XML schema representation to use. * @param result * The Result object that receives (possibly augmented) XML. */ public void validate(Representation schemaRepresentation, javax.xml.transform.Result result) throws Exception { validate(getSchema(schemaRepresentation), result); } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/NodeList.java0000664000175000017500000000436311757206344026645 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.util.AbstractList; import org.w3c.dom.Node; /** * DOM nodes set that implements the standard List interface for easier * iteration. * * @author Jerome Louvel */ public class NodeList extends AbstractList implements org.w3c.dom.NodeList { /** The wrapped node list. */ private volatile org.w3c.dom.NodeList nodes; /** * Constructor. * * @param nodes * The node list to wrap. */ public NodeList(org.w3c.dom.NodeList nodes) { this.nodes = nodes; } @Override public Node get(int index) { return this.nodes.item(index); } /** * {@inheritDoc org.w3c.dom.NodeList#getLength()} */ public int getLength() { return this.nodes.getLength(); } /** * {@inheritDoc org.w3c.dom.NodeList#item(int)} */ public Node item(int index) { return this.nodes.item(index); } @Override public int size() { return this.nodes.getLength(); } } restlet-2.0.14/org.restlet.ext.xml/src/org/restlet/ext/xml/Transformer.java0000664000175000017500000002212111757206344027416 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xml; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.routing.Filter; /** * Filter that can transform XML representations by applying an XSLT transform * sheet. It uses the {@link org.restlet.representation.TransformRepresentation} * to actually transform the XML entities.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class Transformer extends Filter { /** * Mode that transforms request entities before their handling by the * attached Restlet. */ public static final int MODE_REQUEST = 1; /** * Mode that transforms response entities after their handling by the * attached Restlet. */ public static final int MODE_RESPONSE = 2; /** The transformation mode. */ private volatile int mode; /** * The character set of the result representation. The default value is * null. */ private volatile CharacterSet resultCharacterSet; /** * The encodings of the result representation. */ private volatile List resultEncodings; /** The languages of the result representation. */ private volatile List resultLanguages; /** * The media type of the result representation. MediaType.APPLICATION_XML by * default. */ private volatile MediaType resultMediaType; /** The XSLT transform sheet to apply to message entities. */ private volatile Representation transformSheet; /** * Constructor. * * @param mode * The transformation mode. * @param transformSheet * The XSLT transform sheet to apply to message entities. */ public Transformer(int mode, Representation transformSheet) { this.mode = mode; this.transformSheet = transformSheet; this.resultMediaType = MediaType.APPLICATION_XML; this.resultCharacterSet = null; } @Override protected void afterHandle(Request request, Response response) { if ((getMode() == MODE_RESPONSE) && canTransform(response.getEntity())) { response.setEntity(transform(response.getEntity())); } } @Override protected int beforeHandle(Request request, Response response) { if ((getMode() == MODE_REQUEST) && canTransform(request.getEntity())) { request.setEntity(transform(request.getEntity())); } return CONTINUE; } /** * Indicates if the filter can transform the given message entity. By * default, it always returns true. * * @param representation * The entity representation to test. * @return True if the transformation can be applied. */ protected boolean canTransform(Representation representation) { return true; } /** * Returns the transformation mode. See MODE_* constants. * * @return The transformation mode. */ public int getMode() { return this.mode; } /** * Returns the character set of the result representation. The default value * is null. * * @return The character set of the result representation. */ public CharacterSet getResultCharacterSet() { return this.resultCharacterSet; } /** * Returns the modifiable list of encodings of the result representation. * * @return The encoding of the result representation. */ public List getResultEncodings() { // Lazy initialization with double-check. List re = this.resultEncodings; if (re == null) { synchronized (this) { re = this.resultEncodings; if (re == null) { this.resultEncodings = re = new CopyOnWriteArrayList(); } } } return re; } /** * Returns the modifiable list of languages of the result representation. * * @return The language of the result representation. */ public List getResultLanguages() { // Lazy initialization with double-check. List v = this.resultLanguages; if (v == null) { synchronized (this) { v = this.resultLanguages; if (v == null) { this.resultLanguages = v = new CopyOnWriteArrayList(); } } } return v; } /** * Returns the media type of the result representation. The default value is * MediaType.APPLICATION_XML. * * @return The media type of the result representation. */ public MediaType getResultMediaType() { return this.resultMediaType; } /** * Returns the XSLT transform sheet to apply to message entities. * * @return The XSLT transform sheet to apply to message entities. */ public Representation getTransformSheet() { return this.transformSheet; } /** * Sets the transformation mode. See MODE_* constants. * * @param mode * The transformation mode. */ public void setMode(int mode) { this.mode = mode; } /** * Sets the character set of the result representation. * * @param resultCharacterSet * The character set of the result representation. */ public void setResultCharacterSet(CharacterSet resultCharacterSet) { this.resultCharacterSet = resultCharacterSet; } /** * Sets the encodings of the result representation. * * @param resultEncodings * The encodings of the result representation. */ public void setResultEncodings(List resultEncodings) { this.resultEncodings = resultEncodings; } /** * Sets the languages of the result representation. * * @param resultLanguages * The languages of the result representation. */ public void setResultLanguages(List resultLanguages) { this.resultLanguages = resultLanguages; } /** * Sets the media type of the result representation. * * @param resultMediaType * The media type of the result representation. */ public void setResultMediaType(MediaType resultMediaType) { this.resultMediaType = resultMediaType; } /** * Sets the XSLT transform sheet to apply to message entities. * * @param transformSheet * The XSLT transform sheet to apply to message entities. */ public void setTransformSheet(Representation transformSheet) { this.transformSheet = transformSheet; } /** * Transforms a source XML representation by applying an XSLT transform * sheet to it. * * @param source * The source XML representation. * @return The generated result representation. */ public Representation transform(Representation source) { final Representation result = new TransformRepresentation(getContext(), source, getTransformSheet()); if (this.resultLanguages != null) { result.getLanguages().addAll(getResultLanguages()); } result.setCharacterSet(getResultCharacterSet()); if (this.resultEncodings != null) { result.getEncodings().addAll(getResultEncodings()); } result.setMediaType(getResultMediaType()); return result; } } restlet-2.0.14/org.restlet.ext.jackson/0000775000175000017500000000000012001473174020431 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jackson/pom.xml0000600000175000017500000000203212001473174021731 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.jackson Restlet Extension - Jackson Integration with Jackson. org.codehaus.jackson jackson-core-asl 1.4.3 org.codehaus.jackson jackson-mapper-asl 1.4.3 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.jackson/src/0000775000175000017500000000000012001473174021220 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jackson/src/META-INF/0000775000175000017500000000000011757206450022370 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jackson/src/META-INF/services/0000775000175000017500000000000011757206352024214 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jackson/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.jackson/src/META-INF/services/org.restlet.engine.converter.ConverterH0000664000175000017500000000005011757206352033732 0ustar jamespagejamespageorg.restlet.ext.jackson.JacksonConverterrestlet-2.0.14/org.restlet.ext.jackson/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446024030 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.jackson/src/org/0000775000175000017500000000000011757206352022020 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jackson/src/org/restlet/0000775000175000017500000000000011757206352023502 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jackson/src/org/restlet/ext/0000775000175000017500000000000011757206352024302 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jackson/src/org/restlet/ext/jackson/0000775000175000017500000000000011757206352025732 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jackson/src/org/restlet/ext/jackson/package.html0000664000175000017500000000037011757206352030213 0ustar jamespagejamespage Integration with Jackson 1.4. Jackson is a high-performance JSON processor able to serialize objects to JSON and back again. @since Restlet 2.0 @see Jackson Web site restlet-2.0.14/org.restlet.ext.jackson/src/org/restlet/ext/jackson/JacksonConverter.java0000664000175000017500000001731611757206352032065 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jackson; import java.io.IOException; import java.util.List; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator.Feature; import org.codehaus.jackson.map.ObjectMapper; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between the JSON and Representation classes based on Jackson. * * @author Jerome Louvel */ public class JacksonConverter extends ConverterHelper { private static final VariantInfo VARIANT_JSON = new VariantInfo( MediaType.APPLICATION_JSON); /** The modifiable Jackson object mapper. */ private ObjectMapper objectMapper; /** * Creates the marshaling {@link JacksonRepresentation}. * * @param * @param mediaType * The target media type. * @param source * The source object to marshal. * @return The marshaling {@link JacksonRepresentation}. */ protected JacksonRepresentation create(MediaType mediaType, T source) { JacksonRepresentation result = new JacksonRepresentation( mediaType, source); result.setObjectMapper(getObjectMapper()); return result; } /** * Creates the unmarshaling {@link JacksonRepresentation}. * * @param * @param source * The source representation to unmarshal. * @param objectClass * The object class to instantiate. * @return The unmarshaling {@link JacksonRepresentation}. */ protected JacksonRepresentation create(Representation source, Class objectClass) { JacksonRepresentation result = new JacksonRepresentation(source, objectClass); result.setObjectMapper(getObjectMapper()); return result; } /** * Creates a Jackson object mapper based on a media type. By default, it * calls {@link ObjectMapper#ObjectMapper(JsonFactory)}. * * @return The Jackson object mapper. */ protected ObjectMapper createObjectMapper() { JsonFactory jsonFactory = new JsonFactory(); jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false); return new ObjectMapper(jsonFactory); } @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_JSON.isCompatible(source)) { result = addObjectClass(result, Object.class); result = addObjectClass(result, JacksonRepresentation.class); } return result; } /** * Returns the modifiable Jackson object mapper. Useful to customize * mappings. * * @return The modifiable Jackson object mapper. */ public ObjectMapper getObjectMapper() { if (this.objectMapper == null) { synchronized (this) { if (this.objectMapper == null) { this.objectMapper = createObjectMapper(); } } } return this.objectMapper; } @Override public List getVariants(Class source) { List result = null; if (source != null) { result = addVariant(result, VARIANT_JSON); } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source instanceof JacksonRepresentation) { result = 1.0F; } else { if (target == null) { result = 0.5F; } else if (VARIANT_JSON.isCompatible(target)) { result = 0.8F; } else { result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (source instanceof JacksonRepresentation) { result = 1.0F; } else if ((target != null) && JacksonRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (VARIANT_JSON.isCompatible(source)) { result = 0.8F; } return result; } /** * Sets the Jackson object mapper. * * @param objectMapper * The Jackson object mapper. */ public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @SuppressWarnings("unchecked") @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; // The source for the Jackson conversion JacksonRepresentation jacksonSource = null; if (source instanceof JacksonRepresentation) { jacksonSource = (JacksonRepresentation) source; } else if (VARIANT_JSON.isCompatible(source)) { jacksonSource = create(source, target); } if (jacksonSource != null) { // Handle the conversion if ((target != null) && JacksonRepresentation.class.isAssignableFrom(target)) { result = jacksonSource; } else { result = jacksonSource.getObject(); } } return (T) result; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; if (source instanceof JacksonRepresentation) { result = (JacksonRepresentation) source; } else { if (target.getMediaType() == null) { target.setMediaType(MediaType.APPLICATION_JSON); } if (VARIANT_JSON.isCompatible(target)) { JacksonRepresentation jacksonRepresentation = create( target.getMediaType(), source); result = jacksonRepresentation; } } return result; } @Override public void updatePreferences(List> preferences, Class entity) { updatePreferences(preferences, MediaType.APPLICATION_JSON, 1.0F); } } restlet-2.0.14/org.restlet.ext.jackson/src/org/restlet/ext/jackson/JacksonRepresentation.java0000664000175000017500000001374311757206352033120 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jackson; import java.io.IOException; import java.io.Writer; import java.util.logging.Level; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator.Feature; import org.codehaus.jackson.map.ObjectMapper; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; /** * Representation based on the Jackson library. It can serialize and deserialize * automatically in JSON. * * @see Jackson project * @author Jerome Louvel * @param * The type to wrap. */ public class JacksonRepresentation extends WriterRepresentation { /** The (parsed) object to format. */ private T object; /** The object class to instantiate. */ private Class objectClass; /** The JSON representation to parse. */ private Representation jsonRepresentation; /** The modifiable Jackson object mapper. */ private ObjectMapper objectMapper; /** * Constructor. * * @param mediaType * The target media type. * @param object * The object to format. */ @SuppressWarnings("unchecked") public JacksonRepresentation(MediaType mediaType, T object) { super(mediaType); this.object = object; this.objectClass = (Class) ((object == null) ? null : object .getClass()); this.jsonRepresentation = null; this.objectMapper = null; } /** * Constructor. * * @param representation * The representation to parse. */ public JacksonRepresentation(Representation representation, Class objectClass) { super(representation.getMediaType()); this.object = null; this.objectClass = objectClass; this.jsonRepresentation = representation; this.objectMapper = null; } /** * Constructor. * * @param object * The object to format. */ public JacksonRepresentation(T object) { this(MediaType.APPLICATION_JSON, object); } /** * Creates a Jackson object mapper based on a media type. By default, it * calls {@link ObjectMapper#ObjectMapper(JsonFactory)}. * * @return The Jackson object mapper. */ protected ObjectMapper createObjectMapper() { JsonFactory jsonFactory = new JsonFactory(); jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false); return new ObjectMapper(jsonFactory); } /** * Returns the wrapped object, deserializing the representation with Jackson * if necessary. * * @return The wrapped object. */ public T getObject() { T result = null; if (this.object != null) { result = this.object; } else if (this.jsonRepresentation != null) { try { result = getObjectMapper().readValue( this.jsonRepresentation.getStream(), this.objectClass); } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to parse the object with Jackson.", e); } } return result; } /** * Returns the object class to instantiate. * * @return The object class to instantiate. */ public Class getObjectClass() { return objectClass; } /** * Returns the modifiable Jackson object mapper. Useful to customize * mappings. * * @return The modifiable Jackson object mapper. */ public ObjectMapper getObjectMapper() { if (this.objectMapper == null) { this.objectMapper = createObjectMapper(); } return this.objectMapper; } /** * Sets the object to format. * * @param object * The object to format. */ public void setObject(T object) { this.object = object; } /** *Sets the object class to instantiate. * * @param objectClass * The object class to instantiate. */ public void setObjectClass(Class objectClass) { this.objectClass = objectClass; } /** * Sets the Jackson object mapper. * * @param objectMapper * The Jackson object mapper. */ public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void write(Writer writer) throws IOException { if (jsonRepresentation != null) { jsonRepresentation.write(writer); } else if (object != null) { getObjectMapper().writeValue(writer, object); } } } restlet-2.0.14/org.restlet.ext.jaas/0000775000175000017500000000000012001473135017714 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaas/pom.xml0000600000175000017500000000135112001473135021217 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.jaas Restlet Extension - JAAS Support for JAAS based security. org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.jaas/src/0000775000175000017500000000000012001473135020503 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaas/src/META-INF/0000775000175000017500000000000011757206450021656 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaas/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446023316 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.jaas/src/org/0000775000175000017500000000000011757206346021311 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaas/src/org/restlet/0000775000175000017500000000000011757206346022773 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaas/src/org/restlet/ext/0000775000175000017500000000000011757206346023573 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaas/src/org/restlet/ext/jaas/0000775000175000017500000000000011757206346024511 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaas/src/org/restlet/ext/jaas/JaasUtils.java0000664000175000017500000001031111757206346027247 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaas; import java.security.AccessControlContext; import java.security.Principal; import java.security.PrivilegedAction; import javax.security.auth.Subject; import org.restlet.data.ClientInfo; import org.restlet.security.Role; /** * Utility class to facilitate integration between the Restlet and JAAS APIs. * * @author Jerome Louvel */ public final class JaasUtils { /** * Creates a JAAS subject based on a given {@link ClientInfo}. It adds a * {@link ClientInfo#getUser()}, all the entries in * {@link ClientInfo#getRoles()} and all other principals in * {@link ClientInfo#getPrincipals()}. * * @param clientInfo * The client info to expose as a subject. * @return The populated JAAS subject. */ public static Subject createSubject(ClientInfo clientInfo) { Subject result = new Subject(); if (clientInfo != null) { if (clientInfo.getUser() != null) { result.getPrincipals().add(clientInfo.getUser()); } for (Role role : clientInfo.getRoles()) { result.getPrincipals().add(role); } for (Principal principal : clientInfo.getPrincipals()) { result.getPrincipals().add(principal); } } return result; } /** * Creates a JAAS subject on the {@link ClientInfo} and uses it to run the * action, using * {@link Subject#doAsPrivileged(Subject, PrivilegedAction, AccessControlContext)} * . * * @param * the return type of the action. * @param clientInfo * the client info from which to build a subject. * @param action * the code to be run as the specified Subject. * @param acc * the AccessControlContext to be tied to the specified subject * and action. * @return the value returned by the action. */ @SuppressWarnings("unchecked") public static T doAsPriviledged(ClientInfo clientInfo, PrivilegedAction action, AccessControlContext acc) { Subject subject = JaasUtils.createSubject(clientInfo); T result = (T) Subject.doAsPrivileged(subject, action, acc); return result; } /** * Creates a JAAS subject on the {@link ClientInfo} and uses it to run the * action, using * {@link Subject#doAsPrivileged(Subject, PrivilegedAction, AccessControlContext)} * . This uses a null {@link AccessControlContext}. * * @param * the return type of the action. * @param clientInfo * the client info from which to build as a subject. * @param action * the code to be run as the specified Subject. * @return the value returned by the action. */ public static T doAsPriviledged(ClientInfo clientInfo, PrivilegedAction action) { return doAsPriviledged(clientInfo, action, null); } } restlet-2.0.14/org.restlet.ext.jaas/src/org/restlet/ext/jaas/ChallengeCallbackHandler.java0000664000175000017500000001112311757206346032147 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaas; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import org.restlet.Request; import org.restlet.Response; /** * JAAS callback handler that automatically provides the identifier and secret * when asked by login modules. * * @author Jerome Louvel */ public class ChallengeCallbackHandler implements CallbackHandler { /** The handled request. */ private volatile Request request; /** The handled response. */ private volatile Response response; /** * Constructor. * * @param request * The handled request. * @param response * The handled response. */ public ChallengeCallbackHandler(Request request, Response response) { this.request = request; this.response = response; } /** * Returns the handled request. * * @return The handled request. */ public Request getRequest() { return request; } /** * Returns the handled response. * * @return The handled response. */ public Response getResponse() { return response; } /** * Handles a callback. The default implementation automatically sets the * identifier on {@link javax.security.auth.callback.NameCallback} instances * and the secret on {@link PasswordCallback}. * * @param callback * The callback to handle. * @throws UnsupportedCallbackException */ protected void handle(Callback callback) throws UnsupportedCallbackException { if (callback instanceof javax.security.auth.callback.NameCallback) { javax.security.auth.callback.NameCallback nc = (javax.security.auth.callback.NameCallback) callback; if (getRequest().getChallengeResponse() != null) { nc.setName(getRequest().getChallengeResponse().getIdentifier()); } } else if (callback instanceof PasswordCallback) { PasswordCallback pc = (PasswordCallback) callback; if (getRequest().getChallengeResponse() != null) { pc.setPassword(getRequest().getChallengeResponse().getSecret()); } } else { throw new UnsupportedCallbackException(callback, "Unrecognized Callback"); } } /** * Handles the callbacks. The default implementation delegates the handling * to the {@link #handle(Callback)} method. * * @param callbacks * The callbacks to handle. */ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { if (callbacks != null) { for (Callback callback : callbacks) { handle(callback); } } } /** * Sets the handled request. * * @param request * The handled request. */ public void setRequest(Request request) { this.request = request; } /** * Sets the handled response. * * @param response * The handled response. */ public void setResponse(Response response) { this.response = response; } } restlet-2.0.14/org.restlet.ext.jaas/src/org/restlet/ext/jaas/JaasVerifier.java0000664000175000017500000001632111757206346027731 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaas; import java.security.Principal; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ClientInfo; import org.restlet.security.User; import org.restlet.security.Verifier; /** * Verifier that leverages the JAAS pluggable authentication mechanism. * * @author Jerome Louvel * @see JAAS * Tutorials * @see JAAS * Reference Guide */ public class JaasVerifier implements Verifier { /** The optional JAAS login configuration. */ private volatile Configuration configuration; /** The JAAS login context name. */ private volatile String name; /** Optional class from which to build a user principal */ private volatile String userPrincipalClassName; /** * Constructor. * * @param name * The JAAS login context name. */ public JaasVerifier(String name) { this.name = name; } /** * Creates a callback handler for the given parameters. By default it * returns one handler that handles name and password JAAS callbacks. * * @return The callback handler created. */ protected CallbackHandler createCallbackHandler(Request request, Response response) { return new ChallengeCallbackHandler(request, response); } /** * Returns the optional JAAS login configuration. * * @return The optional JAAS login configuration. */ public Configuration getConfiguration() { return configuration; } /** * Returns the JAAS login context name. * * @return The JAAS login context name. */ public String getName() { return name; } /** * Gets the user principal class name. * * @return the user principal class name. */ public String getUserPrincipalClassName() { return this.userPrincipalClassName; } /** * Sets the optional JAAS login configuration. * * @param configuration * The optional JAAS login configuration. */ public void setConfiguration(Configuration configuration) { this.configuration = configuration; } /** * Sets the JAAS login context name. * * @param contextName * The JAAS login context name. */ public void setName(String contextName) { this.name = contextName; } /** * Sets the user principal class name. If a {@link User} is not associated * with the {@link Request}'s {@link ClientInfo} and if one of the * principals returned after the JAAS login is of this type, a new * {@link User} will be associated with the {@link ClientInfo} using its * name. * * @param userPrincipalClassName * the user principal class name. */ public void setUserPrincipalClassName(String userPrincipalClassName) { this.userPrincipalClassName = userPrincipalClassName; } /** * Verifies that the proposed secret is correct for the specified * identifier. By default, it creates a JAAS login context with the callback * handler obtained by {@link #createCallbackHandler(Request, Response)} and * calls the {@link LoginContext#login()} method on it. * * @param request * The request sent. * @param response * The response to update. * @return Result of the verification based on the RESULT_* constants. */ public int verify(Request request, Response response) { int result = RESULT_VALID; try { Subject subject = new Subject(); if (request.getClientInfo().getUser() != null) { subject.getPrincipals().add(request.getClientInfo().getUser()); } if (request.getClientInfo().getRoles() != null) { subject.getPrincipals().addAll( request.getClientInfo().getRoles()); } subject.getPrincipals().addAll( request.getClientInfo().getPrincipals()); LoginContext loginContext = new LoginContext(getName(), subject, createCallbackHandler(request, response), getConfiguration()); loginContext.login(); /* * If the login operation added new principals to the subject, we * add them back to the ClientInfo. */ for (Principal principal : subject.getPrincipals()) { if ((!principal.equals(request.getClientInfo().getUser())) && (!request.getClientInfo().getRoles().contains( principal)) && (!request.getClientInfo().getPrincipals().contains( principal))) { request.getClientInfo().getPrincipals().add(principal); } /* * If no user has been set yet and if this principal if of the * type we expect for a user, we create a new User based on the * principal's name. */ if ((request.getClientInfo().getUser() == null) && (this.userPrincipalClassName != null) && (principal.getClass().getName() .equals(this.userPrincipalClassName))) { request.getClientInfo().setUser( new User(principal.getName())); } } } catch (LoginException le) { result = RESULT_INVALID; } return result; } } restlet-2.0.14/org.restlet.ext.jaas/src/org/restlet/ext/jaas/package.html0000664000175000017500000000016411757206346026773 0ustar jamespagejamespage Support for JAAS authentication and authorization framework. @since Restlet 2.0 restlet-2.0.14/org.restlet.ext.simple/0000775000175000017500000000000012001473140020263 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/pom.xml0000600000175000017500000000157512001473140021576 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.simple Restlet Extension - Simple Integration with Simple framework. org.simpleframework simple 4.1.21 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.simple/src/0000775000175000017500000000000012001473140021052 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/META-INF/0000775000175000017500000000000011757206452022233 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/META-INF/services/0000775000175000017500000000000011757206346024060 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/META-INF/services/org.restlet.engine.ServerHelper0000664000175000017500000000014311757206346032122 0ustar jamespagejamespageorg.restlet.ext.simple.HttpServerHelper # HTTP org.restlet.ext.simple.HttpsServerHelper # HTTPS restlet-2.0.14/org.restlet.ext.simple/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023664 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.simple/src/org/0000775000175000017500000000000011757206346021664 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/org/restlet/0000775000175000017500000000000011757206346023346 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/0000775000175000017500000000000011757206346024146 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/0000775000175000017500000000000011757206346025437 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/SimpleServerHelper.java0000664000175000017500000001344611757206346032072 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.simple; import java.net.InetSocketAddress; import java.util.logging.Level; import org.restlet.Server; import org.restlet.engine.http.HttpServerHelper; import org.simpleframework.transport.connect.Connection; import org.simpleframework.http.core.ContainerServer; /** * Abstract Simple Web server connector. Here is the list of parameters that are * supported. They should be set in the Server's context before it is started: * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    defaultThreadsint20Default number of polling threads for a handler object.
    maxWaitTimeMsint200Maximum waiting time between polls of the input.
    * * @author Lars Heuer * @author Jerome Louvel */ public abstract class SimpleServerHelper extends HttpServerHelper { /** * Indicates if this service is acting in HTTP or HTTPS mode. */ private volatile boolean confidential; /** * Simple connection. */ private volatile Connection connection; /** * Simple container server. */ private volatile ContainerServer containerServer; /** * Socket this server is listening to. */ private volatile InetSocketAddress address; /** * Constructor. * * @param server * The server to help. */ public SimpleServerHelper(Server server) { super(server); } /** * Returns the Simple connection. * * @return The Simple connection. */ protected Connection getConnection() { return this.connection; } /** * Returns the default number of polling threads for a handler object. * * @return The default number of polling threads for a handler object. */ public int getDefaultThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( "defaultThreads", "5")); } /** * Returns the Simple container server. * * @return The Simple container server. */ protected ContainerServer getContainerServer() { return this.containerServer; } /** * Returns the socket address this server is listening to. * * @return The socket address this server is listening to. */ protected InetSocketAddress getAddress() { return this.address; } /** * Indicates if this service is acting in HTTP or HTTPS mode. * * @return True if this service is acting in HTTP or HTTPS mode. */ public boolean isConfidential() { return this.confidential; } /** * Indicates if this service is acting in HTTP or HTTPS mode. * * @param confidential * True if this service is acting in HTTP or HTTPS mode. */ protected void setConfidential(boolean confidential) { this.confidential = confidential; } /** * Sets the Simple connection. * * @param connection * The Simple connection. */ protected void setConnection(Connection connection) { this.connection = connection; } /** * Sets the Simple container server. * * @param container * The Simple containerServer. */ protected void setContainerServer(ContainerServer container) { this.containerServer = container; } /** * Sets the socket address this server is listening to. * * @param address * The socket address this server is listening to. */ protected void setAddress(InetSocketAddress address) { this.address = address; } @Override public synchronized void start() throws Exception { super.start(); getLogger().info( "Starting the Simple " + getProtocols() + " server on port " + getHelped().getPort()); // Sets the ephemeral port is necessary // setEphemeralPort(getAddress().getPort()); } @Override public synchronized void stop() throws Exception { getLogger().info("Stopping the Simple server"); try { getConnection().close(); } catch (Exception e) { getLogger() .log( Level.FINE, "Exception while closing the server socket. Can probably be safely ignored.", e); } getContainerServer().stop(); } } restlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/internal/0000775000175000017500000000000011757206346027253 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/internal/SimpleCall.java0000664000175000017500000002302111757206346032141 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.simple.internal; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; import java.security.cert.Certificate; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import org.restlet.Server; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.engine.http.ServerCall; import org.restlet.util.Series; import org.simpleframework.http.Request; import org.simpleframework.http.Response; /** * Call that is used by the Simple HTTP server. * * @author Lars Heuer * @author Jerome Louvel */ public class SimpleCall extends ServerCall { /** * Simple Request. */ private final Request request; /** * Simple Response. */ private final Response response; /** Indicates if the request headers were parsed and added. */ private volatile boolean requestHeadersAdded; /** * The version of the request; */ private final String version; /** * Constructs this class with the specified {@link simple.http.Request} and * {@link simple.http.Response}. * * @param server * The parent server. * @param request * Request to wrap. * @param response * Response to wrap. * @param confidential * Indicates if this call is acting in HTTP or HTTPS mode. */ SimpleCall(Server server, Request request, Response response, boolean confidential) { super(server); this.version = request.getMajor() + "." + request.getMinor(); this.request = request; this.response = response; setConfidential(confidential); this.requestHeadersAdded = false; } /** * Closes the socket. */ @Override public boolean abort() { try { getSocket().close(); } catch (IOException e) { } return true; } @Override public void complete() { try { // Commit the response this.response.commit(); } catch (Exception ex) { getLogger().log(Level.WARNING, "Unable to commit the response", ex); } } @Override public String getClientAddress() { return this.request.getClientAddress().getAddress().getHostAddress(); } @Override public int getClientPort() { final SocketChannel socket = getSocket(); return (socket != null) ? socket.socket().getPort() : -1; } @Override protected long getContentLength() { return request.getContentLength(); } @Override public String getHostDomain() { return super.getHostDomain(); // FIXME } /** * Returns the request method. * * @return The request method. */ @Override public String getMethod() { return this.request.getMethod(); } @Override public ReadableByteChannel getRequestEntityChannel(long size) { // No performance benefit getting request channel // try { // return this.request.getByteChannel(); // } catch (Exception ex) { // return null; // } return null; } @Override public InputStream getRequestEntityStream(long size) { try { return this.request.getInputStream(); } catch (Exception ex) { return null; } } @Override public ReadableByteChannel getRequestHeadChannel() { // No performance benefit getting request channel // try { // return this.request.getByteChannel(); // } catch (Exception ex) { // return null; // } return null; } /** * Returns the list of request headers. * * @return The list of request headers. */ @Override public Series getRequestHeaders() { final Series result = super.getRequestHeaders(); if (!this.requestHeadersAdded) { final List names = this.request.getNames(); for (String name : names) { for (String value : this.request.getValues(name)) { result.add(new Parameter(name, value)); } } this.requestHeadersAdded = true; } return result; } @Override public InputStream getRequestHeadStream() { // try { // return this.request.getInputStream(); // } catch (Exception ex) { // return null; // } return null; } /** * Returns the full request URI. * * @return The full request URI. */ @Override public String getRequestUri() { return this.request.getTarget(); } /** * Returns the response channel if it exists. * * @return The response channel if it exists. */ @Override public WritableByteChannel getResponseEntityChannel() { try { return this.response.getByteChannel(); } catch (Exception ex) { return null; } } /** * Returns the response stream if it exists. * * @return The response stream if it exists. */ @Override public OutputStream getResponseEntityStream() { try { return this.response.getOutputStream(); } catch (Exception ex) { return null; } } /** * Returns the request socket. * * @return The request socket. */ private SocketChannel getSocket() { return (SocketChannel) this.request .getAttribute(SimpleServer.PROPERTY_SOCKET); } @Override public String getSslCipherSuite() { final SSLEngine sslEngine = getSslEngine(); if (sslEngine != null) { final SSLSession sslSession = sslEngine.getSession(); if (sslSession != null) { return sslSession.getCipherSuite(); } } return null; } @Override public List getSslClientCertificates() { final SSLEngine sslEngine = getSslEngine(); if (sslEngine != null) { final SSLSession sslSession = sslEngine.getSession(); if (sslSession != null) { try { final List clientCertificates = Arrays .asList(sslSession.getPeerCertificates()); return clientCertificates; } catch (SSLPeerUnverifiedException e) { getLogger().log(Level.FINE, "Can't get the client certificates.", e); } } } return null; } @Override protected byte[] getSslSessionIdBytes() { final SSLEngine sslEngine = getSslEngine(); if (sslEngine != null) { final SSLSession sslSession = sslEngine.getSession(); if (sslSession != null) { return sslSession.getId(); } } return null; } /** * Returns the SSL engine. * * @return the SSL engine */ private SSLEngine getSslEngine() { return (SSLEngine) this.request .getAttribute(SimpleServer.PROPERTY_ENGINE); } @Override public String getVersion() { return version; } @Override protected boolean isClientKeepAlive() { return request.isKeepAlive(); } @Override public void writeResponseHead(org.restlet.Response restletResponse) throws IOException { // this.response.clear(); for (final Parameter header : getResponseHeaders()) { this.response.add(header.getName(), header.getValue()); } // Set the status this.response.setCode(getStatusCode()); this.response.setText(getReasonPhrase()); // Ensure the HEAD response sends back the right Content-length header. if (!Method.HEAD.equals(restletResponse.getRequest().getMethod()) && restletResponse.getEntity() == null) { this.response.setContentLength(0); } } } restlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/internal/SimpleContainer.java0000664000175000017500000000556611757206346033226 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.simple.internal; import java.util.logging.Level; import org.restlet.ext.simple.SimpleServerHelper; import org.simpleframework.http.Request; import org.simpleframework.http.Response; import org.simpleframework.http.core.Container; /** * Simple container delegating the calls to the Restlet server helper. * * @author Jerome Louvel */ public class SimpleContainer implements Container { /** The delegate Restlet server helper. */ private volatile SimpleServerHelper helper; /** * Constructor. * * @param helper * The delegate Restlet server helper. */ public SimpleContainer(SimpleServerHelper helper) { this.helper = helper; } /** * Returns the delegate Restlet server helper. * * @return The delegate Restlet server helper. */ public SimpleServerHelper getHelper() { return this.helper; } /** * Handles a Simple request/response transaction. * * @param request * The Simple request. * @param response * The Simple response. */ public void handle(Request request, Response response) { getHelper().handle( new SimpleCall(getHelper().getHelped(), request, response, getHelper().isConfidential())); try { response.close(); } catch (Exception e) { getHelper() .getLogger() .log( Level.FINE, "Exception while closing the Simple response's output stream", e); } } } restlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/internal/SimpleServer.java0000664000175000017500000000527611757206346032550 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.simple.internal; import java.io.IOException; import java.nio.channels.SocketChannel; import java.util.Map; import javax.net.ssl.SSLEngine; import org.simpleframework.transport.Server; import org.simpleframework.transport.Socket; /** * A subclass of BufferedPipelineFactory that sets the connection socket on each * pipeline for later retrieval. * * @author Jerome Louvel */ public class SimpleServer implements Server { public static final String PROPERTY_SOCKET = "org.restlet.ext.simple.socket"; public static final String PROPERTY_ENGINE = "org.restlet.ext.simple.engine"; /** * This is the server to be used. */ private final Server server; /** * Constructor. */ public SimpleServer(Server server) { this.server = server; } /** * Pass in the connection socket and add the engine to the pipeline * attributes. * * @param socket * the pipeline */ @SuppressWarnings("unchecked") public void process(Socket socket) throws IOException { Map map = socket.getAttributes(); SSLEngine engine = socket.getEngine(); SocketChannel channel = socket.getChannel(); map.put(PROPERTY_ENGINE, engine); map.put(PROPERTY_SOCKET, channel); server.process(socket); } /** * This is used to stop the internal server. */ public void stop() throws IOException { server.stop(); } } restlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/package.html0000664000175000017500000000044411757206346027722 0ustar jamespagejamespage Integration with Simple framework 4.1. The primary focus of the project is to provide a truly embeddable Java based HTTP engine capable of handling enormous loads. @since Restlet 1.0 @see Simple Framework restlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/HttpsServerHelper.java0000664000175000017500000002162511757206346031741 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.simple; import java.io.File; import java.net.InetAddress; import java.net.InetSocketAddress; import javax.net.ssl.SSLContext; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.security.SslUtils; import org.restlet.engine.security.SslContextFactory; import org.restlet.ext.simple.internal.SimpleContainer; import org.restlet.ext.simple.internal.SimpleServer; import org.simpleframework.transport.connect.Connection; import org.simpleframework.transport.connect.SocketConnection; import org.simpleframework.http.core.Container; import org.simpleframework.http.core.ContainerServer; /** * Simple HTTP server connector. Here is the list of additional parameters that * are supported. They should be set in the Server's context before it is * started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    sslContextFactoryStringnullLet you specify a {@link SslContextFactory} instance for a more complete * and flexible SSL context setting. If this parameter is set, it takes * Precedence over the other SSL parameters below.
    sslContextFactoryStringnullLet you specify a {@link SslContextFactory} class name as a parameter, or * an instance as an attribute for a more complete and flexible SSL context * setting. If set, it takes precedence over the other SSL parameters below.
    keystorePathString${user.home}/.keystoreSSL keystore path.
    keystorePasswordStringSSL keystore password.
    keystoreTypeStringJKSSSL keystore type
    keyPasswordString${keystorePassword}SSL key password.
    certAlgorithmStringSunX509SSL certificate algorithm.
    enabledCipherSuitesStringnullWhitespace-separated list of enabled cipher suites and/or can be * specified multiple times.
    disabledCipherSuitesStringnullWhitespace-separated list of disabled cipher suites and/or can be * specified multiple times. It affects the cipher suites manually enabled or * the default ones.
    needClientAuthenticationbooleanfalseIndicates if we require client certificate authentication.
    sslProtocolStringTLSSSL protocol.
    wantClientAuthenticationbooleanfalseIndicates if we would like client certificate authentication (only for * the BIO connector type).
    * * @author Lars Heuer * @author Jerome Louvel */ public class HttpsServerHelper extends SimpleServerHelper { /** * This is the SSL context. */ private SSLContext sslContext; /** * Constructor. * * @param server * The server to help. */ public HttpsServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTPS); } /** * Returns the SSL certificate algorithm. * * @return The SSL certificate algorithm. */ @Deprecated public String getCertAlgorithm() { return getHelpedParameters().getFirstValue("certAlgorithm", "SunX509"); } /** * Returns the SSL key password. * * @return The SSL key password. */ @Deprecated public String getKeyPassword() { return getHelpedParameters().getFirstValue("keyPassword", getKeystorePassword()); } /** * Returns the SSL keystore password. * * @return The SSL keystore password. */ @Deprecated public String getKeystorePassword() { return getHelpedParameters().getFirstValue("keystorePassword", ""); } /** * Returns the SSL keystore path. * * @return The SSL keystore path. */ @Deprecated public String getKeystorePath() { return getHelpedParameters().getFirstValue("keystorePath", System.getProperty("user.home") + File.separator + ".keystore"); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getKeystoreType() { return getHelpedParameters().getFirstValue("keystoreType", "JKS"); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getSslProtocol() { return getHelpedParameters().getFirstValue("sslProtocol", "TLS"); } /** * Indicates if we require client certificate authentication. * * @return True if we require client certificate authentication. */ public boolean isNeedClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "needClientAuthentication", "false")); } /** * Indicates if we would like client certificate authentication. * * @return True if we would like client certificate authentication. */ public boolean isWantClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "wantClientAuthentication", "false")); } /** * Gets the SSL context used by this server. * * @return this returns the SSL context. */ public SSLContext getSslContext() { return sslContext; } /** * Sets the SSL context for the server. * * @param sslContext * the SSL context */ public void setSslContext(SSLContext sslContext) { this.sslContext = sslContext; } /** Starts the Restlet. */ @Override public void start() throws Exception { // Initialize the SSL context final SslContextFactory sslContextFactory = SslUtils .getSslContextFactory(this); SSLContext sslContext = sslContextFactory.createSslContext(); final String addr = getHelped().getAddress(); if (addr != null) { // This call may throw UnknownHostException and otherwise always // returns an instance of INetAddress. // Note: textual representation of inet addresses are supported final InetAddress iaddr = InetAddress.getByName(addr); // Note: the backlog of 50 is the default setAddress(new InetSocketAddress(iaddr, getHelped().getPort())); } else { int port = getHelped().getPort(); // Use ephemeral port if (port > 0) { setAddress(new InetSocketAddress(getHelped().getPort())); } } // Complete initialization final Container container = new SimpleContainer(this); final ContainerServer server = new ContainerServer(container, getDefaultThreads()); final SimpleServer filter = new SimpleServer(server); final Connection connection = new SocketConnection(filter); setSslContext(sslContext); setConfidential(true); setContainerServer(server); setConnection(connection); InetSocketAddress address = (InetSocketAddress) getConnection() .connect(getAddress(), getSslContext()); setEphemeralPort(address.getPort()); super.start(); } } restlet-2.0.14/org.restlet.ext.simple/src/org/restlet/ext/simple/HttpServerHelper.java0000664000175000017500000000666711757206346031567 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.simple; import java.net.InetAddress; import java.net.InetSocketAddress; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.ext.simple.internal.SimpleContainer; import org.restlet.ext.simple.internal.SimpleServer; import org.simpleframework.transport.connect.Connection; import org.simpleframework.transport.connect.SocketConnection; import org.simpleframework.http.core.Container; import org.simpleframework.http.core.ContainerServer; /** * Simple HTTPS server connector. * * @author Lars Heuer * @author Jerome Louvel */ public class HttpServerHelper extends SimpleServerHelper { /** * Constructor. * * @param server * The server to help. */ public HttpServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTP); } /** Starts the Restlet. */ @Override public void start() throws Exception { final String addr = getHelped().getAddress(); if (addr != null) { // This call may throw UnknownHostException and otherwise always // returns an instance of INetAddress. // Note: textual representation of inet addresses are supported final InetAddress iaddr = InetAddress.getByName(addr); // Note: the backlog of 50 is the default setAddress(new InetSocketAddress(iaddr, getHelped().getPort())); } else { int port = getHelped().getPort(); // Use ephemeral port if (port > 0) { setAddress(new InetSocketAddress(getHelped().getPort())); } } final Container container = new SimpleContainer(this); final ContainerServer server = new ContainerServer(container, getDefaultThreads()); final SimpleServer restletServer = new SimpleServer(server); final Connection connection = new SocketConnection(restletServer); setConfidential(false); setContainerServer(server); setConnection(connection); InetSocketAddress address = (InetSocketAddress) getConnection() .connect(getAddress()); setEphemeralPort(address.getPort()); super.start(); } } restlet-2.0.14/org.restlet.ext.atom/0000775000175000017500000000000012001473151017734 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/pom.xml0000600000175000017500000000171312001473150021240 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.atom Restlet Extension - Atom Support for the Atom syndication and the AtomPub (Atom Publication Protocol) standards in their 1.0 version. org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 restlet-2.0.14/org.restlet.ext.atom/src/0000775000175000017500000000000012001473150020522 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/src/META-INF/0000775000175000017500000000000011757206446021705 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/src/META-INF/services/0000775000175000017500000000000011757206350023522 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.atom/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.atom/src/META-INF/services/org.restlet.engine.converter.ConverterHelp0000664000175000017500000000004211757206350033742 0ustar jamespagejamespageorg.restlet.ext.atom.AtomConverterrestlet-2.0.14/org.restlet.ext.atom/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206444023336 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.atom/src/org/0000775000175000017500000000000011757206350021326 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/src/org/restlet/0000775000175000017500000000000011757206350023010 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/0000775000175000017500000000000011757206350023610 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/0000775000175000017500000000000011757206350024550 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/FeedReader.java0000664000175000017500000002233211757206350027403 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import java.io.IOException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * Content reader for feeds that is able to transmit events to another * FeedReader. * * @author Thierry Boileau */ public class FeedReader extends DefaultHandler { /** Extra feed reader. */ private FeedReader feedReader; /** * Constructor. */ public FeedReader() { super(); } /** * Constructor. * * @param feedReader * Additional feed reader that will receive all events. */ public FeedReader(FeedReader feedReader) { super(); this.feedReader = feedReader; } @Override public void characters(char[] ch, int start, int length) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.characters(ch, start, length); } } /** * Called at the end of the XML block that defines the given content * element. By default, it relays the event to the extra handler. * * @param content * The current content element. */ public void endContent(Content content) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.endContent(content); } } @Override public void endDocument() throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.endDocument(); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.endElement(uri, localName, qName); } } /** * Called at the end of the XML block that defines the given entry. * * @param entry * The current entry. */ public void endEntry(Entry entry) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.endEntry(entry); } } /** * Called at the end of the XML block that defines the given feed. * * @param feed * The current feed. */ public void endFeed(Feed feed) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.endFeed(feed); } } /** * Called at the end of the XML block that defines the given link. * * @param link * The current link. */ public void endLink(Link link) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.endLink(link); } } @Override public void endPrefixMapping(String prefix) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.endPrefixMapping(prefix); } } @Override public void error(SAXParseException e) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.error(e); } } @Override public void fatalError(SAXParseException e) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.fatalError(e); } } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.ignorableWhitespace(ch, start, length); } } @Override public void notationDecl(String name, String publicId, String systemId) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.notationDecl(name, publicId, systemId); } } @Override public void processingInstruction(String target, String data) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.processingInstruction(target, data); } } @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { // Send the event to the extra handler. if (this.feedReader != null) { return this.feedReader.resolveEntity(publicId, systemId); } return null; } @Override public void setDocumentLocator(Locator locator) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.setDocumentLocator(locator); } } @Override public void skippedEntity(String name) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.skippedEntity(name); } } /** * Called when a new content element has been detected in the Atom document. * * @param content * The current content element. */ public void startContent(Content content) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.startContent(content); } } @Override public void startDocument() throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.startDocument(); } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.startElement(uri, localName, qName, attributes); } } /** * Called when a new entry has been detected in the Atom document. * * @param entry * The current entry. */ public void startEntry(Entry entry) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.startEntry(entry); } } /** * Called when a new feed has been detected in the Atom document. * * @param feed * The current feed. */ public void startFeed(Feed feed) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.startFeed(feed); } } /** * Called when a new link has been detected in the Atom document. * * @param link * The current link. */ public void startLink(Link link) { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.startLink(link); } } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.startPrefixMapping(prefix, uri); } } @Override public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.unparsedEntityDecl(name, publicId, systemId, notationName); } } @Override public void warning(SAXParseException e) throws SAXException { // Send the event to the extra handler. if (this.feedReader != null) { this.feedReader.warning(e); } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Person.java0000664000175000017500000001035211757206350026662 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; /** * Element that describes a person, corporation, or similar entity (hereafter, * 'person'). * * @author Jerome Louvel */ public class Person { /** * Email address associated with the person. */ private volatile String email; /** * Human-readable name. */ private volatile String name; /** * IRI associated with the person. */ private volatile Reference uri; /** * Constructor. */ public Person() { this(null, null, null); } /** * Constructor. * * @param name * The name. * @param uri * The URI reference. * @param email * The email address. */ public Person(String name, Reference uri, String email) { this.name = name; this.uri = uri; this.email = email; } /** * Returns the email address associated with the person. * * @return The email address associated with the person. */ public String getEmail() { return this.email; } /** * Returns the human-readable name. * * @return The human-readable name. */ public String getName() { return this.name; } /** * Returns the IRI associated with the person. * * @return The IRI associated with the person. */ public Reference getUri() { return this.uri; } /** * Sets the email address. * * @param email * The email address. */ public void setEmail(String email) { this.email = email; } /** * Sets the human-readable name. * * @param name * The human-readable name. */ public void setName(String name) { this.name = name; } /** * Sets the IRI associated with the person. * * @param uri * The IRI associated with the person. */ public void setUri(Reference uri) { this.uri = uri; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @param localName * The local name of the element. * @throws SAXException */ public void writeElement(XmlWriter writer, String localName) throws SAXException { writer.startElement(ATOM_NAMESPACE, localName); if (getEmail() != null) { writer.dataElement(ATOM_NAMESPACE, "email", getEmail()); } if (getName() != null) { writer.dataElement(ATOM_NAMESPACE, "name", getName()); } if ((getUri() != null) && (getUri().toString() != null)) { writer.dataElement(ATOM_NAMESPACE, "uri", getUri().toString()); } writer.endElement(ATOM_NAMESPACE, localName); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java0000664000175000017500000004101011757206350026252 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.engine.util.DateUtils; import org.restlet.ext.atom.internal.FeedContentReader; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Atom Feed Document, acting as a component for metadata and data associated * with the feed. * * @author Jerome Louvel */ public class Feed extends SaxRepresentation { /** Atom Syndication Format namespace. */ public final static String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; /** XHTML namespace. */ public final static String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; /** The authors of the feed. */ private volatile List authors; /** * The base reference used to resolve relative references found within the * scope of the xml:base attribute. */ private volatile Reference baseReference; /** The categories associated with the feed. */ private volatile List categories; /** The contributors to the feed. */ private volatile List contributors; /** * Individual entries, acting as a components for associated metadata and * data. */ private List entries; /** The agent used to generate a feed. */ private volatile Generator generator; /** Image that provides iconic visual identification for a feed. */ private volatile Reference icon; /** Permanent, universally unique identifier for the feed. */ private volatile String id; /** The references from the entry to Web resources. */ private volatile List links; /** Image that provides visual identification for a feed. */ private volatile Reference logo; /** Information about rights held in and over an entry. */ private volatile Text rights; /** Short summary, abstract, or excerpt of an entry. */ private volatile Text subtitle; /** The human-readable title for the entry. */ private volatile Text title; /** Most recent moment when the entry was modified in a significant way. */ private volatile Date updated; /** * Constructor. */ public Feed() { super(MediaType.APPLICATION_ATOM); setNamespaceAware(true); this.authors = null; this.categories = null; this.contributors = null; this.generator = null; this.icon = null; this.id = null; this.links = null; this.logo = null; this.rights = null; this.subtitle = null; this.title = null; this.updated = null; this.entries = null; } /** * Constructor. * * @param clientDispatcher * The client HTTP dispatcher. * @param feedUri * The feed URI. * @throws IOException */ public Feed(Client clientDispatcher, String feedUri) throws IOException { this(clientDispatcher.handle(new Request(Method.GET, feedUri)) .getEntity()); } /** * Constructor. * * @param context * The context from which the client dispatcher will be * retrieved. * @param feedUri * The feed URI. * @throws IOException */ public Feed(Context context, String feedUri) throws IOException { this(context.getClientDispatcher().handle( new Request(Method.GET, feedUri)).getEntity()); } /** * Constructor. * * @param xmlFeed * The XML feed document. * @throws IOException */ public Feed(Representation xmlFeed) throws IOException { super(xmlFeed); setNamespaceAware(true); parse(new FeedContentReader(this)); } /** * Constructor. * * @param xmlFeed * The XML feed document. * @param feedReader * Custom feed reader. * @throws IOException */ public Feed(Representation xmlFeed, FeedReader feedReader) throws IOException { super(xmlFeed); setNamespaceAware(true); parse(new FeedContentReader(this, feedReader)); } /** * Constructor. * * @param feedUri * The feed URI. * @throws IOException */ public Feed(String feedUri) throws IOException { this(new Client(new Reference(feedUri).getSchemeProtocol()), feedUri); } /** * Returns the authors of the entry. * * @return The authors of the entry. */ public List getAuthors() { // Lazy initialization with double-check. List a = this.authors; if (a == null) { synchronized (this) { a = this.authors; if (a == null) { this.authors = a = new ArrayList(); } } } return a; } /** * Returns the base reference used to resolve relative references found * within the scope of the xml:base attribute. * * @return The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public Reference getBaseReference() { return baseReference; } /** * Returns the categories associated with the entry. * * @return The categories associated with the entry. */ public List getCategories() { // Lazy initialization with double-check. List c = this.categories; if (c == null) { synchronized (this) { c = this.categories; if (c == null) { this.categories = c = new ArrayList(); } } } return c; } /** * Returns the contributors to the entry. * * @return The contributors to the entry. */ public List getContributors() { // Lazy initialization with double-check. List c = this.contributors; if (c == null) { synchronized (this) { c = this.contributors; if (c == null) { this.contributors = c = new ArrayList(); } } } return c; } /** * Returns the individual entries, acting as a components for associated * metadata and data. * * @return The individual entries, acting as a components for associated * metadata and data. */ public List getEntries() { // Lazy initialization with double-check. List e = this.entries; if (e == null) { synchronized (this) { e = this.entries; if (e == null) { this.entries = e = new ArrayList(); } } } return e; } /** * Returns the agent used to generate a feed. * * @return The agent used to generate a feed. */ public Generator getGenerator() { return this.generator; } /** * Returns the image that provides iconic visual identification for a feed. * * @return The image that provides iconic visual identification for a feed. */ public Reference getIcon() { return this.icon; } /** * Returns the permanent, universally unique identifier for the entry. * * @return The permanent, universally unique identifier for the entry. */ public String getId() { return this.id; } /** * Returns the references from the entry to Web resources. * * @return The references from the entry to Web resources. */ public List getLinks() { // Lazy initialization with double-check. List l = this.links; if (l == null) { synchronized (this) { l = this.links; if (l == null) { this.links = l = new ArrayList(); } } } return l; } /** * Returns the image that provides visual identification for a feed. * * @return The image that provides visual identification for a feed. */ public Reference getLogo() { return this.logo; } /** * Returns the information about rights held in and over an entry. * * @return The information about rights held in and over an entry. */ public Text getRights() { return this.rights; } /** * Returns the short summary, abstract, or excerpt of an entry. * * @return The short summary, abstract, or excerpt of an entry. */ public Text getSubtitle() { return this.subtitle; } /** * Returns the human-readable title for the entry. * * @return The human-readable title for the entry. */ public Text getTitle() { return this.title; } /** * Returns the most recent moment when the entry was modified in a * significant way. * * @return The most recent moment when the entry was modified in a * significant way. */ public Date getUpdated() { return this.updated; } /** * Sets the base reference used to resolve relative references found within * the scope of the xml:base attribute. * * @param baseReference * The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public void setBaseReference(Reference baseReference) { this.baseReference = baseReference; } /** * Sets the base URI used to resolve relative references found within the * scope of the xml:base attribute. * * @param baseUri * The base URI used to resolve relative references found within * the scope of the xml:base attribute. */ public void setBaseReference(String baseUri) { setBaseReference(new Reference(baseUri)); } /** * Sets the agent used to generate a feed. * * @param generator * The agent used to generate a feed. */ public void setGenerator(Generator generator) { this.generator = generator; } /** * Sets the image that provides iconic visual identification for a feed. * * @param icon * The image that provides iconic visual identification for a * feed. */ public void setIcon(Reference icon) { this.icon = icon; } /** * Sets the permanent, universally unique identifier for the entry. * * @param id * The permanent, universally unique identifier for the entry. */ public void setId(String id) { this.id = id; } /** * Sets the image that provides visual identification for a feed. * * @param logo * The image that provides visual identification for a feed. */ public void setLogo(Reference logo) { this.logo = logo; } /** * Sets the information about rights held in and over an entry. * * @param rights * The information about rights held in and over an entry. */ public void setRights(Text rights) { this.rights = rights; } /** * Sets the short summary, abstract, or excerpt of an entry. * * @param subtitle * The short summary, abstract, or excerpt of an entry. */ public void setSubtitle(Text subtitle) { this.subtitle = subtitle; } /** * Sets the human-readable title for the entry. * * @param title * The human-readable title for the entry. */ public void setTitle(Text title) { this.title = title; } /** * Sets the most recent moment when the entry was modified in a significant * way. * * @param updated * The most recent moment when the entry was modified in a * significant way. */ public void setUpdated(Date updated) { this.updated = DateUtils.unmodifiable(updated); } /** * Writes the representation to a XML writer. * * @param writer * The XML writer to write to. * @throws IOException */ @Override public void write(XmlWriter writer) throws IOException { try { writer.setPrefix(ATOM_NAMESPACE, ""); writer.setDataFormat(true); writer.setIndentStep(3); writer.startDocument(); writeElement(writer); writer.endDocument(); } catch (SAXException e) { IOException ioe = new IOException( "Unable to write the Atom feed document."); ioe.initCause(e); throw ioe; } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { writer.startElement(ATOM_NAMESPACE, "feed"); if (getAuthors() != null) { for (final Person person : getAuthors()) { person.writeElement(writer, "author"); } } if (getCategories() != null) { for (final Category category : getCategories()) { category.writeElement(writer); } } if (getContributors() != null) { for (final Person person : getContributors()) { person.writeElement(writer, "contributor"); } } if (getGenerator() != null) { getGenerator().writeElement(writer); } if (getIcon() != null) { writer.dataElement(ATOM_NAMESPACE, "icon", getIcon().toString()); } if (getId() != null) { writer.dataElement(ATOM_NAMESPACE, "id", null, new AttributesImpl(), getId()); } if (getLinks() != null) { for (final Link link : getLinks()) { link.writeElement(writer); } } if ((getLogo() != null) && (getLogo().toString() != null)) { writer.dataElement(ATOM_NAMESPACE, "logo", getLogo().toString()); } if (getRights() != null) { getRights().writeElement(writer, "rights"); } if (getSubtitle() != null) { getSubtitle().writeElement(writer, "subtitle"); } if (getTitle() != null) { getTitle().writeElement(writer, "title"); } if (getUpdated() != null) { Text.writeElement(writer, getUpdated(), ATOM_NAMESPACE, "updated"); } if (getEntries() != null) { for (final Entry entry : getEntries()) { entry.writeElement(writer); } } writer.endElement(ATOM_NAMESPACE, "feed"); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java0000664000175000017500000003641611757206350026526 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.engine.util.DateUtils; import org.restlet.ext.atom.internal.EntryContentReader; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.xml.sax.SAXException; /** * Represents an individual entry, acting as a component for metadata and data * associated with the entry. * * @author Jerome Louvel */ public class Entry extends SaxRepresentation { /** The authors of the entry. */ private volatile List authors; /** The categories associated with the entry. */ private volatile List categories; /** Contains or links to the content of the entry. */ private volatile Content content; /** The contributors to the entry. */ private volatile List contributors; /** Permanent, universally unique identifier for the entry. */ private volatile String id; /** The references from the entry to Web resources. */ private volatile List links; /** Moment associated with an event early in the life cycle of the entry. */ private volatile Date published; /** Information about rights held in and over an entry. */ private volatile Text rights; /** Source feed's metadata if the entry was copied from another feed. */ private volatile Source source; /** Short summary, abstract, or excerpt of the entry. */ private volatile String summary; /** The human-readable title for the entry. */ private volatile Text title; /** Most recent moment when the entry was modified in a significant way. */ private volatile Date updated; /** * Constructor. */ public Entry() { super(MediaType.APPLICATION_ATOM); setNamespaceAware(true); this.authors = null; this.categories = null; this.content = null; this.contributors = null; this.id = null; this.links = null; this.published = null; this.rights = null; this.source = null; this.summary = null; this.title = null; this.updated = null; } /** * Constructor. * * @param clientDispatcher * The client HTTP dispatcher. * @param entryUri * The entry URI. * @throws IOException */ public Entry(Client clientDispatcher, String entryUri) throws IOException { this(clientDispatcher.handle(new Request(Method.GET, entryUri)) .getEntity()); } /** * Constructor. * * @param context * The context from which the client dispatcher will be * retrieved. * @param entryUri * The entry URI. * @throws IOException */ public Entry(Context context, String entryUri) throws IOException { this(context.getClientDispatcher().handle( new Request(Method.GET, entryUri)).getEntity()); } /** * Constructor. * * @param xmlEntry * The XML entry document. * @throws IOException */ public Entry(Representation xmlEntry) throws IOException { super(xmlEntry); setNamespaceAware(true); parse(new EntryContentReader(this)); } /** * Constructor. * * @param xmlEntry * The XML entry document. * @param entryReader * Custom entry reader. * @throws IOException */ public Entry(Representation xmlEntry, EntryReader entryReader) throws IOException { super(xmlEntry); setNamespaceAware(true); parse(new EntryContentReader(this, entryReader)); } /** * Constructor. * * @param entryUri * The entry URI. * @throws IOException */ public Entry(String entryUri) throws IOException { this(new Client(new Reference(entryUri).getSchemeProtocol()), entryUri); } /** * Returns the authors of the entry. * * @return The authors of the entry. */ public List getAuthors() { // Lazy initialization with double-check. List a = this.authors; if (a == null) { synchronized (this) { a = this.authors; if (a == null) { this.authors = a = new ArrayList(); } } } return a; } /** * Returns the categories associated with the entry. * * @return The categories associated with the entry. */ public List getCategories() { // Lazy initialization with double-check. List c = this.categories; if (c == null) { synchronized (this) { c = this.categories; if (c == null) { this.categories = c = new ArrayList(); } } } return c; } /** * Returns the content of the entry or links to it. * * @return The content of the entry or links to it. */ public Content getContent() { return this.content; } /** * Returns the contributors to the entry. * * @return The contributors to the entry. */ public List getContributors() { // Lazy initialization with double-check. List c = this.contributors; if (c == null) { synchronized (this) { c = this.contributors; if (c == null) { this.contributors = c = new ArrayList(); } } } return c; } /** * Returns the permanent, universally unique identifier for the entry. * * @return The permanent, universally unique identifier for the entry. */ public String getId() { return this.id; } /** * Returns the first available link with a given relation type. * * @param rel * The relation type to match. * @return The first available link with a given relation type. */ public Link getLink(Relation rel) { Link result = null; Link current = null; for (final Iterator iter = getLinks().iterator(); (result == null) && iter.hasNext();) { current = iter.next(); if (current.getRel() == rel) { result = current; } } return result; } /** * Returns the references from the entry to Web resources. * * @return The references from the entry to Web resources. */ public List getLinks() { // Lazy initialization with double-check. List l = this.links; if (l == null) { synchronized (this) { l = this.links; if (l == null) { this.links = l = new ArrayList(); } } } return l; } /** * Returns the moment associated with an event early in the life cycle of * the entry. * * @return The moment associated with an event early in the life cycle of * the entry. */ public Date getPublished() { return this.published; } /** * Returns the information about rights held in and over an entry. * * @return The information about rights held in and over an entry. */ public Text getRights() { return this.rights; } /** * Returns the source feed's metadata if the entry was copied from another * feed. * * @return The source feed's metadata if the entry was copied from another * feed. */ public Source getSource() { return this.source; } /** * Returns the short summary, abstract, or excerpt of the entry. * * @return The short summary, abstract, or excerpt of the entry. */ public String getSummary() { return this.summary; } /** * Returns the human-readable title for the entry. * * @return The human-readable title for the entry. */ public Text getTitle() { return this.title; } /** * Returns the most recent moment when the entry was modified in a * significant way. * * @return The most recent moment when the entry was modified in a * significant way. */ public Date getUpdated() { return this.updated; } /** * Sets the content of the entry or links to it. * * @param content * The content of the entry or links to it. */ public void setContent(Content content) { this.content = content; } /** * Sets the permanent, universally unique identifier for the entry. * * @param id * The permanent, universally unique identifier for the entry. */ public void setId(String id) { this.id = id; } /** * Sets the moment associated with an event early in the life cycle of the * entry. * * @param published * The moment associated with an event early in the life cycle of * the entry. */ public void setPublished(Date published) { this.published = DateUtils.unmodifiable(published); } /** * Sets the information about rights held in and over an entry. * * @param rights * The information about rights held in and over an entry. */ public void setRights(Text rights) { this.rights = rights; } /** * Sets the source feed's metadata if the entry was copied from another * feed. * * @param source * The source feed's metadata if the entry was copied from * another feed. */ public void setSource(Source source) { this.source = source; } /** * Sets the short summary, abstract, or excerpt of the entry. * * @param summary * The short summary, abstract, or excerpt of the entry. */ public void setSummary(String summary) { this.summary = summary; } /** * Sets the human-readable title for the entry. * * @param title * The human-readable title for the entry. */ public void setTitle(Text title) { this.title = title; } /** * Sets the most recent moment when the entry was modified in a significant * way. * * @param updated * The most recent moment when the entry was modified in a * significant way. */ public void setUpdated(Date updated) { this.updated = DateUtils.unmodifiable(updated); } /** * Writes the representation to a XML writer. * * @param writer * The XML writer to write to. * @throws IOException */ @Override public void write(XmlWriter writer) throws IOException { try { writer.setPrefix(ATOM_NAMESPACE, ""); writer.setDataFormat(true); writer.setIndentStep(3); writer.startDocument(); writeElement(writer); writer.endDocument(); } catch (SAXException e) { IOException ioe = new IOException( "Unable to write the Atom entry document."); ioe.initCause(e); throw ioe; } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { writer.startElement(ATOM_NAMESPACE, "entry"); if (getAuthors() != null) { for (final Person person : getAuthors()) { person.writeElement(writer, "author"); } } if (getCategories() != null) { for (final Category category : getCategories()) { category.writeElement(writer); } } if (getContent() != null) { getContent().writeElement(writer); } if (getContributors() != null) { for (final Person person : getContributors()) { person.writeElement(writer, "contributor"); } } if (getId() != null) { writer.dataElement(ATOM_NAMESPACE, "id", getId()); } if (getLinks() != null) { for (final Link link : getLinks()) { link.writeElement(writer); } } if (getPublished() != null) { Text.writeElement(writer, getPublished(), ATOM_NAMESPACE, "published"); } if (getRights() != null) { getRights().writeElement(writer, "rights"); } if (getSource() != null) { getSource().writeElement(writer); } if (getSummary() != null) { writer.dataElement(ATOM_NAMESPACE, "summary", getSummary()); } if (getTitle() != null) { getTitle().writeElement(writer, "title"); } if (getUpdated() != null) { Text.writeElement(writer, getUpdated(), ATOM_NAMESPACE, "updated"); } writeInlineContent(writer); writer.endElement(ATOM_NAMESPACE, "entry"); } /** * Allow to write extra content inside the entry. The default implementation * does nothing and is intended to be overridden. * * @param writer * The SAX writer. * @throws SAXException */ public void writeInlineContent(XmlWriter writer) throws SAXException { // Do nothing by default. } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/0000775000175000017500000000000011757206350026364 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java0000664000175000017500000004770211757206350033020 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom.internal; import java.io.StringWriter; import java.util.Date; import java.util.Map; import java.util.TreeMap; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.engine.util.DateUtils; import org.restlet.ext.atom.Category; import org.restlet.ext.atom.Content; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.EntryReader; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Link; import org.restlet.ext.atom.Person; import org.restlet.ext.atom.Relation; import org.restlet.ext.atom.Text; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.StringRepresentation; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Content reader for entries. * * @author Jerome Louvel */ public class EntryContentReader extends EntryReader { private enum State { FEED_ENTRY, FEED_ENTRY_AUTHOR, FEED_ENTRY_AUTHOR_EMAIL, FEED_ENTRY_AUTHOR_NAME, FEED_ENTRY_AUTHOR_URI, FEED_ENTRY_CATEGORY, FEED_ENTRY_CONTENT, FEED_ENTRY_CONTRIBUTOR, FEED_ENTRY_ID, FEED_ENTRY_LINK, FEED_ENTRY_PUBLISHED, FEED_ENTRY_RIGHTS, FEED_ENTRY_SOURCE, FEED_ENTRY_SOURCE_AUTHOR, FEED_ENTRY_SOURCE_AUTHOR_EMAIL, FEED_ENTRY_SOURCE_AUTHOR_NAME, FEED_ENTRY_SOURCE_AUTHOR_URI, FEED_ENTRY_SOURCE_CATEGORY, FEED_ENTRY_SOURCE_CONTRIBUTOR, FEED_ENTRY_SOURCE_GENERATOR, FEED_ENTRY_SOURCE_ICON, FEED_ENTRY_SOURCE_ID, FEED_ENTRY_SOURCE_LINK, FEED_ENTRY_SOURCE_LOGO, FEED_ENTRY_SOURCE_RIGHTS, FEED_ENTRY_SOURCE_SUBTITLE, FEED_ENTRY_SOURCE_TITLE, FEED_ENTRY_SOURCE_UPDATED, FEED_ENTRY_SUMMARY, FEED_ENTRY_TITLE, FEED_ENTRY_UPDATED, NONE } /** Buffer for the current text content of the current tag. */ private StringBuilder contentBuffer; /** The media type of the Content (for inline cases). */ private MediaType contentType; /** Mark the Content depth. */ private int contentDepth; /** The currently parsed Category. */ private Category currentCategory; /** The currently parsed Content. */ private Content currentContent; /** The currently parsed XML content writer. */ private XmlWriter currentContentWriter; /** The currently date parsed from the current text content. */ private Date currentDate; /** The currently parsed Entry. */ private Entry currentEntry; /** The currently parsed Link. */ private Link currentLink; /** The currently parsed Person. */ private Person currentPerson; /** The currently parsed Text. */ private Text currentText; /** The current list of prefix mappings. */ private Map prefixMappings; /** The currently state. */ private EntryContentReader.State state; /** * Constructor. * * @param entry * The entry object to update during the parsing. */ public EntryContentReader(Entry entry) { this(entry, null); } /** * Constructor. * * @param entry * The entry object to update during the parsing. * @param extraEntryHandler * Custom handler of all events. */ public EntryContentReader(Entry entry, EntryReader extraEntryHandler) { super(extraEntryHandler); this.state = State.NONE; this.contentDepth = -1; this.currentEntry = entry; this.currentText = null; this.currentDate = null; this.currentLink = null; this.currentPerson = null; this.contentBuffer = null; this.currentCategory = null; this.currentContent = null; this.prefixMappings = new TreeMap(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (this.contentDepth >= 0) { // The content might embed XML elements from various namespaces if (this.currentContentWriter != null) { this.currentContentWriter.characters(ch, start, length); } } else { this.contentBuffer.append(ch, start, length); } super.characters(ch, start, length); } @Override public void endDocument() throws SAXException { this.state = State.NONE; this.contentBuffer = null; super.endDocument(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (this.currentText != null) { this.currentText.setContent(this.contentBuffer.toString()); } if (this.currentDate != null) { final String formattedDate = this.contentBuffer.toString(); final Date parsedDate = DateUtils.parse(formattedDate.trim(), DateUtils.FORMAT_RFC_3339); if (parsedDate != null) { this.currentDate.setTime(parsedDate.getTime()); } else { this.currentDate = null; } } if (contentDepth > 0) { // The content might embed XML elements from various namespaces if (this.currentContentWriter != null) { this.currentContentWriter.endElement(uri, localName, qName); } contentDepth--; } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equals("feed")) { this.state = State.NONE; } else if (localName.equals("title")) { if (this.state == State.FEED_ENTRY_TITLE) { this.currentEntry.setTitle(this.currentText); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_TITLE) { this.currentEntry.getSource().setTitle(this.currentText); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("updated")) { if (this.state == State.FEED_ENTRY_UPDATED) { this.currentEntry.setUpdated(this.currentDate); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_UPDATED) { this.currentEntry.getSource().setUpdated(this.currentDate); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("published")) { if (this.state == State.FEED_ENTRY_PUBLISHED) { this.currentEntry.setPublished(this.currentDate); this.state = State.FEED_ENTRY; } } else if (localName.equals("author")) { if (this.state == State.FEED_ENTRY_AUTHOR) { this.currentEntry.getAuthors().add(this.currentPerson); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_AUTHOR) { this.currentEntry.getSource().getAuthors().add( this.currentPerson); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("name")) { this.currentPerson.setName(this.contentBuffer.toString()); if (this.state == State.FEED_ENTRY_AUTHOR_NAME) { this.state = State.FEED_ENTRY_AUTHOR; } else if (this.state == State.FEED_ENTRY_SOURCE_AUTHOR_NAME) { this.state = State.FEED_ENTRY_SOURCE_AUTHOR; } } else if (localName.equals("id")) { if (this.state == State.FEED_ENTRY_ID) { this.currentEntry.setId(this.contentBuffer.toString()); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_ID) { this.currentEntry.getSource().setId( this.contentBuffer.toString()); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("link")) { if (this.state == State.FEED_ENTRY_LINK) { this.currentEntry.getLinks().add(this.currentLink); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_LINK) { this.currentEntry.getSource().getLinks().add( this.currentLink); this.state = State.FEED_ENTRY_SOURCE; } // Set the inline content, if any if (this.currentContentWriter != null) { String content = this.currentContentWriter.getWriter() .toString().trim(); contentDepth = -1; if ("".equals(content)) { this.currentLink.setContent(null); } else { if (this.currentLink.getType() != null) { currentContent .setInlineContent(new StringRepresentation( content, this.currentLink.getType())); } else { currentContent .setInlineContent(new StringRepresentation( content, contentType)); } } this.currentContentWriter = null; } endLink(this.currentLink); } else if (localName.equalsIgnoreCase("entry")) { this.state = State.NONE; endEntry(this.currentEntry); } else if (localName.equals("category")) { if (this.state == State.FEED_ENTRY_CATEGORY) { this.currentEntry.getCategories().add(this.currentCategory); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_CATEGORY) { this.currentEntry.getSource().getCategories().add( this.currentCategory); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equalsIgnoreCase("content")) { if (this.state == State.FEED_ENTRY_CONTENT) { if (!this.currentEntry.getContent().isExternal()) { String content = this.currentContentWriter.getWriter() .toString().trim(); contentDepth = -1; if ("".equals(content)) { this.currentEntry.setContent(null); } else { currentContent .setInlineContent(new StringRepresentation( content)); } } this.state = State.FEED_ENTRY; } this.currentContentWriter = null; endContent(this.currentContent); } } this.currentText = null; this.currentDate = null; super.endElement(uri, localName, qName); } @Override public void endPrefixMapping(String prefix) throws SAXException { this.prefixMappings.remove(prefix); super.endPrefixMapping(prefix); } /** * Returns a media type from an Atom type attribute. * * @param type * The Atom type attribute. * @return The media type. */ private MediaType getMediaType(String type) { MediaType result = null; if (type == null) { // No type defined } else if (type.equals("text")) { result = MediaType.TEXT_PLAIN; } else if (type.equals("html")) { result = MediaType.TEXT_HTML; } else if (type.equals("xhtml")) { result = MediaType.APPLICATION_XHTML; } else { result = new MediaType(type); } return result; } /** * Initiates the parsing of a mixed content part of the current document. */ private void initiateInlineMixedContent() { this.contentDepth = 0; StringWriter sw = new StringWriter(); currentContentWriter = new XmlWriter(sw); for (String prefix : this.prefixMappings.keySet()) { currentContentWriter.forceNSDecl(this.prefixMappings.get(prefix), prefix); } } @Override public void startDocument() throws SAXException { this.contentBuffer = new StringBuilder(); super.startDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { this.contentBuffer.delete(0, this.contentBuffer.length() + 1); if (this.contentDepth >= 0) { // The content might embed XML elements from various namespaces if (this.currentContentWriter != null) { this.currentContentWriter.startElement(uri, localName, qName, attrs); } this.contentDepth++; } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equals("title")) { startTextElement(attrs); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_TITLE; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_TITLE; } } else if (localName.equals("updated")) { this.currentDate = new Date(); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_UPDATED; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_UPDATED; } } else if (localName.equals("published")) { this.currentDate = new Date(); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_PUBLISHED; } } else if (localName.equals("author")) { this.currentPerson = new Person(); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_AUTHOR; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_AUTHOR; } } else if (localName.equals("name")) { if (this.state == State.FEED_ENTRY_AUTHOR) { this.state = State.FEED_ENTRY_AUTHOR_NAME; } else if (this.state == State.FEED_ENTRY_SOURCE_AUTHOR) { this.state = State.FEED_ENTRY_SOURCE_AUTHOR_NAME; } } else if (localName.equals("id")) { if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_ID; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_ID; } } else if (localName.equals("link")) { this.currentLink = new Link(); this.currentLink.setHref(new Reference(attrs.getValue("", "href"))); this.currentLink.setRel(Relation.valueOf(attrs.getValue("", "rel"))); String type = attrs.getValue("", "type"); if (type != null && type.length() > 0) { this.currentLink.setType(new MediaType(type)); } this.currentLink.setHrefLang(new Language(attrs.getValue("", "hreflang"))); this.currentLink.setTitle(attrs.getValue("", "title")); final String attr = attrs.getValue("", "length"); this.currentLink.setLength((attr == null) ? -1L : Long .parseLong(attr)); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_LINK; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_LINK; } // Glean the content this.currentContent = new Content(); // Content available inline initiateInlineMixedContent(); this.currentLink.setContent(currentContent); startLink(this.currentLink); } else if (localName.equalsIgnoreCase("entry")) { this.state = State.FEED_ENTRY; startEntry(this.currentEntry); } else if (localName.equals("category")) { this.currentCategory = new Category(); this.currentCategory.setTerm(attrs.getValue("", "term")); this.currentCategory.setScheme(new Reference(attrs.getValue("", "scheme"))); this.currentCategory.setLabel(attrs.getValue("", "label")); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_CATEGORY; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_CATEGORY; } } else if (localName.equalsIgnoreCase("content")) { if (this.state == State.FEED_ENTRY) { contentType = getMediaType(attrs.getValue("", "type")); String srcAttr = attrs.getValue("", "src"); this.currentContent = new Content(); if (srcAttr == null) { // Content available inline initiateInlineMixedContent(); } else { // Content available externally this.currentContent.setExternalRef(new Reference( srcAttr)); this.currentContent.setExternalType(contentType); } this.currentEntry.setContent(currentContent); this.state = State.FEED_ENTRY_CONTENT; } startContent(this.currentContent); } } super.startElement(uri, localName, qName, attrs); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { this.prefixMappings.put(prefix, uri); super.startPrefixMapping(prefix, uri); } /** * Receive notification of the beginning of a text element. * * @param attrs * The attributes attached to the element. */ public void startTextElement(Attributes attrs) { this.currentText = new Text(getMediaType(attrs.getValue("", "type"))); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java0000664000175000017500000005703411757206350032561 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom.internal; import java.io.StringWriter; import java.util.Date; import java.util.Map; import java.util.TreeMap; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.engine.util.DateUtils; import org.restlet.ext.atom.Category; import org.restlet.ext.atom.Content; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.FeedReader; import org.restlet.ext.atom.Link; import org.restlet.ext.atom.Person; import org.restlet.ext.atom.Relation; import org.restlet.ext.atom.Text; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.StringRepresentation; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Content reader for feeds. * * @author Thierry Boileau */ public class FeedContentReader extends FeedReader { private enum State { FEED, FEED_AUTHOR, FEED_AUTHOR_EMAIL, FEED_AUTHOR_NAME, FEED_AUTHOR_URI, FEED_CATEGORY, FEED_CONTRIBUTOR, FEED_CONTRIBUTOR_EMAIL, FEED_CONTRIBUTOR_NAME, FEED_CONTRIBUTOR_URI, FEED_ENTRY, FEED_ENTRY_AUTHOR, FEED_ENTRY_AUTHOR_EMAIL, FEED_ENTRY_AUTHOR_NAME, FEED_ENTRY_AUTHOR_URI, FEED_ENTRY_CATEGORY, FEED_ENTRY_CONTENT, FEED_ENTRY_CONTRIBUTOR, FEED_ENTRY_ID, FEED_ENTRY_LINK, FEED_ENTRY_PUBLISHED, FEED_ENTRY_RIGHTS, FEED_ENTRY_SOURCE, FEED_ENTRY_SOURCE_AUTHOR, FEED_ENTRY_SOURCE_AUTHOR_EMAIL, FEED_ENTRY_SOURCE_AUTHOR_NAME, FEED_ENTRY_SOURCE_AUTHOR_URI, FEED_ENTRY_SOURCE_CATEGORY, FEED_ENTRY_SOURCE_CONTRIBUTOR, FEED_ENTRY_SOURCE_GENERATOR, FEED_ENTRY_SOURCE_ICON, FEED_ENTRY_SOURCE_ID, FEED_ENTRY_SOURCE_LINK, FEED_ENTRY_SOURCE_LOGO, FEED_ENTRY_SOURCE_RIGHTS, FEED_ENTRY_SOURCE_SUBTITLE, FEED_ENTRY_SOURCE_TITLE, FEED_ENTRY_SOURCE_UPDATED, FEED_ENTRY_SUMMARY, FEED_ENTRY_TITLE, FEED_ENTRY_UPDATED, FEED_GENERATOR, FEED_ICON, FEED_ID, FEED_LINK, FEED_LOGO, FEED_RIGHTS, FEED_SUBTITLE, FEED_TITLE, FEED_UPDATED, NONE } /** The media type of the Content (for inline cases). */ private MediaType contentType; /** Buffer for the current text content of the current tag. */ private StringBuilder contentBuffer; /** Mark the Content depth. */ private int contentDepth; /** The currently parsed Category. */ private Category currentCategory; /** The currently parsed Content. */ private Content currentContent; /** The currently parsed XML content writer. */ private XmlWriter currentContentWriter; /** The currently date parsed from the current text content. */ private Date currentDate; /** The currently parsed Entry. */ private Entry currentEntry; /** The currently parsed Feed. */ private final Feed currentFeed; /** The currently parsed Link. */ private Link currentLink; /** The currently parsed Person. */ private Person currentPerson; /** The currently parsed Text. */ private Text currentText; /** The current list of prefix mappings. */ private Map prefixMappings; /** The current state. */ private FeedContentReader.State state; /** * Constructor. * * @param feed * The feed object to update during the parsing. */ public FeedContentReader(Feed feed) { this(feed, null); } /** * Constructor. * * @param feed * The feed object to update during the parsing. * @param extraFeedReader * Custom handler of all events. */ public FeedContentReader(Feed feed, FeedReader extraFeedReader) { super(extraFeedReader); this.state = State.NONE; this.currentFeed = feed; this.currentEntry = null; this.currentText = null; this.currentDate = null; this.currentLink = null; this.currentPerson = null; this.contentBuffer = null; this.currentCategory = null; this.currentContent = null; this.prefixMappings = new TreeMap(); this.contentDepth = -1; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (this.contentDepth >= 0) { // The content might embed XML elements from various namespaces if (this.currentContentWriter != null) { this.currentContentWriter.characters(ch, start, length); } } else { this.contentBuffer.append(ch, start, length); } super.characters(ch, start, length); } @Override public void endDocument() throws SAXException { this.state = State.NONE; this.currentEntry = null; this.contentBuffer = null; super.endDocument(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (this.currentText != null) { this.currentText.setContent(this.contentBuffer.toString()); } if (this.currentDate != null) { final String formattedDate = this.contentBuffer.toString(); final Date parsedDate = DateUtils.parse(formattedDate.trim(), DateUtils.FORMAT_RFC_3339); if (parsedDate != null) { this.currentDate.setTime(parsedDate.getTime()); } else { this.currentDate = null; } } if (contentDepth > 0) { // The content might embed XML elements from various namespaces if (this.currentContentWriter != null) { this.currentContentWriter.endElement(uri, localName, qName); } contentDepth--; } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equals("feed")) { this.state = State.NONE; endFeed(this.currentFeed); } else if (localName.equals("title")) { if (this.state == State.FEED_TITLE) { this.currentFeed.setTitle(this.currentText); this.state = State.FEED; } else if (this.state == State.FEED_ENTRY_TITLE) { this.currentEntry.setTitle(this.currentText); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_TITLE) { this.currentEntry.getSource().setTitle(this.currentText); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("summary")) { if (this.state == State.FEED_ENTRY_SUMMARY) { if (this.currentText != null) { this.currentEntry.setSummary(this.currentText .getContent()); } this.state = State.FEED_ENTRY; } } else if (localName.equals("updated")) { if (this.state == State.FEED_UPDATED) { this.currentFeed.setUpdated(this.currentDate); this.state = State.FEED; } else if (this.state == State.FEED_ENTRY_UPDATED) { this.currentEntry.setUpdated(this.currentDate); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_UPDATED) { this.currentEntry.getSource().setUpdated(this.currentDate); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("published")) { if (this.state == State.FEED_ENTRY_PUBLISHED) { this.currentEntry.setPublished(this.currentDate); this.state = State.FEED_ENTRY; } } else if (localName.equals("author")) { if (this.state == State.FEED_AUTHOR) { this.currentFeed.getAuthors().add(this.currentPerson); this.state = State.FEED; } else if (this.state == State.FEED_ENTRY_AUTHOR) { this.currentEntry.getAuthors().add(this.currentPerson); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_AUTHOR) { this.currentEntry.getSource().getAuthors().add( this.currentPerson); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("name")) { this.currentPerson.setName(this.contentBuffer.toString()); if (this.state == State.FEED_AUTHOR_NAME) { this.state = State.FEED_AUTHOR; } else if (this.state == State.FEED_ENTRY_AUTHOR_NAME) { this.state = State.FEED_ENTRY_AUTHOR; } else if (this.state == State.FEED_ENTRY_SOURCE_AUTHOR_NAME) { this.state = State.FEED_ENTRY_SOURCE_AUTHOR; } } else if (localName.equals("id")) { if (this.state == State.FEED_ID) { this.currentFeed.setId(this.contentBuffer.toString()); this.state = State.FEED; } else if (this.state == State.FEED_ENTRY_ID) { this.currentEntry.setId(this.contentBuffer.toString()); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_ID) { this.currentEntry.getSource().setId( this.contentBuffer.toString()); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equals("link")) { if (this.state == State.FEED_LINK) { this.currentFeed.getLinks().add(this.currentLink); this.state = State.FEED; } else if (this.state == State.FEED_ENTRY_LINK) { this.currentEntry.getLinks().add(this.currentLink); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_LINK) { this.currentEntry.getSource().getLinks().add( this.currentLink); this.state = State.FEED_ENTRY_SOURCE; } // Set the inline content, if any if (this.currentContentWriter != null) { String content = this.currentContentWriter.getWriter() .toString().trim(); contentDepth = -1; if ("".equals(content)) { this.currentLink.setContent(null); } else { if (this.currentLink.getType() != null) { currentContent .setInlineContent(new StringRepresentation( content, this.currentLink.getType())); } else { currentContent .setInlineContent(new StringRepresentation( content)); } } this.currentContentWriter = null; } endLink(this.currentLink); } else if (localName.equalsIgnoreCase("entry")) { if (this.state == State.FEED_ENTRY) { this.currentFeed.getEntries().add(this.currentEntry); this.state = State.FEED; } endEntry(this.currentEntry); } else if (localName.equals("category")) { if (this.state == State.FEED_CATEGORY) { this.currentFeed.getCategories().add(this.currentCategory); this.state = State.FEED; } else if (this.state == State.FEED_ENTRY_CATEGORY) { this.currentEntry.getCategories().add(this.currentCategory); this.state = State.FEED_ENTRY; } else if (this.state == State.FEED_ENTRY_SOURCE_CATEGORY) { this.currentEntry.getSource().getCategories().add( this.currentCategory); this.state = State.FEED_ENTRY_SOURCE; } } else if (localName.equalsIgnoreCase("content")) { if (this.state == State.FEED_ENTRY_CONTENT) { if (!this.currentEntry.getContent().isExternal()) { String content = this.currentContentWriter.getWriter() .toString().trim(); contentDepth = -1; if ("".equals(content)) { this.currentEntry.setContent(null); } else { currentContent .setInlineContent(new StringRepresentation( content, contentType)); } } this.state = State.FEED_ENTRY; } this.currentContentWriter = null; endContent(this.currentContent); } } this.currentText = null; this.currentDate = null; super.endElement(uri, localName, qName); } @Override public void endPrefixMapping(String prefix) throws SAXException { this.prefixMappings.remove(prefix); // Send the event to the right extra handler. super.endPrefixMapping(prefix); } /** * Returns a media type from an Atom type attribute. * * @param type * The Atom type attribute. * @return The media type. */ private MediaType getMediaType(String type) { MediaType result = null; if (type == null) { // No type defined } else if (type.equals("text")) { result = MediaType.TEXT_PLAIN; } else if (type.equals("html")) { result = MediaType.TEXT_HTML; } else if (type.equals("xhtml")) { result = MediaType.APPLICATION_XHTML; } else { result = new MediaType(type); } return result; } /** * Initiates the parsing of a mixed content part of the current document. */ private void initiateInlineMixedContent() { this.contentDepth = 0; StringWriter sw = new StringWriter(); currentContentWriter = new XmlWriter(sw); for (String prefix : this.prefixMappings.keySet()) { currentContentWriter.forceNSDecl(this.prefixMappings.get(prefix), prefix); } } @Override public void startDocument() throws SAXException { this.contentBuffer = new StringBuilder(); super.startDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { this.contentBuffer.delete(0, this.contentBuffer.length() + 1); if (this.contentDepth >= 0) { // The content might embed XML elements from various namespaces if (this.currentContentWriter != null) { this.currentContentWriter.startElement(uri, localName, qName, attrs); } this.contentDepth++; } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equals("feed")) { String attr = attrs.getValue("xml:base"); if (attr != null) { this.currentFeed.setBaseReference(new Reference(attr)); } this.state = State.FEED; startFeed(this.currentFeed); } else if (localName.equals("title")) { startTextElement(attrs); if (this.state == State.FEED) { this.state = State.FEED_TITLE; } else if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_TITLE; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_TITLE; } } else if (localName.equals("summary")) { startTextElement(attrs); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_SUMMARY; } } else if (localName.equals("updated")) { this.currentDate = new Date(); if (this.state == State.FEED) { this.state = State.FEED_UPDATED; } else if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_UPDATED; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_UPDATED; } } else if (localName.equals("published")) { this.currentDate = new Date(); if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_PUBLISHED; } } else if (localName.equals("author")) { this.currentPerson = new Person(); if (this.state == State.FEED) { this.state = State.FEED_AUTHOR; } else if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_AUTHOR; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_AUTHOR; } } else if (localName.equals("name")) { if (this.state == State.FEED_AUTHOR) { this.state = State.FEED_AUTHOR_NAME; } else if (this.state == State.FEED_ENTRY_AUTHOR) { this.state = State.FEED_ENTRY_AUTHOR_NAME; } else if (this.state == State.FEED_ENTRY_SOURCE_AUTHOR) { this.state = State.FEED_ENTRY_SOURCE_AUTHOR_NAME; } } else if (localName.equals("id")) { if (this.state == State.FEED) { this.state = State.FEED_ID; } else if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_ID; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_ID; } } else if (localName.equals("link")) { this.currentLink = new Link(); this.currentLink.setHref(new Reference(attrs.getValue("", "href"))); this.currentLink.setRel(Relation.valueOf(attrs.getValue("", "rel"))); String type = attrs.getValue("", "type"); if (type != null && type.length() > 0) { this.currentLink.setType(new MediaType(type)); } this.currentLink.setHrefLang(new Language(attrs.getValue("", "hreflang"))); this.currentLink.setTitle(attrs.getValue("", "title")); final String attr = attrs.getValue("", "length"); this.currentLink.setLength((attr == null) ? -1L : Long .parseLong(attr)); if (this.state == State.FEED) { this.state = State.FEED_LINK; } else if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_LINK; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_LINK; } // Glean the content this.currentContent = new Content(); // Content available inline initiateInlineMixedContent(); this.currentLink.setContent(currentContent); startLink(this.currentLink); } else if (localName.equalsIgnoreCase("entry")) { if (this.state == State.FEED) { this.currentEntry = new Entry(); this.state = State.FEED_ENTRY; } startEntry(this.currentEntry); } else if (localName.equals("category")) { this.currentCategory = new Category(); this.currentCategory.setTerm(attrs.getValue("", "term")); this.currentCategory.setScheme(new Reference(attrs.getValue("", "scheme"))); this.currentCategory.setLabel(attrs.getValue("", "label")); if (this.state == State.FEED) { this.state = State.FEED_CATEGORY; } else if (this.state == State.FEED_ENTRY) { this.state = State.FEED_ENTRY_CATEGORY; } else if (this.state == State.FEED_ENTRY_SOURCE) { this.state = State.FEED_ENTRY_SOURCE_CATEGORY; } } else if (localName.equalsIgnoreCase("content")) { if (this.state == State.FEED_ENTRY) { contentType = getMediaType(attrs.getValue("", "type")); String srcAttr = attrs.getValue("", "src"); this.currentContent = new Content(); if (srcAttr == null) { // Content available inline initiateInlineMixedContent(); } else { // Content available externally this.currentContent.setExternalRef(new Reference( srcAttr)); this.currentContent.setExternalType(contentType); } this.currentEntry.setContent(currentContent); this.state = State.FEED_ENTRY_CONTENT; } startContent(this.currentContent); } } super.startElement(uri, localName, qName, attrs); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { this.prefixMappings.put(prefix, uri); super.startPrefixMapping(prefix, uri); } /** * Receives notification of the beginning of a text element. * * @param attrs * The attributes attached to the element. */ public void startTextElement(Attributes attrs) { this.currentText = new Text(getMediaType(attrs.getValue("", "type"))); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/CategoriesContentReader.java0000664000175000017500000000673111757206350034001 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom.internal; import java.util.ArrayList; import org.restlet.data.Reference; import org.restlet.ext.atom.Categories; import org.restlet.ext.atom.Category; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Service; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Content reader for categories. * * @author Jerome Louvel */ public class CategoriesContentReader extends DefaultHandler { private Categories categories = null; /** * Constructor. * * @param categories * The parent categories. */ public CategoriesContentReader(Categories categories) { this.categories = categories; } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (uri.equalsIgnoreCase(Service.APP_NAMESPACE)) { if (localName.equalsIgnoreCase("categories")) { String attr = attrs.getValue("", "fixed"); this.categories.setFixed((attr == null) ? false : Boolean .parseBoolean(attr)); attr = attrs.getValue("", "scheme"); this.categories.setScheme((attr == null) ? null : new Reference(attr)); } } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equalsIgnoreCase("category")) { Category category = new Category(); if (this.categories.getEntries() == null) { this.categories.setEntries(new ArrayList()); } this.categories.getEntries().add(category); String attr = attrs.getValue("", "term"); category.setTerm((attr == null) ? null : attr); attr = attrs.getValue("", "label"); category.setLabel((attr == null) ? null : attr); attr = attrs.getValue("", "scheme"); category.setScheme((attr == null) ? null : new Reference(attr)); if (category.getScheme() == null) { category.setScheme(this.categories.getScheme()); } } } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/ServiceContentReader.java0000664000175000017500000001751411757206350033315 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom.internal; import java.util.ArrayList; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.atom.Collection; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Service; import org.restlet.ext.atom.Workspace; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Content reader for services. * * @author Thierry Boileau */ public class ServiceContentReader extends DefaultHandler { private final static int IN_ACCEPT = 1; private final static int IN_COLLECTION = 2; private final static int IN_COLLECTION_TITLE = 3; private final static int IN_NONE = 0; private final static int IN_SERVICE = 4; private final static int IN_WORKSPACE = 5; private final static int IN_WORKSPACE_TITLE = 6; private StringBuilder contentBuffer = null; private Collection currentCollection = null; private Service currentService = null; private Workspace currentWorkspace = null; private int state = IN_NONE; /** * Constructor. * * @param service * The parent service. */ public ServiceContentReader(Service service) { this.currentService = service; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if ((this.state == IN_ACCEPT) || (this.state == IN_COLLECTION_TITLE) || (this.state == IN_WORKSPACE_TITLE)) { this.contentBuffer.append(ch, start, length); } } @Override public void endDocument() throws SAXException { this.state = IN_NONE; this.currentWorkspace = null; this.currentCollection = null; this.contentBuffer = null; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (uri.equalsIgnoreCase(Service.APP_NAMESPACE)) { if (localName.equalsIgnoreCase("service")) { this.state = IN_NONE; } else if (localName.equalsIgnoreCase("workspace")) { if (this.state == IN_WORKSPACE) { currentService.getWorkspaces().add(this.currentWorkspace); this.currentWorkspace = null; this.state = IN_SERVICE; } } else if (localName.equalsIgnoreCase("collection")) { if (this.state == IN_COLLECTION) { this.currentWorkspace.getCollections().add( this.currentCollection); this.currentCollection = null; this.state = IN_WORKSPACE; } } else if (localName.equalsIgnoreCase("accept")) { if (this.state == IN_ACCEPT) { List mediaTypes = null; String accept = this.contentBuffer.toString(); if ((accept != null) && (accept.length() > 0)) { String[] acceptTokens = accept.split(","); mediaTypes = new ArrayList(); for (String acceptToken : acceptTokens) { mediaTypes.add(MediaType.valueOf(acceptToken)); } } this.currentCollection.setAccept(mediaTypes); this.state = IN_COLLECTION; } } } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equalsIgnoreCase("title")) { if (this.state == IN_COLLECTION_TITLE) { String title = this.contentBuffer.toString(); this.currentCollection.setTitle(title); this.state = IN_COLLECTION; } else if (this.state == IN_WORKSPACE_TITLE) { String title = this.contentBuffer.toString(); this.currentWorkspace.setTitle(title); this.state = IN_WORKSPACE; } } } } @Override public void startDocument() throws SAXException { this.state = IN_NONE; this.currentWorkspace = null; this.currentCollection = null; this.contentBuffer = null; } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (uri.equalsIgnoreCase(Service.APP_NAMESPACE)) { if (localName.equalsIgnoreCase("service")) { String attr = attrs.getValue("xml:base"); if (attr != null) { this.currentService.setBaseReference(new Reference(attr)); } this.state = IN_SERVICE; } else if (localName.equalsIgnoreCase("workspace")) { if (this.state == IN_SERVICE) { this.currentWorkspace = new Workspace(this.currentService); String attr = attrs.getValue("xml:base"); if (attr != null) { this.currentWorkspace.setBaseReference(new Reference( attr)); } this.state = IN_WORKSPACE; } } else if (localName.equalsIgnoreCase("collection")) { if (this.state == IN_WORKSPACE) { this.currentCollection = new Collection( this.currentWorkspace, attrs.getValue("title"), attrs.getValue("href")); String attr = attrs.getValue("xml:base"); if (attr != null) { this.currentCollection.setBaseReference(new Reference( attr)); } this.state = IN_COLLECTION; } } else if (localName.equalsIgnoreCase("accept")) { if (this.state == IN_COLLECTION) { this.contentBuffer = new StringBuilder(); this.state = IN_ACCEPT; } } } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equalsIgnoreCase("title")) { if (this.state == IN_COLLECTION) { this.contentBuffer = new StringBuilder(); this.state = IN_COLLECTION_TITLE; } else if (this.state == IN_WORKSPACE) { this.contentBuffer = new StringBuilder(); this.state = IN_WORKSPACE_TITLE; } } } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Service.java0000664000175000017500000002224411757206350027017 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.atom.internal.ServiceContentReader; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.xml.sax.SAXException; /** * Represents an Atom introspection document. * * @author Jerome Louvel */ public class Service extends SaxRepresentation { /** Atom Publishing Protocol namespace. */ public static final String APP_NAMESPACE = "http://www.w3.org/2007/app"; /** * The base reference used to resolve relative references found within the * scope of the xml:base attribute. */ private volatile Reference baseReference; /** * The client HTTP dispatcher. */ private volatile Client clientDispatcher; /** * The reference. */ private volatile Reference reference; /** * The list of workspaces. */ private volatile List workspaces; /** * Constructor. * * @param clientDispatcher * The client HTTP dispatcher. */ public Service(Client clientDispatcher) { super(new MediaType("***")); setNamespaceAware(true); this.clientDispatcher = clientDispatcher; } /** * Constructor. * * @param clientDispatcher * The client HTTP dispatcher. * @param serviceUri * The service URI. * @throws IOException */ public Service(Client clientDispatcher, String serviceUri) throws IOException { this(clientDispatcher, serviceUri, clientDispatcher.handle( new Request(Method.GET, serviceUri)).getEntity()); } /** * Constructor. * * @param clientDispatcher * The client HTTP dispatcher. * @param serviceUri * The service URI. * @param xmlService * The XML introspection document. * @throws IOException */ public Service(Client clientDispatcher, String serviceUri, Representation xmlService) throws IOException { super(xmlService); setNamespaceAware(true); this.clientDispatcher = clientDispatcher; this.reference = (serviceUri == null) ? null : new Reference(serviceUri); parse(new ServiceContentReader(this)); } /** * Constructor. * * @param context * The context from which the client dispatcher will be * retrieved. * @param serviceUri * The service URI. * @throws IOException */ public Service(Context context, String serviceUri) throws IOException { this(context.getClientDispatcher(), serviceUri, context .getClientDispatcher().handle( new Request(Method.GET, serviceUri)).getEntity()); } /** * Constructor. * * @param xmlService * The XML introspection document. * @throws IOException */ public Service(Representation xmlService) throws IOException { this(null, null, xmlService); } /** * Constructor. * * @param serviceUri * The service URI. * @throws IOException */ public Service(String serviceUri) throws IOException { this(new Client(new Reference(serviceUri).getSchemeProtocol()), serviceUri); } /** * Constructor. * * @param serviceUri * The service URI. * @param xmlService * The XML introspection document. * @throws IOException */ public Service(String serviceUri, Representation xmlService) throws IOException { this(new Client(new Reference(serviceUri).getSchemeProtocol()), serviceUri, xmlService); } /** * Deletes a resource. * * @param uri * The resource URI. * @return The result status. */ public Status deleteResource(String uri) { return getClientDispatcher().handle(new Request(Method.DELETE, uri)) .getStatus(); } /** * Returns the base reference used to resolve relative references found * within the scope of the xml:base attribute. * * @return The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public Reference getBaseReference() { return baseReference; } /** * Returns the client HTTP dispatcher. * * @return The client HTTP dispatcher. */ public Client getClientDispatcher() { return this.clientDispatcher; } /** * Returns the hypertext reference. * * @return The hypertext reference. */ public Reference getReference() { return this.reference; } /** * Retrieves a resource representation. * * @param uri * The resource URI. * @return The resource representation. */ public Representation getResource(String uri) { return getClientDispatcher().handle(new Request(Method.GET, uri)) .getEntity(); } /** * Returns the list of workspaces. * * @return The list of workspaces. */ public List getWorkspaces() { if (this.workspaces == null) { this.workspaces = new ArrayList(); } return this.workspaces; } /** * Sets the base reference used to resolve relative references found within * the scope of the xml:base attribute. * * @param baseReference * The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public void setBaseReference(Reference baseReference) { this.baseReference = baseReference; } /** * Sets the client HTTP dispatcher. * * @param clientDispatcher * The client HTTP dispatcher. */ public void setClientDispatcher(Client clientDispatcher) { this.clientDispatcher = clientDispatcher; } /** * Sets the hypertext reference. * * @param ref * The hypertext reference. */ public void setReference(Reference ref) { this.reference = ref; } /** * Updates a resource representation. * * @param uri * The resource URI. * @return The resource representation. */ public Status updateResource(String uri, Representation updatedRepresentation) { return getClientDispatcher().handle( new Request(Method.PUT, uri, updatedRepresentation)) .getStatus(); } /** * Writes the representation to a XML writer. * * @param writer * The XML writer to write to. * @throws IOException */ @Override public void write(XmlWriter writer) throws IOException { try { writer.forceNSDecl(APP_NAMESPACE, ""); writer.forceNSDecl(ATOM_NAMESPACE, "atom"); writer.setDataFormat(true); writer.setIndentStep(3); writer.startDocument(); writer.startElement(APP_NAMESPACE, "service"); for (final Workspace workspace : getWorkspaces()) { workspace.writeElement(writer); } writer.endElement(APP_NAMESPACE, "service"); writer.endDocument(); } catch (SAXException se) { throw new IOException("Couldn't write the service representation: " + se.getMessage()); } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/EntryReader.java0000664000175000017500000002121211757206350027635 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import java.io.IOException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * Content reader for entries that is able to transmit events to another * EntryReader. * * @author Thierry Boileau */ public class EntryReader extends DefaultHandler { /** Extra entry reader. */ private EntryReader entryReader; /** * Constructor. */ public EntryReader() { super(); } /** * Constructor. * * @param entryReader * Additional feed reader that will receive all events. */ public EntryReader(EntryReader entryReader) { super(); this.entryReader = entryReader; } @Override public void characters(char[] ch, int start, int length) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.characters(ch, start, length); } } /** * Called at the end of the XML block that defines the given content * element. By default, it relays the event to the extra handler. * * @param content * The current content element. */ public void endContent(Content content) { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.endContent(content); } } @Override public void endDocument() throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.endDocument(); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.endElement(uri, localName, qName); } } /** * Called at the end of the XML block that defines the given entry. * * @param entry * The current entry. */ public void endEntry(Entry entry) { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.endEntry(entry); } } /** * Called at the end of the XML block that defines the given link. * * @param link * The current link. */ public void endLink(Link link) { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.endLink(link); } } @Override public void endPrefixMapping(String prefix) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.endPrefixMapping(prefix); } } @Override public void error(SAXParseException e) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.error(e); } } @Override public void fatalError(SAXParseException e) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.fatalError(e); } } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.ignorableWhitespace(ch, start, length); } } @Override public void notationDecl(String name, String publicId, String systemId) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.notationDecl(name, publicId, systemId); } } @Override public void processingInstruction(String target, String data) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.processingInstruction(target, data); } } @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { // Send the event to the extra handler. if (this.entryReader != null) { return this.entryReader.resolveEntity(publicId, systemId); } return null; } @Override public void setDocumentLocator(Locator locator) { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.setDocumentLocator(locator); } } @Override public void skippedEntity(String name) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.skippedEntity(name); } } /** * Called when a new content element has been detected in the Atom document. * * @param content * The current content element. */ public void startContent(Content content) { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.startContent(content); } } @Override public void startDocument() throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.startDocument(); } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.startElement(uri, localName, qName, attributes); } } /** * Called when a new entry has been detected in the Atom document. * * @param entry * The current entry. */ public void startEntry(Entry entry) { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.startEntry(entry); } } /** * Called when a new link has been detected in the Atom document. * * @param link * The current link. */ public void startLink(Link link) { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.startLink(link); } } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.startPrefixMapping(prefix, uri); } } @Override public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.unparsedEntityDecl(name, publicId, systemId, notationName); } } @Override public void warning(SAXParseException e) throws SAXException { // Send the event to the extra handler. if (this.entryReader != null) { this.entryReader.warning(e); } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/AtomConverter.java0000664000175000017500000001323711757206350030211 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import java.io.IOException; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between the Atom API and Representation classes. * * @author Jerome Louvel */ public class AtomConverter extends ConverterHelper { private static final VariantInfo VARIANT_ATOM = new VariantInfo( MediaType.APPLICATION_ATOM); private static final VariantInfo VARIANT_ATOMPUB_SERVICE = new VariantInfo( MediaType.APPLICATION_ATOMPUB_SERVICE); // private static final Variant VARIANT_ATOMPUB_CATEGORY = new Variant( // MediaType.APPLICATION_ATOMPUB_CATEGORY); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_ATOM.isCompatible(source)) { result = addObjectClass(result, Feed.class); } else if (VARIANT_ATOMPUB_SERVICE.isCompatible(source)) { result = addObjectClass(result, Service.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (Feed.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ATOM); } else if (Service.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ATOMPUB_SERVICE); } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source instanceof Feed) { if (target == null) { result = 0.5F; } else if (MediaType.APPLICATION_ATOM.isCompatible(target .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } else if (source instanceof Service) { if ((target != null) && MediaType.APPLICATION_ATOMPUB_SERVICE .isCompatible(target.getMediaType())) { result = 1.0F; } else { result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (target != null) { if (Feed.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_ATOM.isCompatible(source .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } else if (Service.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_ATOMPUB_SERVICE.isCompatible(source .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } } return result; } @SuppressWarnings("unchecked") @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (Feed.class.isAssignableFrom(target)) { result = new Feed(source); } else if (Service.class.isAssignableFrom(target)) { result = new Service(source); } return (T) result; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; if (source instanceof Feed) { result = (Feed) source; } else if (source instanceof Service) { result = (Service) source; } return result; } @Override public void updatePreferences(List> preferences, Class entity) { if (Feed.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_ATOM, 1.0F); } else if (Service.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_ATOMPUB_SERVICE, 1.0F); } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Categories.java0000664000175000017500000001553711757206350027513 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import static org.restlet.ext.atom.Service.APP_NAMESPACE; import java.io.IOException; import java.util.List; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.ext.atom.internal.CategoriesContentReader; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.xml.sax.SAXException; /** * Collection of {@link Category} entries. * * @author Jerome Louvel */ public class Categories extends SaxRepresentation { /** * The base reference used to resolve relative references found within the * scope of the xml:base attribute. */ private volatile Reference baseReference; /** * The list of entries. */ private volatile List entries; /** Indicates if the list is fixed. */ private boolean fixed; /** */ private Reference scheme; /** * Constructor. * * @param clientDispatcher * The client HTTP dispatcher. * @param categoriesUri * The feed URI. * @throws IOException */ public Categories(Client clientDispatcher, String categoriesUri) throws IOException { this(clientDispatcher.handle(new Request(Method.GET, categoriesUri)) .getEntity()); } /** * Constructor. * * @param context * The context from which the client dispatcher will be * retrieved. * @param categoriesUri * The feed URI. * @throws IOException */ public Categories(Context context, String categoriesUri) throws IOException { this(context.getClientDispatcher().handle( new Request(Method.GET, categoriesUri)).getEntity()); } /** * Constructor. * * @param categoriesFeed * The XML entries document. * @throws IOException */ public Categories(Representation categoriesFeed) throws IOException { super(categoriesFeed); setNamespaceAware(true); parse(new CategoriesContentReader(this)); } /** * Constructor. * * @param categoriesUri * The feed URI. * @throws IOException */ public Categories(String categoriesUri) throws IOException { this(new Client(new Reference(categoriesUri).getSchemeProtocol()), categoriesUri); } /** * Returns the base reference used to resolve relative references found * within the scope of the xml:base attribute. * * @return The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public Reference getBaseReference() { return baseReference; } /** * Returns the list of entries. * * @return The list of entries. */ public List getEntries() { return entries; } /** * Returns the scheme. * * @return The scheme. */ public Reference getScheme() { return this.scheme; } /** * Indicates if the list is fixed. * * @return True if the list is fixed. */ public boolean isFixed() { return fixed; } /** * Sets the base reference used to resolve relative references found within * the scope of the xml:base attribute. * * @param baseReference * The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public void setBaseReference(Reference baseReference) { this.baseReference = baseReference; } /** * Sets the list of entries. * * @param entries * The list of entries. */ public void setEntries(List entries) { this.entries = entries; } /** * Indicates if the list is fixed. * * @param fixed * True if the list is fixed. */ public void setFixed(boolean fixed) { this.fixed = fixed; } /** * Sets the scheme. * * @param scheme * The scheme. */ public void setScheme(Reference scheme) { this.scheme = scheme; } /** * Writes the representation to a XML writer. * * @param writer * The XML writer to write to. * @throws IOException */ @Override public void write(XmlWriter writer) throws IOException { try { writer.setPrefix(APP_NAMESPACE, ""); writer.setPrefix(ATOM_NAMESPACE, "atom"); writer.setDataFormat(true); writer.setIndentStep(3); writer.startDocument(); writeElement(writer); writer.endDocument(); } catch (SAXException e) { IOException ioe = new IOException( "Unable to write the AtomPub categories document."); ioe.initCause(e); throw ioe; } } /** * Writes the representation to a XML writer. * * @param writer * The XML writer to write to. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { writer.startElement(APP_NAMESPACE, "categories"); for (final Category entry : getEntries()) { entry.writeElement(writer); } writer.endElement(APP_NAMESPACE, "categories"); writer.endDocument(); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/package.html0000664000175000017500000000035411757206350027033 0ustar jamespagejamespage Support for the Atom syndication and the AtomPub (Atom Publication Protocol) standards in their 1.0 version. @since Restlet 1.1 @see Atom Enabled consortium restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Category.java0000664000175000017500000001020011757206350027161 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Conveys information about a category associated with an entry or feed. * * @author Jerome Louvel */ public class Category { /** The human-readable label for display in end-user applications. */ private volatile String label; /** The IRI that identifies a categorization scheme. */ private volatile Reference scheme; /** The identifier term. */ private volatile String term; /** * Constructor. */ public Category() { this(null, null, null); } /** * Constructor. * * @param label * The identifier term. * @param scheme * The IRI that identifies a categorization scheme. * @param term * The human-readable label for display in end-user applications. */ public Category(String label, Reference scheme, String term) { this.label = label; this.scheme = scheme; this.term = term; } /** * Returns the label. * * @return The label. */ public String getLabel() { return this.label; } /** * Returns the scheme. * * @return The scheme. */ public Reference getScheme() { return this.scheme; } /** * Returns the term. * * @return The term. */ public String getTerm() { return this.term; } /** * Sets the label. * * @param label * The label. */ public void setLabel(String label) { this.label = label; } /** * Sets the scheme. * * @param scheme * The scheme. */ public void setScheme(Reference scheme) { this.scheme = scheme; } /** * Sets the term. * * @param term * The term. */ public void setTerm(String term) { this.term = term; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if (getLabel() != null) { attributes.addAttribute("", "label", null, "text", getLabel()); } if ((getScheme() != null) && (getScheme().toString() != null)) { attributes.addAttribute("", "scheme", null, "atomURI", getScheme() .toString()); } if (getTerm() != null) { attributes.addAttribute("", "term", null, "text", getTerm()); } writer.emptyElement(ATOM_NAMESPACE, "category", null, attributes); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Collection.java0000664000175000017500000002057011757206350027512 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import static org.restlet.ext.atom.Service.APP_NAMESPACE; import java.util.List; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Atom Protocol collection, part of a workspace. * * @author Jerome Louvel */ public class Collection { /** * The accepted media types. */ private volatile List accept; /** * The base reference used to resolve relative references found within the * scope of the xml:base attribute. */ private volatile Reference baseReference; /** The categories. */ private volatile Categories categories; /** * The hypertext reference. */ private volatile Reference href; /** * The title. */ private volatile String title; /** * The parent workspace. */ private volatile Workspace workspace; /** * Constructor. * * @param workspace * The parent workspace. * @param title * The title. * @param href * The hypertext reference. */ public Collection(Workspace workspace, String title, String href) { this.workspace = workspace; this.title = title; this.href = new Reference(href); this.accept = null; this.categories = null; } /** * Returns the accepted media types. * * @return The accepted media types. */ public List getAccept() { return this.accept; } /** * Returns the base reference used to resolve relative references found * within the scope of the xml:base attribute. * * @return The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public Reference getBaseReference() { return baseReference; } /** * Returns the categories. * * @return The categories. */ public Categories getCategories() { return categories; } /** * Returns the feed representation. * * @return The feed representation. * @throws Exception */ public Feed getFeed() throws Exception { final Reference feedRef = getHref(); if (feedRef.isRelative()) { feedRef.setBaseRef(getWorkspace().getService().getReference()); } final Request request = new Request(Method.GET, feedRef.getTargetRef()); final Response response = getWorkspace().getService() .getClientDispatcher().handle(request); if (response.getStatus().equals(Status.SUCCESS_OK)) { return new Feed(response.getEntity()); } throw new Exception( "Couldn't get the feed representation. Status returned: " + response.getStatus()); } /** * Returns the hypertext reference. * * @return The hypertext reference. */ public Reference getHref() { return this.href; } /** * Returns the title. * * @return The title. */ public String getTitle() { return this.title; } /** * Returns the parent workspace. * * @return The parent workspace. */ public Workspace getWorkspace() { return this.workspace; } /** * Posts a member to the collection resulting in the creation of a new * resource. * * @param member * The member representation to post. * @return The reference of the new resource. * @throws Exception */ public Reference postMember(Representation member) throws Exception { final Request request = new Request(Method.POST, getHref(), member); final Response response = getWorkspace().getService() .getClientDispatcher().handle(request); if (response.getStatus().equals(Status.SUCCESS_CREATED)) { return response.getLocationRef(); } throw new Exception( "Couldn't post the member representation. Status returned: " + response.getStatus()); } /** * Sets the accepted media types. * * @param accept * The accepted media types. */ public void setAccept(List accept) { this.accept = accept; } /** * Sets the base reference used to resolve relative references found within * the scope of the xml:base attribute. * * @param baseReference * The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public void setBaseReference(Reference baseReference) { this.baseReference = baseReference; } /** * Sets the categories. * * @param categories * The categories. */ public void setCategories(Categories categories) { this.categories = categories; } /** * Sets the hypertext reference. * * @param href * The hypertext reference. */ public void setHref(Reference href) { this.href = href; } /** * Sets the title. * * @param title * The title. */ public void setTitle(String title) { this.title = title; } /** * Sets the parent workspace. * * @param workspace * The parent workspace. */ public void setWorkspace(Workspace workspace) { this.workspace = workspace; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getHref() != null) && (getHref().toString() != null)) { attributes.addAttribute("", "href", null, "atomURI", getHref() .toString()); } writer.startElement(APP_NAMESPACE, "collection", null, attributes); if (getTitle() != null) { writer.dataElement(ATOM_NAMESPACE, "title", getTitle()); } if (getAccept() != null) { StringBuilder sb = new StringBuilder(); for (MediaType mediaType : getAccept()) { if (sb.length() > 0) { sb.append(", "); } sb.append(mediaType.toString()); } writer.dataElement(APP_NAMESPACE, "accept", sb.toString()); } try { if (getCategories() != null) { getCategories().writeElement(writer); } } catch (Exception e) { e.printStackTrace(); } writer.endElement(APP_NAMESPACE, "collection"); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Link.java0000664000175000017500000001647411757206350026324 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Defines a reference from an entry or feed to a Web resource. * * @author Jerome Louvel */ public class Link { /** Contains or links to the content of the entry. */ private volatile Content content; /** The link's IRI. */ private volatile Reference href; /** Language of the resource pointed to by the href attribute. */ private volatile Language hrefLang; /** Advisory length of the linked content in octets. */ private volatile long length; /** The link's relation type. */ private volatile Relation rel; /** Human-readable information about the link. */ private volatile String title; /** Advisory media type. */ private volatile MediaType type; /** * Constructor. */ public Link() { this.content = null; this.href = null; this.rel = null; this.type = null; this.hrefLang = null; this.title = null; this.length = -1; } /** * Constructor. * * @param href * The link's IRI. * @param rel * The link's relation type. * @param type * Advisory media type. */ public Link(Reference href, Relation rel, MediaType type) { super(); this.href = href; this.rel = rel; this.type = type; } /** * Returns the content of the entry or links to it. * * @return The content of the entry or links to it. */ public Content getContent() { return this.content; } /** * Returns the link's IRI. * * @return The link's IRI. */ public Reference getHref() { return this.href; } /** * Returns the language of the resource pointed to by the href attribute. * * @return The language of the resource pointed to by the href attribute. */ public Language getHrefLang() { return this.hrefLang; } /** * Returns the advisory length of the linked content in octets. * * @return The advisory length of the linked content in octets. */ public long getLength() { return this.length; } /** * Returns the link's relation type. * * @return The link's relation type. */ public Relation getRel() { return this.rel; } /** * Returns the human-readable information about the link. * * @return The human-readable information about the link. */ public String getTitle() { return this.title; } /** * Returns the advisoty media type. * * @return The advisoty media type. */ public MediaType getType() { return this.type; } /** * Sets the content of the entry or links to it. * * @param content * The content of the entry or links to it. */ public void setContent(Content content) { this.content = content; } /** * Sets the link's IRI. * * @param href * The link's IRI. */ public void setHref(Reference href) { this.href = href; } /** * Sets the language of the resource pointed to by the href attribute. * * @param hrefLang * The language of the resource pointed to by the href attribute. */ public void setHrefLang(Language hrefLang) { this.hrefLang = hrefLang; } /** * Sets the advisory length of the linked content in octets. * * @param length * The advisory length of the linked content in octets. */ public void setLength(long length) { this.length = length; } /** * Sets the link's relation type. * * @param rel * The link's relation type. */ public void setRel(Relation rel) { this.rel = rel; } /** * Sets the human-readable information about the link. * * @param title * The human-readable information about the link. */ public void setTitle(String title) { this.title = title; } /** * Sets the advisoty media type. * * @param type * The advisoty media type. */ public void setType(MediaType type) { this.type = type; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { AttributesImpl attributes = new AttributesImpl(); if ((getHref() != null) && (getHref().toString() != null)) { attributes.addAttribute("", "href", null, "atomURI", getHref() .toString()); } if ((getHrefLang() != null) && (getHrefLang().toString() != null)) { attributes.addAttribute("", "hreflang", null, "atomLanguageTag", getHrefLang().toString()); } if (getLength() > 0) { attributes.addAttribute("", "length", null, "text", Long .toString(getLength())); } attributes.addAttribute("", "rel", null, "text", Relation .toString(getRel())); if (getTitle() != null) { attributes.addAttribute("", "title", null, "text", getTitle()); } if (getType() != null) { attributes.addAttribute("", "type", null, "atomMediaType", getType().toString()); } if (getContent() != null) { writer.startElement(ATOM_NAMESPACE, "link", null, attributes); getContent().writeElement(writer); writer.endElement(ATOM_NAMESPACE, "link"); } else { writer.emptyElement(ATOM_NAMESPACE, "link", null, attributes); } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Source.java0000664000175000017500000002615611757206350026665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.restlet.data.Reference; import org.restlet.engine.util.DateUtils; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; /** * Source feed's metadata for entries copied from another feed. * * @author Jerome Louvel */ public class Source { /** The authors of the entry. */ private volatile List authors; /** The categories associated with the entry. */ private volatile List categories; /** The contributors to the entry. */ private volatile List contributors; /** The agent used to generate a feed. */ private volatile Generator generator; /** Image that provides iconic visual identification for a feed. */ private volatile Reference icon; /** Permanent, universally unique identifier for the entry. */ private volatile String id; /** The references from the entry to Web resources. */ private volatile List links; /** Image that provides visual identification for a feed. */ private volatile Reference logo; /** Information about rights held in and over an entry. */ private volatile Text rights; /** Short summary, abstract, or excerpt of an entry. */ private volatile Text subtitle; /** The human-readable title for the entry. */ private volatile Text title; /** Most recent moment when the entry was modified in a significant way. */ private volatile Date updated; /** * Constructor. */ public Source() { this.authors = null; this.categories = null; this.contributors = null; this.generator = null; this.icon = null; this.id = null; this.links = null; this.logo = null; this.rights = null; this.subtitle = null; this.title = null; this.updated = null; } /** * Returns the authors of the entry. * * @return The authors of the entry. */ public List getAuthors() { // Lazy initialization with double-check. List a = this.authors; if (a == null) { synchronized (this) { a = this.authors; if (a == null) { this.authors = a = new ArrayList(); } } } return a; } /** * Returns the categories associated with the entry. * * @return The categories associated with the entry. */ public List getCategories() { // Lazy initialization with double-check. List c = this.categories; if (c == null) { synchronized (this) { c = this.categories; if (c == null) { this.categories = c = new ArrayList(); } } } return c; } /** * Returns the contributors to the entry. * * @return The contributors to the entry. */ public List getContributors() { // Lazy initialization with double-check. List c = this.contributors; if (c == null) { synchronized (this) { c = this.contributors; if (c == null) { this.contributors = c = new ArrayList(); } } } return c; } /** * Returns the agent used to generate a feed. * * @return The agent used to generate a feed. */ public Generator getGenerator() { return this.generator; } /** * Returns the image that provides iconic visual identification for a feed. * * @return The image that provides iconic visual identification for a feed. */ public Reference getIcon() { return this.icon; } /** * Returns the permanent, universally unique identifier for the entry. * * @return The permanent, universally unique identifier for the entry. */ public String getId() { return this.id; } /** * Returns the references from the entry to Web resources. * * @return The references from the entry to Web resources. */ public List getLinks() { // Lazy initialization with double-check. List l = this.links; if (l == null) { synchronized (this) { l = this.links; if (l == null) { this.links = l = new ArrayList(); } } } return l; } /** * Returns the image that provides visual identification for a feed. * * @return The image that provides visual identification for a feed. */ public Reference getLogo() { return this.logo; } /** * Returns the information about rights held in and over an entry. * * @return The information about rights held in and over an entry. */ public Text getRights() { return this.rights; } /** * Returns the short summary, abstract, or excerpt of an entry. * * @return The short summary, abstract, or excerpt of an entry. */ public Text getSubtitle() { return this.subtitle; } /** * Returns the human-readable title for the entry. * * @return The human-readable title for the entry. */ public Text getTitle() { return this.title; } /** * Returns the most recent moment when the entry was modified in a * significant way. * * @return The most recent moment when the entry was modified in a * significant way. */ public Date getUpdated() { return this.updated; } /** * Sets the agent used to generate a feed. * * @param generator * The agent used to generate a feed. */ public void setGenerator(Generator generator) { this.generator = generator; } /** * Sets the image that provides iconic visual identification for a feed. * * @param icon * The image that provides iconic visual identification for a * feed. */ public void setIcon(Reference icon) { this.icon = icon; } /** * Sets the permanent, universally unique identifier for the entry. * * @param id * The permanent, universally unique identifier for the entry. */ public void setId(String id) { this.id = id; } /** * Sets the image that provides visual identification for a feed. * * @param logo * The image that provides visual identification for a feed. */ public void setLogo(Reference logo) { this.logo = logo; } /** * Sets the information about rights held in and over an entry. * * @param rights * The information about rights held in and over an entry. */ public void setRights(Text rights) { this.rights = rights; } /** * Sets the short summary, abstract, or excerpt of an entry. * * @param subtitle * The short summary, abstract, or excerpt of an entry. */ public void setSubtitle(Text subtitle) { this.subtitle = subtitle; } /** * Sets the human-readable title for the entry. * * @param title * The human-readable title for the entry. */ public void setTitle(Text title) { this.title = title; } /** * Sets the most recent moment when the entry was modified in a significant * way. * * @param updated * The most recent moment when the entry was modified in a * significant way. */ public void setUpdated(Date updated) { this.updated = DateUtils.unmodifiable(updated); } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { writer.startElement(ATOM_NAMESPACE, "source"); if (getAuthors() != null) { for (final Person person : getAuthors()) { person.writeElement(writer, "author"); } } if (getCategories() != null) { for (final Category category : getCategories()) { category.writeElement(writer); } } if (getContributors() != null) { for (final Person person : getContributors()) { person.writeElement(writer, "contributor"); } } if (getGenerator() != null) { getGenerator().writeElement(writer); } if ((getIcon() != null) && (getIcon().toString() != null)) { writer.dataElement(ATOM_NAMESPACE, "icon", getIcon().toString()); } if (getId() != null) { writer.dataElement(ATOM_NAMESPACE, "id", getId()); } if (getLinks() != null) { for (final Link link : getLinks()) { link.writeElement(writer); } } if ((getLogo() != null) && (getLogo().toString() != null)) { writer.dataElement(ATOM_NAMESPACE, "logo", getLogo().toString()); } if (getRights() != null) { getRights().writeElement(writer, "rights"); } if (getSubtitle() != null) { getSubtitle().writeElement(writer, "subtitle"); } if (getTitle() != null) { getTitle().writeElement(writer, "title"); } if (getUpdated() != null) { Text.writeElement(writer, getUpdated(), ATOM_NAMESPACE, "updated"); } writer.endElement(ATOM_NAMESPACE, "source"); } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Generator.java0000664000175000017500000001100611757206350027337 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Identifies the agent used to generate a feed, for debugging and other * purposes. * * @author Jerome Louvel */ public class Generator { /** Human-readable name for the generating agent. */ private volatile String name; /** Reference of the generating agent. */ private volatile Reference uri; /** Version of the generating agent. */ private volatile String version; /** * Constructor. */ public Generator() { this(null, null, null); } /** * Constructor. * * @param name * Human-readable name for the generating agent. * @param uri * Reference of the generating agent. * @param version * Version of the generating agent. */ public Generator(String name, Reference uri, String version) { this.uri = uri; this.version = version; this.name = name; } /** * Returns the human-readable name for the generating agent. * * @return The human-readable name for the generating agent. */ public String getName() { return this.name; } /** * Returns the reference of the generating agent. * * @return The reference of the generating agent. */ public Reference getUri() { return this.uri; } /** * Returns the version of the generating agent. * * @return The version of the generating agent. */ public String getVersion() { return this.version; } /** * Sets the human-readable name for the generating agent. * * @param name * The human-readable name for the generating agent. */ public void setName(String name) { this.name = name; } /** * Sets the reference of the generating agent. * * @param uri * The reference of the generating agent. */ public void setUri(Reference uri) { this.uri = uri; } /** * Sets the version of the generating agent. * * @param version * The version of the generating agent. */ public void setVersion(String version) { this.version = version; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getUri() != null) && (getUri().toString() != null)) { attributes.addAttribute("", "uri", null, "atomURI", getUri() .toString()); } if (getVersion() != null) { attributes.addAttribute("", "version", null, "text", getVersion()); } if (getName() != null) { writer.dataElement(ATOM_NAMESPACE, "generator", null, attributes, getName()); } else { writer.emptyElement(ATOM_NAMESPACE, "generator", null, attributes); } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Content.java0000664000175000017500000001574211757206350027036 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Either contains or links to the content of the entry. * * @author Jerome Louvel */ public class Content { /** Reference to the external representation. */ private volatile Reference externalRef; /** Expected media type of the external content. */ private volatile MediaType externalType; /** Representation for inline content. */ private volatile Representation inlineContent; /** Must the content be encoded or not? */ private boolean toEncode; /** * Constructor. */ public Content() { this.inlineContent = null; this.externalRef = null; this.externalType = null; this.toEncode = true; } /** * Returns the reference to the external representation. * * @return The reference to the external representation. */ public Reference getExternalRef() { return this.externalRef; } /** * Returns the expected media type of the external content. * * @return The expected media type of the external content. */ public MediaType getExternalType() { return this.externalType; } /** * Returns the representation for inline content. * * @return The representation for inline content. */ public Representation getInlineContent() { return this.inlineContent; } /** * Indicates if the content is available externally. * * @return True if the content is available externally. */ public boolean isExternal() { return (this.externalRef != null); } /** * Indicates if the content is available inline. * * @return True if the content is available inline. */ public boolean isInline() { return (this.inlineContent != null); } /** * Returns true if the content is to be encoded. * * @return True if the content is to be encoded. */ public boolean isToEncode() { return toEncode; } /** * Sets the reference to the external representation. * * @param externalRef * The reference to the external representation. */ public void setExternalRef(Reference externalRef) { this.externalRef = externalRef; } /** * Sets the expected media type of the external content. * * @param externalType * The expected media type of the external content. */ public void setExternalType(MediaType externalType) { this.externalType = externalType; } /** * Sets the representation for inline content. * * @param inlineContent * The representation for inline content. */ public void setInlineContent(Representation inlineContent) { this.inlineContent = inlineContent; } /** * Indicates if the content is to be encoded. * * @param toEncode * True if the content is to be encoded. */ public void setToEncode(boolean toEncode) { this.toEncode = toEncode; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); String strContent = null; if (getInlineContent() != null) { final MediaType mediaType = getInlineContent().getMediaType(); String type = null; if ((mediaType != null) && (mediaType.getSubType() != null)) { if (mediaType.getSubType().contains("xhtml")) { type = "xhtml"; } else if (mediaType.getSubType().contains("html")) { type = "html"; } else { type = mediaType.getName(); } } if (type == null) { type = "text"; } attributes.addAttribute("", "type", null, "text", type); try { strContent = getInlineContent().getText(); } catch (IOException e) { e.printStackTrace(); } } else { if ((getExternalType() != null) && (getExternalType().toString() != null)) { attributes.addAttribute("", "type", null, "atomMediaType", getExternalType().toString()); } if ((getExternalRef() != null) && (getExternalRef().toString() != null)) { attributes.addAttribute("", "src", null, "atomURI", getExternalRef().toString()); } } if (strContent == null) { writer.emptyElement(ATOM_NAMESPACE, "content", null, attributes); } else { if (isToEncode()) { writer.dataElement(ATOM_NAMESPACE, "content", null, attributes, strContent); } else { writer .startElement(ATOM_NAMESPACE, "content", null, attributes); try { writer.getWriter().write(strContent); } catch (IOException e) { throw new SAXException(e); } writer.endElement(ATOM_NAMESPACE, "content", null); } } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Text.java0000664000175000017500000001207011757206350026337 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import java.util.Date; import org.restlet.data.MediaType; import org.restlet.engine.util.DateUtils; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * A Text construct contains human-readable text, usually in small quantities. * The content of Text constructs is Language-Sensitive. * * @author Jerome Louvel */ public class Text { /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @param namespace * The element namespace URI. * @param localName * The local name of the element. * @throws SAXException */ public static void writeElement(XmlWriter writer, Date date, String namespace, String localName) throws SAXException { if (date != null) { writer.startElement(namespace, localName); writer.characters(DateUtils.format(date, DateUtils.FORMAT_RFC_3339 .get(0))); writer.endElement(namespace, localName); } else { writer.emptyElement(namespace, localName); } } /** * The content. */ private volatile String content; /** * The content type. */ private volatile MediaType type; /** * Constructor. * * @param type * The content type. */ public Text(MediaType type) { this(type, null); } /** * Constructor. * * @param type * The content type. * @param content * The content. */ public Text(MediaType type, String content) { this.type = type; this.content = content; } /** * Constructor. * * @param content * The content. */ public Text(String content) { this(null, content); } /** * Returns the content. * * @return The content. */ public String getContent() { return this.content; } /** * Returns the content type. * * @return The content type. */ public MediaType getType() { return this.type; } /** * Sets the content. * * @param content * The content. */ public void setContent(String content) { this.content = content; } /** * Sets the content type. * * @param type * The content type. */ public void setType(MediaType type) { this.type = type; } @Override public String toString() { return getContent(); } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @param localName * The local name of the element. * @throws SAXException */ public void writeElement(XmlWriter writer, String localName) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); String type = null; if ((getType() != null) && (getType().getSubType() != null)) { if (getType().getSubType().contains("xhtml")) { type = "xhtml"; } else if (getType().getSubType().contains("html")) { type = "html"; } } if (type == null) { type = "text"; } attributes.addAttribute("", "type", null, "text", type); if (getContent() != null) { writer.dataElement(ATOM_NAMESPACE, localName, null, attributes, getContent()); } else { writer.emptyElement(ATOM_NAMESPACE, localName, null, attributes); } } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Relation.java0000664000175000017500000003120111757206350027165 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; /** * Enumeration of relation types. * * @author Jerome Louvel * @see IANA * Atom relations */ public class Relation { /** * Signifies that the IRI in the value of the href attribute identifies an * alternate version of the resource described by the containing element. */ public static final Relation ALTERNATE = new Relation("alternate"); /** * Signifies that the IRI returns a feed document containing the most recent * entries in the feed. */ public static final Relation CURRENT = new Relation("current"); /** * Relationship that asserts that resource B provides a description of * resource A. There are no constraints on the format or representation of * either A or B, neither are there any further constraints on either * resource. */ public static final Relation DESCRIBED_BY = new Relation("describedby"); /** * Signifies that the IRI in the value of the href attribute identifies a * resource that is able to edit the current resource. */ public static final Relation EDIT = new Relation("edit"); /** * An IRI of an editable Media Resource. When appearing within an * atom:entry, the href IRI can be used to retrieve, update and delete the * Media Resource associated with that Entry. */ public static final Relation EDIT_MEDIA = new Relation("edit-media"); /** * Signifies that the IRI in the value of the href attribute identifies a * related resource that is potentially large in size and might require * special handling. For atom:link elements with rel="enclosure", the length * attribute SHOULD be provided. */ public static final Relation ENCLOSURE = new Relation("enclosure"); /** * Signifies that the IRI in the value of the href attribute identifies the * first resource in a series including the current resource. */ public static final Relation FIRST = new Relation("first"); /** * A URI for a hub that enables registration for real-time updates to the * resource. */ public static final Relation HUB = new Relation("hub"); /** * Signifies that the IRI in the value of the href attribute identifies the * last resource in a series including the current resource. */ public static final Relation LAST = new Relation("last"); /** * When included on a versioned resource, this link points to a resource * containing the latest (e.g., current) version. The latest version is * defined by the system. For linear versioning systems, this is probably * the latest version by timestamp. For systems that support branching, * there will be multiple latest versions, one for each branch in the * version history. Some systems may allow multiple of these link relations. */ public static final Relation LAST_VERSION = new Relation("latest-version"); /** * Signifies that the IRI in the value of the href attribute identifies the * resource describing the license. */ public static final Relation LICENSE = new Relation("license"); /** * Signifies that the IRI in the value of the href attribute identifies the * next resource in a series including the current resource. */ public static final Relation NEXT = new Relation("next"); /** * Signifies that the IRI in the value of the href attribute identifies the * immediately following archive document. */ public static final Relation NEXT_ARCHIVE = new Relation("next-archive"); /** * Signifies that the IRI in the value of the href attribute identifies * where payment is accepted. */ public static final Relation PAYMENT = new Relation("payment"); /** * When included on a versioned resource, this link points to a resource * containing the predecessor version in the version history. Some systems * may allow multiple of these link relations in the case of a multiple * branches merging. */ public static final Relation PREDECESSOR_VERSION = new Relation( "predecessor-version"); /** * A URI that refers to the immediately preceding archive document. */ public static final Relation PREVIOUS_ARCHIVE = new Relation("prev-archive"); /** * Signifies that the IRI in the value of the href attribute identifies the * previous resource in a series including the current resource. */ public static final Relation PREVIOUS = new Relation("previous"); /** * Signifies that the IRI in the value of the href attribute identifies a * resource related to the resource described by the containing element. */ public static final Relation RELATED = new Relation("related"); /** * Signifies that the IRI in the value of the href attribute identifies a * resource where responses to an entry may be found. */ public static final Relation REPLIES = new Relation("replies"); /** * Signifies that the IRI in the value of the href attribute identifies a * resource equivalent to the containing element. */ public static final Relation SELF = new Relation("self"); /** * Signifies that the IRI in the value of the href attribute identifies a * resource that can be used to retrieve an Atom Publishing Protocol Service * Document as defined by RFC 5023. */ public static final Relation SERVICE = new Relation("service"); /** * When included on a versioned resource, this link points to a resource * containing the successor version in the version history. Some systems may * allow multiple of these link relations in order to support branching. */ public static final Relation SUCCESSOR_VERSION = new Relation( "successor-version"); /** * A URI that refers to a parent document in a hierarchy of documents. */ public static final Relation UP = new Relation("up"); /** * When included on a versioned resource, this link points to a resource * containing the version history for this resource. */ public static final Relation VERSION_HISTORY = new Relation( "version-history"); /** * Signifies that the IRI in the value of the href attribute identifies a * resource that is the source of the information provided in the containing * element. */ public static final Relation VIA = new Relation("via"); /** * When included on a versioned resource, this link points to a working copy * for this resource. Some systems may allow multiple of these link * relations. */ public static final Relation WORKING_COPY = new Relation("working-copy"); /** * When included on a working copy, this link points to the versioned * resource from which this working copy was obtained. */ public static final Relation WORKING_COPY_OF = new Relation( "working-copy-of"); /** * Parses a relation name into the equivalent enumeration item. * * @param rel * The relation name to parse. * @return The equivalent enumeration item. * @deprecated Use the {@link #valueOf(String)} method instead. */ @Deprecated public static Relation parse(String rel) { return valueOf(rel); } /** * Return a String object representing the specified Relation. * * @param rel * The relation to be converted. * @return The String representation of the argument. */ public static String toString(Relation rel) { return rel.name; } /** * Parses a relation name into the equivalent item. * * @param rel * The relation name to parse. * @return The equivalent item. */ public static Relation valueOf(String rel) { Relation result = ALTERNATE; if (rel != null) { if (rel.equalsIgnoreCase("alternate")) { result = ALTERNATE; } else if (rel.equalsIgnoreCase("current")) { result = CURRENT; } else if (rel.equalsIgnoreCase("describedby")) { result = DESCRIBED_BY; } else if (rel.equalsIgnoreCase("edit")) { result = EDIT; } else if (rel.equalsIgnoreCase("edit-media")) { result = EDIT_MEDIA; } else if (rel.equalsIgnoreCase("enclosure")) { result = ENCLOSURE; } else if (rel.equalsIgnoreCase("first")) { result = FIRST; } else if (rel.equalsIgnoreCase("hub")) { result = HUB; } else if (rel.equalsIgnoreCase("last")) { result = LAST; } else if (rel.equalsIgnoreCase("latest-version")) { result = LAST_VERSION; } else if (rel.equalsIgnoreCase("license")) { result = LICENSE; } else if (rel.equalsIgnoreCase("next")) { result = NEXT; } else if (rel.equalsIgnoreCase("next-archive")) { result = NEXT_ARCHIVE; } else if (rel.equalsIgnoreCase("payment")) { result = PAYMENT; } else if (rel.equalsIgnoreCase("predecessor-version")) { result = PREDECESSOR_VERSION; } else if (rel.equalsIgnoreCase("previous")) { result = PREVIOUS; } else if (rel.equalsIgnoreCase("prev-archive")) { result = PREVIOUS_ARCHIVE; } else if (rel.equalsIgnoreCase("related")) { result = RELATED; } else if (rel.equalsIgnoreCase("replies")) { result = REPLIES; } else if (rel.equalsIgnoreCase("self")) { result = SELF; } else if (rel.equalsIgnoreCase("service")) { result = SERVICE; } else if (rel.equalsIgnoreCase("successor-version")) { result = SUCCESSOR_VERSION; } else if (rel.equalsIgnoreCase("up")) { result = UP; } else if (rel.equalsIgnoreCase("version-history")) { result = VERSION_HISTORY; } else if (rel.equalsIgnoreCase("via")) { result = VIA; } else if (rel.equalsIgnoreCase("working-copy")) { result = WORKING_COPY; } else if (rel.equalsIgnoreCase("working-copy-of")) { result = WORKING_COPY_OF; } else { result = new Relation(rel); } } return result; } /** The name of the relation. */ private String name; /** * Constructor. * * @param name * The name of the relation. */ public Relation(String name) { super(); this.name = name; } /** {@inheritDoc} */ @Override public boolean equals(Object object) { return (object instanceof Relation) && name.equalsIgnoreCase(((Relation) object).getName()); } /** * Returns the name of the relation. * * @return The name of the relation. */ public String getName() { return name; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().toLowerCase().hashCode(); } @Override public String toString() { return name; } } restlet-2.0.14/org.restlet.ext.atom/src/org/restlet/ext/atom/Workspace.java0000664000175000017500000001151111757206350027350 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.atom; import static org.restlet.ext.atom.Feed.ATOM_NAMESPACE; import static org.restlet.ext.atom.Service.APP_NAMESPACE; import java.util.ArrayList; import java.util.List; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; /** * Workspace containing collections of members entries. * * @author Jerome Louvel */ public class Workspace { /** * The base reference used to resolve relative references found within the * scope of the xml:base attribute. */ private volatile Reference baseReference; /** * The list of collections. */ private volatile List collections; /** * The parent service. */ private volatile Service service; /** * The title. */ private volatile String title; /** * Constructor. * * @param service * The parent service. */ public Workspace(Service service) { this(service, null); } /** * Constructor. * * @param service * The parent service. * @param title * The title. */ public Workspace(Service service, String title) { this.service = service; this.title = title; } /** * Returns the base reference used to resolve relative references found * within the scope of the xml:base attribute. * * @return The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public Reference getBaseReference() { return baseReference; } /** * Returns the list of collections. * * @return The list of collections. */ public List getCollections() { if (this.collections == null) { this.collections = new ArrayList(); } return this.collections; } /** * Returns the parent service. * * @return The parent service. */ public Service getService() { return this.service; } /** * Returns the title. * * @return The title. */ public String getTitle() { return this.title; } /** * Sets the base reference used to resolve relative references found within * the scope of the xml:base attribute. * * @param baseReference * The base reference used to resolve relative references found * within the scope of the xml:base attribute. */ public void setBaseReference(Reference baseReference) { this.baseReference = baseReference; } /** * Sets the parent service. * * @param service * The parent service. */ public void setService(Service service) { this.service = service; } /** * Sets the title. * * @param title * The title. */ public void setTitle(String title) { this.title = title; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { writer.startElement(APP_NAMESPACE, "workspace"); if (getTitle() != null) { writer.dataElement(ATOM_NAMESPACE, "title", getTitle()); } for (final Collection collection : getCollections()) { collection.writeElement(writer); } writer.endElement(APP_NAMESPACE, "workspace"); } } restlet-2.0.14/org.restlet.ext.wadl/0000775000175000017500000000000012001473207017725 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.wadl/pom.xml0000600000175000017500000000160212001473207021227 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.wadl Restlet Extension - WADL Support for the WADL specification. org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 restlet-2.0.14/org.restlet.ext.wadl/src/0000775000175000017500000000000012001473206020513 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.wadl/src/META-INF/0000775000175000017500000000000011757206452021671 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.wadl/src/META-INF/services/0000775000175000017500000000000011757206352023513 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.wadl/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.wadl/src/META-INF/services/org.restlet.engine.converter.ConverterHelp0000664000175000017500000000004211757206352033733 0ustar jamespagejamespageorg.restlet.ext.wadl.WadlConverterrestlet-2.0.14/org.restlet.ext.wadl/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023322 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.wadl/src/org/0000775000175000017500000000000011757206352021317 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/0000775000175000017500000000000011757206352023001 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/0000775000175000017500000000000011757206352023601 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/0000775000175000017500000000000011757206352024530 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/DocumentedInfo.java0000664000175000017500000001323511757206352030302 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.w3c.dom.Node; /** * Superclass of WADL elements that supports dcumentation. * */ public abstract class DocumentedInfo { /** Doc elements used to document that element. */ private List documentations; /** * Constructor. */ public DocumentedInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public DocumentedInfo(DocumentationInfo documentation) { super(); getDocumentations().add(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public DocumentedInfo(List documentations) { super(); this.documentations = documentations; } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public DocumentedInfo(String documentation) { this(new DocumentationInfo(documentation)); } /** * Returns the list of documentation elements. * * @return The list of documentation elements. */ public List getDocumentations() { // Lazy initialization with double-check. List d = this.documentations; if (d == null) { synchronized (this) { d = this.documentations; if (d == null) { this.documentations = d = new ArrayList(); } } } return d; } /** * Returns the list of namespaces used in the documentation elements as a * map. The key is the URI of the namespace and the value, the prefix. * * @return The list of namespaces used in the documentation elements as a * map. */ public Map resolveNamespaces() { Map result = new HashMap(); for (DocumentationInfo documentationInfo : getDocumentations()) { if (documentationInfo.getMixedContent() != null) { resolveNamespaces(documentationInfo.getMixedContent(), result); } } return result; } /** * Completes the given map of namespaces with the namespaces of the given * node. * * @param node * The node to analyse. * @param namespaces * the map of namespaces to complete. */ private void resolveNamespaces(Node node, Map namespaces) { if (node.getNamespaceURI() != null) { namespaces.put(node.getNamespaceURI(), node.getPrefix()); } if (node.getChildNodes() != null) { for (int i = 0; i < node.getChildNodes().getLength(); i++) { resolveNamespaces(node.getChildNodes().item(i), namespaces); } } } /** * Set the list of documentation elements with a single element. * * @param documentationInfo * A single documentation element. */ public void setDocumentation(DocumentationInfo documentationInfo) { getDocumentations().clear(); getDocumentations().add(documentationInfo); } /** * Set the list of documentation elements with a single element. * * @param documentation * A single documentation element. */ public void setDocumentation(String documentation) { getDocumentations().clear(); getDocumentations().add(new DocumentationInfo(documentation)); } /** * Sets the list of documentation elements. * * @param doc * The list of documentation elements. */ public void setDocumentations(List doc) { this.documentations = doc; } /** * Completes the given map of namespaces with the namespaces used in the * documentation elements. The key is the URI of the namespace and the * value, the prefix. * * @param namespaces * The given map of namespaces to complete. */ public abstract void updateNamespaces(Map namespaces); } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/ResourceTypeInfo.java0000664000175000017500000001442111757206352030642 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Describes a reusable type of resources. * * @author Jerome Louvel */ public class ResourceTypeInfo extends DocumentedInfo { /** Identifier for that element. */ private String identifier; /** List of supported methods. */ private List methods; /** List of parameters. */ private List parameters; /** * Constructor. */ public ResourceTypeInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResourceTypeInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public ResourceTypeInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResourceTypeInfo(String documentation) { super(documentation); } /** * Returns the identifier for that element. * * @return The identifier for that element. */ public String getIdentifier() { return this.identifier; } /** * Returns the list of supported methods. * * @return The list of supported methods. */ public List getMethods() { // Lazy initialization with double-check. List m = this.methods; if (m == null) { synchronized (this) { m = this.methods; if (m == null) { this.methods = m = new ArrayList(); } } } return m; } /** * Returns the list of parameters. * * @return The list of parameters. */ public List getParameters() { // Lazy initialization with double-check. List p = this.parameters; if (p == null) { synchronized (this) { p = this.parameters; if (p == null) { this.parameters = p = new ArrayList(); } } } return p; } /** * Sets the identifier for that element. * * @param identifier * The identifier for that element. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Sets the list of supported methods. * * @param methods * The list of supported methods. */ public void setMethods(List methods) { this.methods = methods; } /** * Sets the list of parameters. * * @param parameters * The list of parameters. */ public void setParameters(List parameters) { this.parameters = parameters; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); for (final MethodInfo methodInfo : getMethods()) { methodInfo.updateNamespaces(namespaces); } for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getIdentifier() != null) && !getIdentifier().equals("")) { attributes.addAttribute("", "id", null, "xs:ID", getIdentifier()); } if (getDocumentations().isEmpty() && getMethods().isEmpty() && getParameters().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "resource_type", null, attributes); } else { writer.startElement(APP_NAMESPACE, "resource_type", null, attributes); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (final MethodInfo methodInfo : getMethods()) { methodInfo.writeElement(writer); } for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "resource_type"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/DocumentationInfo.java0000664000175000017500000002357311757206352031032 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.io.IOException; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.ext.xml.DomRepresentation; import org.restlet.ext.xml.XmlWriter; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Document WADL description elements. * * @author Jerome Louvel */ public class DocumentationInfo { /** The language of that documentation element. */ private Language language; /** The mixed content of that element. */ private Node mixedContent; /** The title of that documentation element. */ private String title; /** * Constructor. */ public DocumentationInfo() { super(); } /** * Constructor with mixed content. * * @param mixedContent * The mixed content. */ public DocumentationInfo(Node mixedContent) { super(); this.mixedContent = mixedContent; } /** * Constructor with text content. * * @param textContent * The text content. */ public DocumentationInfo(String textContent) { super(); setTextContent(textContent); } /** * Returns the language of that documentation element. * * @return The language of this documentation element. */ public Language getLanguage() { return this.language; } /** * Returns the mixed content of that element. * * @return The mixed content of that element. */ public Node getMixedContent() { return this.mixedContent; } /** * Returns the language of that documentation element. * * @return The content of that element as text. */ public String getTextContent() { return this.mixedContent.getTextContent(); } /** * Returns the title of that documentation element. * * @return The title of that documentation element. */ public String getTitle() { return this.title; } /** * The language of that documentation element. * * @param language * The language of that documentation element. */ public void setLanguage(Language language) { this.language = language; } /** * Sets the mixed content of that element. * * @param mixedContent * The mixed content of that element. */ public void setMixedContent(Node mixedContent) { this.mixedContent = mixedContent; } /** * Sets the content of that element as text. * * @param textContent * The content of that element as text. */ public void setTextContent(String textContent) { try { Document doc = new DomRepresentation(MediaType.TEXT_XML) .getDocument(); this.mixedContent = doc.createTextNode(textContent); } catch (IOException e) { } } /** * Sets the title of that documentation element. * * @param title * The title of that documentation element. */ public void setTitle(String title) { this.title = title; } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getTitle() != null) && !getTitle().equals("")) { attributes.addAttribute("", "title", null, "xs:string", getTitle()); } if ((getLanguage() != null) && (getLanguage().toString() != null)) { attributes.addAttribute("", "xml:lang", null, "xs:string", getLanguage().toString()); } if (getMixedContent() == null) { writer.emptyElement(APP_NAMESPACE, "doc", null, attributes); } else { writer.startElement(APP_NAMESPACE, "doc", null, attributes); try { // Used to restore the SAX writer's dataFormat boolean isDataFormat = writer.isDataFormat(); writer.setDataFormat(false); writeElement(writer, getMixedContent()); // Restore the SAX writer's dataFormat writer.setDataFormat(isDataFormat); } catch (IOException e) { Context .getCurrentLogger() .log( Level.SEVERE, "Error when writing the text content of the current \"doc\" tag.", e); } writer.endElement(APP_NAMESPACE, "doc"); } } /** * Writes the given node using the given SAX writer. It detects the type of * node (CDATASection, Entity, Comment, Text, DocumentFragment, Node). * * @param writer * The SAX writer * @param node * the given Node to write. * @throws IOException * @throws SAXException */ private void writeElement(XmlWriter writer, Node node) throws IOException, SAXException { if (node instanceof CDATASection) { CDATASection section = (CDATASection) node; writer.getWriter().write(""); } else if (node instanceof Text) { Text text = (Text) node; writer.getWriter().write(text.getNodeValue()); } else if (node instanceof EntityReference) { EntityReference entity = (EntityReference) node; writer.getWriter().write("&"); writer.getWriter().write(entity.getNodeName()); writer.getWriter().write(";"); } else if (node instanceof Comment) { Comment comment = (Comment) node; writer.getWriter().write(""); } else if (node instanceof DocumentFragment) { DocumentFragment documentFragment = (DocumentFragment) node; // Walk along the tree of nodes. for (int i = 0; i < documentFragment.getChildNodes().getLength(); i++) { writeElement(writer, documentFragment.getChildNodes().item(i)); } } else { // Check that the node contains attributes, and convert it into the // SAX model. AttributesImpl attributes = null; if (node.hasAttributes()) { attributes = new AttributesImpl(); for (int i = 0; i < node.getAttributes().getLength(); i++) { Node attribute = node.getAttributes().item(i); // NB : the type of the attribute is set to null. attributes.addAttribute(attribute.getNamespaceURI(), attribute.getLocalName(), "", null, attribute .getNodeValue()); } } if (node.getChildNodes() != null && node.getChildNodes().getLength() > 0) { // This node contains children nodes. if (attributes == null) { writer.startElement(node.getNamespaceURI(), node .getLocalName()); } else { writer.startElement(node.getNamespaceURI(), node .getLocalName(), node.getPrefix(), attributes); } // Add the children nodes. for (int i = 0; i < node.getChildNodes().getLength(); i++) { writeElement(writer, node.getChildNodes().item(i)); } writer.endElement(node.getNamespaceURI(), node.getLocalName()); } else { // This node is empty. if (attributes == null) { writer.emptyElement(node.getNamespaceURI(), node .getLocalName()); } else { writer.emptyElement(node.getNamespaceURI(), node .getLocalName(), node.getPrefix(), attributes); } } } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlResource.java0000664000175000017500000002671611757206352030006 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import java.util.ArrayList; import java.util.List; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.Resource; /** * Resource that is able to automatically describe itself with WADL. This * description can be customized by overriding the {@link #describe()} and * {@link #describeMethod(Method, MethodInfo)} methods. * * When used to describe a class of resources in the context of a parent * application, a special instance will be created using the default constructor * (with no request, response associated). In this case, the resource should do * its best to return the generic information when the WADL description methods * are invoked, like {@link #describe()} and delegate methods. * * @author Jerome Louvel * @deprecated Use the {@link WadlServerResource} class instead */ @Deprecated public class WadlResource extends Resource { /** * Indicates if the resource should be automatically described via WADL when * an OPTIONS request is handled. */ private volatile boolean autoDescribed; /** * The title of this documented resource. Is seen as the title of the first * "doc" tag of the "application" tag in a WADL document or as the title of * the HTML representation. */ private volatile String title; /** * Constructor. */ public WadlResource() { this.autoDescribed = true; } /** * Constructor. * * @param context * The parent context. * @param request * The request to handle. * @param response * The response to return. */ public WadlResource(Context context, Request request, Response response) { super(context, request, response); this.autoDescribed = true; } /** * Indicates if OPTIONS calls are allowed by checking the "readable" * property. * * @return True if the method is allowed. */ @Override public boolean allowOptions() { return isReadable(); } /** * Describes the resource as a WADL document. * * @return The WADL description. */ protected Representation describe() { return describe(getPreferredWadlVariant()); } /** * Returns a WADL description of the current resource, leveraging the * {@link #getResourcePath()} method. * * @param info * WADL description of the current resource to update. */ private void describe(ResourceInfo info) { describe(getResourcePath(), info); } /** * Returns a WADL description of the current resource. * * @param path * Path of the current resource. * @param info * WADL description of the current resource to update. */ public void describe(String path, ResourceInfo info) { ResourceInfo.describe(null, info, this, path); } /** * Describes the resource as a WADL document for the given variant. * * @param variant * The WADL variant. * @return The WADL description. */ protected Representation describe(Variant variant) { Representation result = null; if (variant != null) { ResourceInfo resourceInfo = new ResourceInfo(); describe(resourceInfo); if (getTitle() != null && !"".equals(getTitle())) { DocumentationInfo doc = null; if (resourceInfo.getDocumentations().isEmpty()) { doc = new DocumentationInfo(); resourceInfo.getDocumentations().add(doc); } else { doc = resourceInfo.getDocumentations().get(0); } doc.setTitle(getTitle()); } if (MediaType.APPLICATION_WADL.equals(variant.getMediaType())) { result = new WadlRepresentation(resourceInfo); } else if (MediaType.TEXT_HTML.equals(variant.getMediaType())) { result = new WadlRepresentation(resourceInfo) .getHtmlRepresentation(); } } return result; } /** * Describes the DELETE method. * * @param info * The method description to update. */ protected void describeDelete(MethodInfo info) { } /** * Describes the GET method.
    * By default, it describes the response with the available variants based * on the {@link #getVariants()} method. Thus in the majority of cases, the * method of the super class must be called when overriden. * * @param info * The method description to update. */ protected void describeGet(MethodInfo info) { List variants = getVariants(); if (variants != null) { // Describe each variant for (final Variant variant : variants) { info.addResponseRepresentation(variant); } } } /** * Returns a WADL description of the given method. * * @param method * The method to describe. * @param info * The method description to update. */ protected void describeMethod(Method method, MethodInfo info) { info.setName(method); info.setRequest(new RequestInfo()); info.getResponses().add(new ResponseInfo()); if (Method.GET.equals(method)) { describeGet(info); } else if (Method.POST.equals(method)) { describePost(info); } else if (Method.PUT.equals(method)) { describePut(info); } else if (Method.DELETE.equals(method)) { describeDelete(info); } else if (Method.OPTIONS.equals(method)) { describeOptions(info); } } /** * Describes the OPTIONS method.
    * By default it describes the response with the available variants based on * the {@link #getWadlVariants()} method. * * @param info * The method description to update. */ protected void describeOptions(MethodInfo info) { // Describe each variant for (final Variant variant : getWadlVariants()) { info.addResponseRepresentation(variant); } } /** * Describes the POST method. * * @param info * The method description to update. */ protected void describePost(MethodInfo info) { } /** * Describes the PUT method. * * @param info * The method description to update. */ protected void describePut(MethodInfo info) { } /** * Returns the description of the parameters of this resource. Returns null * by default. * * @return The description of the parameters. */ protected List getParametersInfo() { final List result = null; return result; } /** * Returns the preferred WADL variant according to the client preferences * specified in the request. * * @return The preferred WADL variant. */ protected Variant getPreferredWadlVariant() { // Compute the preferred variant Variant result = getRequest().getClientInfo().getPreferredVariant( getWadlVariants(), (getApplication() == null) ? null : getApplication() .getMetadataService()); return result; } /** * Returns the resource's relative path. * * @return The resource's relative path. */ protected String getResourcePath() { final Reference ref = new Reference(getRequest().getRootRef(), getRequest().getResourceRef()); return ref.getRemainingPart(); } /** * Returns the application resources base URI. * * @return The application resources base URI. */ protected Reference getResourcesBase() { return getRequest().getRootRef(); } /** * Returns the title of this documented resource. * * @return The title of this documented resource. */ public String getTitle() { return title; } /** * Returns the available WADL variants. * * @return The available WADL variants. */ protected List getWadlVariants() { final List result = new ArrayList(); result.add(new Variant(MediaType.APPLICATION_WADL)); result.add(new Variant(MediaType.TEXT_HTML)); return result; } @Override public void handleOptions() { if (isAutoDescribed()) { getResponse().setEntity(describe()); } } /** * Indicates if the resource should be automatically described via WADL when * an OPTIONS request is handled. * * @return True if the resource should be automatically described via WADL. */ public boolean isAutoDescribed() { return this.autoDescribed; } /** * Indicates if the given method exposes its WADL description. By default, * HEAD and OPTIONS are not exposed. This method is called by * {@link #describe(String, ResourceInfo)}. * * @param method * The method * @return True if the method exposes its description, false otherwise. */ public boolean isDescribable(Method method) { return !(Method.HEAD.equals(method) || Method.OPTIONS.equals(method)); } /** * Indicates if the resource should be automatically described via WADL when * an OPTIONS request is handled. * * @param autoDescribed * True if the resource should be automatically described via * WADL. */ public void setAutoDescribed(boolean autoDescribed) { this.autoDescribed = autoDescribed; } /** * Sets the title of this documented resource. * * @param title * The title of this documented resource. */ public void setTitle(String title) { this.title = title; } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/RepresentationInfo.java0000664000175000017500000002665011757206352031222 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Variant; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Describes a variant representation for a target resource. * * @author Jerome Louvel */ public class RepresentationInfo extends DocumentedInfo { /** Identifier for that element. */ private String identifier; /** Media type of that element. */ private MediaType mediaType; /** List of parameters. */ private List parameters; /** List of locations of one or more meta data profiles. */ private List profiles; /** Reference to an representation identifier. */ private String reference; /** * List of statuses associated with this response representation. * * @deprecated According to new WADL specification, this attribute has been * moved to the {@link ResponseInfo} class. */ @Deprecated private List statuses; /** Qualified name of the root element for this XML-based representation. */ private String xmlElement; /** * Constructor. */ public RepresentationInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public RepresentationInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public RepresentationInfo(List documentations) { super(documentations); } /** * Constructor with a media type. * * @param mediaType * The media type of the representation. */ public RepresentationInfo(MediaType mediaType) { setMediaType(mediaType); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public RepresentationInfo(String documentation) { super(documentation); } /** * Constructor with a variant. * * @param variant * The variant to describe. */ public RepresentationInfo(Variant variant) { setMediaType(variant.getMediaType()); } /** * Returns the identifier for that element. * * @return The identifier for that element. */ public String getIdentifier() { return this.identifier; } /** * Returns the media type of that element. * * @return The media type of that element. */ public MediaType getMediaType() { return this.mediaType; } /** * Returns the list of parameters. * * @return The list of parameters. */ public List getParameters() { // Lazy initialization with double-check. List p = this.parameters; if (p == null) { synchronized (this) { p = this.parameters; if (p == null) { this.parameters = p = new ArrayList(); } } } return p; } /** * Returns the list of locations of one or more meta data profiles. * * @return The list of locations of one or more meta data profiles. */ public List getProfiles() { // Lazy initialization with double-check. List p = this.profiles; if (p == null) { synchronized (this) { p = this.profiles; if (p == null) { this.profiles = p = new ArrayList(); } } } return p; } /** * Returns the reference to an representation identifier. * * @return The reference to an representation identifier. */ public String getReference() { return reference; } /** * Returns the list of statuses associated with this response * representation. * * @return The list of statuses associated with this response * representation. * @deprecated According to new WADL specification, this method has been * moved to the {@link ResponseInfo} class. */ @Deprecated public List getStatuses() { // Lazy initialization with double-check. List s = this.statuses; if (s == null) { synchronized (this) { s = this.statuses; if (s == null) { this.statuses = s = new ArrayList(); } } } return s; } /** * Returns the qualified name of the root element for this XML-based * representation. * * @return The qualified name of the root element for this XML-based * representation. */ public String getXmlElement() { return this.xmlElement; } /** * Sets the identifier for that element. * * @param identifier * The identifier for that element. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Sets the media type of that element. * * @param mediaType * The media type of that element. */ public void setMediaType(MediaType mediaType) { this.mediaType = mediaType; } /** * Sets the list of parameters. * * @param parameters * The list of parameters. */ public void setParameters(List parameters) { this.parameters = parameters; } /** * Sets the list of locations of one or more meta data profiles. * * @param profiles * The list of locations of one or more meta data profiles. */ public void setProfiles(List profiles) { this.profiles = profiles; } /** * Sets the reference to an representation identifier. * * @param reference * The reference to an representation identifier. */ public void setReference(String reference) { this.reference = reference; } /** * Sets the list of statuses associated with this response representation. * * @param statuses * The list of statuses associated with this response * representation. * @deprecated According to new WADL specification, this method has been * moved to the {@link ResponseInfo} class. */ @Deprecated public void setStatuses(List statuses) { this.statuses = statuses; } /** * Sets the qualified name of the root element for this XML-based * representation. * * @param xmlElement * The qualified name of the root element for this XML-based * representation. */ public void setXmlElement(String xmlElement) { this.xmlElement = xmlElement; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { AttributesImpl attributes = new AttributesImpl(); if ((getReference() != null) && !getReference().equals("")) { attributes.addAttribute("", "href", null, "xs:anyURI", "#" + getReference()); writer.emptyElement(APP_NAMESPACE, "representation", null, attributes); } else { if ((getIdentifier() != null) && !getIdentifier().equals("")) { attributes.addAttribute("", "id", null, "xs:ID", getIdentifier()); } if (getMediaType() != null) { attributes.addAttribute("", "mediaType", null, "xs:string", getMediaType().toString()); } if ((getProfiles() != null) && !getProfiles().isEmpty()) { StringBuilder builder = new StringBuilder(); for (Iterator iterator = getProfiles().iterator(); iterator .hasNext();) { Reference reference = iterator.next(); builder.append(reference.toString()); if (iterator.hasNext()) { builder.append(" "); } } attributes.addAttribute("", "profile", null, "xs:string", builder.toString()); } if ((getXmlElement() != null) && !getXmlElement().equals("")) { attributes.addAttribute("", "element", null, "xs:QName", getXmlElement()); } if (getDocumentations().isEmpty() && getParameters().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "representation", null, attributes); } else { writer.startElement(APP_NAMESPACE, "representation", null, attributes); for (DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (ParameterInfo parameterInfo : getParameters()) { parameterInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "representation"); } } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/ResourcesInfo.java0000664000175000017500000001233711757206352030167 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Describes the root resources of an application. * * @author Jerome Louvel */ public class ResourcesInfo extends DocumentedInfo { /** Base URI for each child resource identifier. */ private Reference baseRef; /** List of child resources. */ private List resources; /** * Constructor. */ public ResourcesInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResourcesInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public ResourcesInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResourcesInfo(String documentation) { super(documentation); } /** * Returns the base URI for each child resource identifier. * * @return The base URI for each child resource identifier. */ public Reference getBaseRef() { return this.baseRef; } /** * Returns the list of child resources. * * @return The list of child resources. */ public List getResources() { // Lazy initialization with double-check. List r = this.resources; if (r == null) { synchronized (this) { r = this.resources; if (r == null) { this.resources = r = new ArrayList(); } } } return r; } /** * Sets the base URI for each child resource identifier. * * @param baseRef * The base URI for each child resource identifier. */ public void setBaseRef(Reference baseRef) { this.baseRef = baseRef; } /** * Sets the list of child resources. * * @param resources * The list of child resources. */ public void setResources(List resources) { this.resources = resources; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); for (final ResourceInfo resourceInfo : getResources()) { resourceInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if (getBaseRef() != null) { attributes.addAttribute("", "base", null, "xs:anyURI", getBaseRef() .toString()); } if (getDocumentations().isEmpty() && getResources().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "resources", null, attributes); } else { writer.startElement(APP_NAMESPACE, "resources", null, attributes); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (final ResourceInfo resourceInfo : getResources()) { resourceInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "resources"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/ResourceInfo.java0000664000175000017500000004127411757206352030006 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Variant; import org.restlet.resource.Directory; import org.restlet.resource.ServerResource; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Describes a class of closely related resources. * * @author Jerome Louvel */ public class ResourceInfo extends DocumentedInfo { /** * Returns a WADL description of the current resource. * * @param applicationInfo * The parent application. * @param resource * The resource to describe. * @param path * Path of the current resource. * @param info * WADL description of the current resource to update. */ @SuppressWarnings("deprecation") public static void describe(ApplicationInfo applicationInfo, ResourceInfo info, Object resource, String path) { if ((path != null) && path.startsWith("/")) { path = path.substring(1); } info.setPath(path); // Introspect the current resource to detect the allowed methods List methodsList = new ArrayList(); if (resource instanceof ServerResource) { ((ServerResource) resource).updateAllowedMethods(); methodsList.addAll(((ServerResource) resource).getAllowedMethods()); if (resource instanceof WadlServerResource) { info.setParameters(((WadlServerResource) resource) .describeParameters()); if (applicationInfo != null) { ((WadlServerResource) resource).describe(applicationInfo); } } } else if (resource instanceof org.restlet.resource.Resource) { methodsList.addAll(((org.restlet.resource.Resource) resource) .getAllowedMethods()); if (resource instanceof WadlResource) { info.setParameters(((WadlResource) resource) .getParametersInfo()); } } else if (resource instanceof Directory) { Directory directory = (Directory) resource; methodsList.add(Method.GET); if (directory.isModifiable()) { methodsList.add(Method.DELETE); methodsList.add(Method.PUT); } } Method.sort(methodsList); // Update the resource info with the description of the allowed methods List methods = info.getMethods(); MethodInfo methodInfo; for (Method method : methodsList) { methodInfo = new MethodInfo(); methods.add(methodInfo); methodInfo.setName(method); if (resource instanceof ServerResource) { if (resource instanceof WadlServerResource) { WadlServerResource wsResource = (WadlServerResource) resource; if (wsResource.canDescribe(method)) { wsResource.describeMethod(method, methodInfo); } } else { MethodInfo.describeAnnotations(methodInfo, (ServerResource) resource); } } else if (resource instanceof org.restlet.resource.Resource) { if (resource instanceof WadlResource) { WadlResource wsResource = (WadlResource) resource; if (wsResource.isDescribable(method)) { wsResource.describeMethod(method, methodInfo); } } else { // Can document the list of supported variants. if (Method.GET.equals(method)) { ResponseInfo responseInfo = null; for (Variant variant : ((org.restlet.resource.Resource) resource) .getVariants()) { RepresentationInfo representationInfo = new RepresentationInfo(); representationInfo.setMediaType(variant .getMediaType()); if (responseInfo == null) { responseInfo = new ResponseInfo(); methodInfo.getResponses().add(responseInfo); } responseInfo.getRepresentations().add( representationInfo); } } } } } // Document the resource String title = null; String textContent = null; if (resource instanceof WadlServerResource) { title = ((WadlServerResource) resource).getName(); textContent = ((WadlServerResource) resource).getDescription(); } else if (resource instanceof WadlResource) { title = ((WadlResource) resource).getTitle(); } if ((title != null) && !"".equals(title)) { DocumentationInfo doc = null; if (info.getDocumentations().isEmpty()) { doc = new DocumentationInfo(); info.getDocumentations().add(doc); } else { info.getDocumentations().get(0); } doc.setTitle(title); doc.setTextContent(textContent); } } /** List of child resources. */ private List childResources; /** Identifier for that element. */ private String identifier; /** List of supported methods. */ private List methods; /** List of parameters. */ private List parameters; /** URI template for the identifier of the resource. */ private String path; /** Media type for the query component of the resource URI. */ private MediaType queryType; /** List of references to resource type elements. */ private List type; /** * Constructor. */ public ResourceInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResourceInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public ResourceInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResourceInfo(String documentation) { super(documentation); } /** * Creates an application descriptor that wraps this resource descriptor. * The title of the resource, that is to say the title of its first * documentation tag is transfered to the title of the first documentation * tag of the main application tag. * * @return The new application descriptor. */ public ApplicationInfo createApplication() { ApplicationInfo result = new ApplicationInfo(); if (!getDocumentations().isEmpty()) { String titleResource = getDocumentations().get(0).getTitle(); if (titleResource != null && !"".equals(titleResource)) { DocumentationInfo doc = null; if (result.getDocumentations().isEmpty()) { doc = new DocumentationInfo(); result.getDocumentations().add(doc); } else { doc = result.getDocumentations().get(0); } doc.setTitle(titleResource); } } ResourcesInfo resources = new ResourcesInfo(); result.setResources(resources); resources.getResources().add(this); return result; } /** * Returns the list of child resources. * * @return The list of child resources. */ public List getChildResources() { // Lazy initialization with double-check. List r = this.childResources; if (r == null) { synchronized (this) { r = this.childResources; if (r == null) { this.childResources = r = new ArrayList(); } } } return r; } /** * Returns the identifier for that element. * * @return The identifier for that element. */ public String getIdentifier() { return this.identifier; } /** * Returns the list of supported methods. * * @return The list of supported methods. */ public List getMethods() { // Lazy initialization with double-check. List m = this.methods; if (m == null) { synchronized (this) { m = this.methods; if (m == null) { this.methods = m = new ArrayList(); } } } return m; } /** * Returns the list of parameters. * * @return The list of parameters. */ public List getParameters() { // Lazy initialization with double-check. List p = this.parameters; if (p == null) { synchronized (this) { p = this.parameters; if (p == null) { this.parameters = p = new ArrayList(); } } } return p; } /** * Returns the URI template for the identifier of the resource. * * @return The URI template for the identifier of the resource. */ public String getPath() { return this.path; } /** * Returns the media type for the query component of the resource URI. * * @return The media type for the query component of the resource URI. */ public MediaType getQueryType() { return this.queryType; } /** * Returns the list of references to resource type elements. * * @return The list of references to resource type elements. */ public List getType() { // Lazy initialization with double-check. List t = this.type; if (t == null) { synchronized (this) { t = this.type; if (t == null) { this.type = t = new ArrayList(); } } } return t; } /** * Sets the list of child resources. * * @param resources * The list of child resources. */ public void setChildResources(List resources) { this.childResources = resources; } /** * Sets the identifier for that element. * * @param identifier * The identifier for that element. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Sets the list of supported methods. * * @param methods * The list of supported methods. */ public void setMethods(List methods) { this.methods = methods; } /** * Sets the list of parameters. * * @param parameters * The list of parameters. */ public void setParameters(List parameters) { this.parameters = parameters; } /** * Sets the URI template for the identifier of the resource. * * @param path * The URI template for the identifier of the resource. */ public void setPath(String path) { this.path = path; } /** * Sets the media type for the query component of the resource URI. * * @param queryType * The media type for the query component of the resource URI. */ public void setQueryType(MediaType queryType) { this.queryType = queryType; } /** * Sets the list of references to resource type elements. * * @param type * The list of references to resource type elements. */ public void setType(List type) { this.type = type; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.updateNamespaces(namespaces); } for (final ResourceInfo resourceInfo : getChildResources()) { resourceInfo.updateNamespaces(namespaces); } for (final MethodInfo methodInfo : getMethods()) { methodInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getIdentifier() != null) && !getIdentifier().equals("")) { attributes.addAttribute("", "id", null, "xs:ID", getIdentifier()); } if ((getPath() != null) && !getPath().equals("")) { attributes.addAttribute("", "path", null, "xs:string", getPath()); } if (getQueryType() != null) { attributes.addAttribute("", "queryType", null, "xs:string", getQueryType().getMainType()); } if ((getType() != null) && !getType().isEmpty()) { final StringBuilder builder = new StringBuilder(); for (final Iterator iterator = getType().iterator(); iterator .hasNext();) { final Reference reference = iterator.next(); builder.append(reference.toString()); if (iterator.hasNext()) { builder.append(" "); } } attributes.addAttribute("", "type", null, "xs:string", builder .toString()); } if (getChildResources().isEmpty() && getDocumentations().isEmpty() && getMethods().isEmpty() && getParameters().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "resource", null, attributes); } else { writer.startElement(APP_NAMESPACE, "resource", null, attributes); for (final ResourceInfo resourceInfo : getChildResources()) { resourceInfo.writeElement(writer); } for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.writeElement(writer); } for (final MethodInfo methodInfo : getMethods()) { methodInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "resource"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/ApplicationInfo.java0000664000175000017500000002544211757206352030461 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; /** * Root of a WADL description document. * * @author Jerome Louvel */ public class ApplicationInfo extends DocumentedInfo { /** List of faults (representations that denote an error condition). */ @SuppressWarnings("deprecation") private List faults; /** Container for definitions of the format of data exchanged. */ private GrammarsInfo grammars; /** List of methods. */ private List methods; /** * Map of namespaces used in the WADL document. The key is the URI of the * namespace and the value, the prefix. */ private Map namespaces; /** List of representations. */ private List representations; /** Resources provided by the application. */ private ResourcesInfo resources; /** * Describes a set of methods that define the behavior of a type of * resource. */ private List resourceTypes; /** * Constructor. */ public ApplicationInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ApplicationInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public ApplicationInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ApplicationInfo(String documentation) { super(documentation); } /** * Returns the list of fault elements. * * @return The list of fault elements. */ @SuppressWarnings("deprecation") public List getFaults() { // Lazy initialization with double-check. List f = this.faults; if (f == null) { synchronized (this) { f = this.faults; if (f == null) { this.faults = f = new ArrayList(); } } } return f; } /** * Returns the grammar elements. * * @return The grammar elements. */ public GrammarsInfo getGrammars() { return this.grammars; } /** * Returns the list of method elements. * * @return The list of method elements. */ public List getMethods() { // Lazy initialization with double-check. List m = this.methods; if (m == null) { synchronized (this) { m = this.methods; if (m == null) { this.methods = m = new ArrayList(); } } } return m; } /** * Returns the map of namespaces used in the WADL document. * * @return The ap of namespaces used in the WADL document. */ public Map getNamespaces() { // Lazy initialization with double-check. Map n = this.namespaces; if (n == null) { synchronized (this) { n = this.namespaces; if (n == null) { this.namespaces = n = new HashMap(); } } } return n; } /** * Returns the list of representation elements. * * @return The list of representation elements. */ public List getRepresentations() { // Lazy initialization with double-check. List r = this.representations; if (r == null) { synchronized (this) { r = this.representations; if (r == null) { this.representations = r = new ArrayList(); } } } return r; } /** * Returns the resources root element. * * @return The resources root element. */ public ResourcesInfo getResources() { // Lazy initialization with double-check. ResourcesInfo r = this.resources; if (r == null) { synchronized (this) { r = this.resources; if (r == null) { this.resources = r = new ResourcesInfo(); } } } return r; } /** * Returns the list of resource type elements. * * @return The list of resource type elements. */ public List getResourceTypes() { // Lazy initialization with double-check. List rt = this.resourceTypes; if (rt == null) { synchronized (this) { rt = this.resourceTypes; if (rt == null) { this.resourceTypes = rt = new ArrayList(); } } } return rt; } /** * Sets the list of fault elements. * * @param faults * The list of documentation elements. */ @SuppressWarnings("deprecation") public void setFaults(List faults) { this.faults = faults; } /** * Sets the grammars element. * * @param grammars * The grammars element. */ public void setGrammars(GrammarsInfo grammars) { this.grammars = grammars; } /** * Sets the list of documentation elements. * * @param methods * The list of method elements. */ public void setMethods(List methods) { this.methods = methods; } /** * Sets the map of namespaces used in the WADL document. The key is the URI * of the namespace and the value, the prefix. * * @param namespaces * The map of namespaces used in the WADL document. */ public void setNamespaces(Map namespaces) { this.namespaces = namespaces; } /** * Sets the list of representation elements. * * @param representations * The list of representation elements. */ public void setRepresentations(List representations) { this.representations = representations; } /** * Sets the list of resource elements. * * @param resources * The list of resource elements. */ public void setResources(ResourcesInfo resources) { this.resources = resources; } /** * Sets the list of resource type elements. * * @param resourceTypes * The list of resource type elements. */ public void setResourceTypes(List resourceTypes) { this.resourceTypes = resourceTypes; } @SuppressWarnings("deprecation") @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); if (getGrammars() != null) { getGrammars().updateNamespaces(namespaces); } for (final MethodInfo methodInfo : getMethods()) { methodInfo.updateNamespaces(namespaces); } for (final RepresentationInfo representationInfo : getRepresentations()) { representationInfo.updateNamespaces(namespaces); } if (getResources() != null) { getResources().updateNamespaces(namespaces); } for (final ResourceTypeInfo resourceTypeInfo : getResourceTypes()) { resourceTypeInfo.updateNamespaces(namespaces); } for (final FaultInfo faultInfo : getFaults()) { faultInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ @SuppressWarnings("deprecation") public void writeElement(XmlWriter writer) throws SAXException { updateNamespaces(getNamespaces()); for (String key : getNamespaces().keySet()) { writer.forceNSDecl(key, getNamespaces().get(key)); } writer.startElement(APP_NAMESPACE, "application"); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } if (getGrammars() != null) { getGrammars().writeElement(writer); } for (final MethodInfo methodInfo : getMethods()) { methodInfo.writeElement(writer); } for (final RepresentationInfo representationInfo : getRepresentations()) { representationInfo.writeElement(writer); } if (getResources() != null) { getResources().writeElement(writer); } for (final ResourceTypeInfo resourceTypeInfo : getResourceTypes()) { resourceTypeInfo.writeElement(writer); } for (final FaultInfo faultInfo : getFaults()) { faultInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "application"); } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlRepresentation.java0000664000175000017500000011621511757206352031213 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.ext.xml.DomRepresentation; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.TransformRepresentation; import org.restlet.ext.xml.XmlRepresentation; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.DefaultHandler; /** * Root of a WADL description document. For the {@link #getHtmlRepresentation()} * method to work properly, you will certainly have to update your classpath * with a recent version of Apache * Xalan XSLT engine (version 2.7.1 has been successfully tested). This is * due to the XSLT * stylesheet bundled which relies on EXSLT features.
    * * @author Jerome Louvel */ public class WadlRepresentation extends SaxRepresentation { // ------------------- // Content reader part // ------------------- private static class ContentReader extends DefaultHandler implements LexicalHandler { public enum MixedContentState { CDATA, COMMENT, ELEMENT, ENTITY, NONE, TEXT } public enum State { APPLICATION, DOCUMENTATION, FAULT, GRAMMARS, INCLUDE, LINK, METHOD, NONE, OPTION, PARAMETER, REPRESENTATION, REQUEST, RESOURCE, RESOURCES, RESOURCETYPE, RESPONSE } /** The current parsed "application" tag. */ private ApplicationInfo currentApplication; /** The current parsed "documentation" tag. */ private DocumentationInfo currentDocumentation; /** The current parsed "grammars" tag. */ private GrammarsInfo currentGrammars; /** The current parsed "include" tag. */ private IncludeInfo currentInclude; /** The current parsed "link" tag. */ private LinkInfo currentLink; /** The current parsed "method" tag. */ private MethodInfo currentMethod; /** The current mixed content CDataSection. */ private CDATASection currentMixedContentCDataSection; /** The current mixed content node. */ private Node currentMixedContentNode; /** The current parsed "option" tag. */ private OptionInfo currentOption; /** The current parsed "param" tag. */ private ParameterInfo currentParameter; /** The current parsed "representation" tag. */ private RepresentationInfo currentRepresentation; /** The current parsed "request" tag. */ private RequestInfo currentRequest; /** The current parsed "resources" tag. */ private ResourcesInfo currentResources; /** The list of the current parsed "resource" tags. */ private final List currentResourcesList; /** The current parsed "resource_type" tag. */ private ResourceTypeInfo currentResourceType; /** The current parsed "response" tag. */ private ResponseInfo currentResponse; /** The document used to create the mixed content. */ private Document mixedContentDocument; /** The stack of mixed content parser states. */ private final List mixedContentStates; /** The top node of mixed content nodes. */ private Node mixedContentTopNode; /** * Map of namespaces used in the WADL document. The key is the URI of * the namespace and the value, the prefix. */ private Map namespaces; /** The stack of parser states. */ private final List states; /** The WadlRepresentation instance that represents the parsed document. */ private final WadlRepresentation wadlRepresentation; /** * Constructor * * @param wadlRepresentation * The WadlRepresentation instance that represents the parsed * document. */ public ContentReader(WadlRepresentation wadlRepresentation) { this.states = new ArrayList(); this.states.add(State.NONE); this.mixedContentStates = new ArrayList(); this.mixedContentStates.add(MixedContentState.NONE); this.currentApplication = null; this.currentDocumentation = null; this.currentGrammars = null; this.currentInclude = null; this.currentLink = null; this.currentMethod = null; this.currentOption = null; this.currentParameter = null; this.currentRepresentation = null; this.currentRequest = null; this.currentResourcesList = new ArrayList(); this.currentResources = null; this.currentResourceType = null; this.currentResponse = null; try { this.mixedContentDocument = new DomRepresentation( MediaType.TEXT_XML).getDocument(); } catch (IOException e) { } this.currentMixedContentCDataSection = null; this.namespaces = new HashMap(); this.wadlRepresentation = wadlRepresentation; } /** * Receive notification of character data. * * @param ch * The characters from the XML document. * @param start * The start position in the array. * @param length * The number of characters to read from the array. */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (getState() == State.DOCUMENTATION) { if (getMixedContentState() == MixedContentState.CDATA) { this.currentMixedContentCDataSection.appendData(new String( ch, start, length)); } else if (getMixedContentState() != MixedContentState.ENTITY) { this.currentMixedContentNode .appendChild(this.mixedContentDocument .createTextNode(new String(ch, start, length))); } } } /** * Receive notification of a comment section. * * @param ch * The characters from the XML document. * @param start * The start position in the array. * @param length * The number of characters to read from the array. */ public void comment(char[] ch, int start, int length) throws SAXException { if (getState() == State.DOCUMENTATION) { this.currentMixedContentNode .appendChild(this.mixedContentDocument .createComment(new String(ch, start, length))); } } /** * Receive notification of the end of a CDATA sectionn. */ public void endCDATA() throws SAXException { if (getState() == State.DOCUMENTATION) { popMixedContentState(); } } /** * Receive notification of the end of a document. */ @Override public void endDocument() throws SAXException { popState(); if (this.namespaces != null && !this.namespaces.isEmpty() && this.currentApplication != null) { this.currentApplication.setNamespaces(namespaces); } this.wadlRepresentation.setApplication(this.currentApplication); } public void endDTD() throws SAXException { } /** * Receive notification of the end of an element. * * @param uri * The Namespace URI, or the empty string if the element has * no Namespace URI or if Namespace processing is not being * performed. * @param localName * The local name (without prefix), or the empty string if * Namespace processing is not being performed. * @param qName * The qualified XML name (with prefix), or the empty string * if qualified names are not available. */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (uri.equalsIgnoreCase(APP_NAMESPACE)) { if (localName.equals("application")) { popState(); } else if (localName.equals("doc")) { this.currentDocumentation .setMixedContent(mixedContentTopNode); popState(); } else if (localName.equals("fault")) { popState(); } else if (localName.equals("grammars")) { popState(); } else if (localName.equals("include")) { popState(); } else if (localName.equals("link")) { popState(); } else if (localName.equals("method")) { popState(); } else if (localName.equals("option")) { popState(); } else if (localName.equals("param")) { popState(); } else if (localName.equals("representation")) { popState(); } else if (localName.equals("request")) { popState(); } else if (localName.equals("resource")) { this.currentResourcesList.remove(0); popState(); } else if (localName.equals("resources")) { popState(); } else if (localName.equals("resource_type")) { popState(); } else if (localName.equals("response")) { popState(); } } else { if (getState() == State.DOCUMENTATION) { popMixedContentState(); this.currentMixedContentNode = this.currentMixedContentNode .getParentNode(); } } } /** * Receive notification of the end of an entity section. * * @param name * The name of the entity. */ public void endEntity(String name) throws SAXException { popMixedContentState(); } /** * Returns the current state when processing mixed content sections. * * @return The current state when processing mixed content sections. */ private MixedContentState getMixedContentState() { final MixedContentState result = this.mixedContentStates.get(0); return result; } /** * Returns a parameterStyle value according to the given string or null. * * @param parameterStyle * The given string. * @return The parameterStyle value that corresponds to the given style * name, or null otherwise. */ public ParameterStyle getParameterStyle(String parameterStyle) { ParameterStyle result = null; if ("header".equalsIgnoreCase(parameterStyle)) { result = ParameterStyle.HEADER; } else if ("matrix".equalsIgnoreCase(parameterStyle)) { result = ParameterStyle.MATRIX; } else if ("plain".equalsIgnoreCase(parameterStyle)) { result = ParameterStyle.PLAIN; } else if ("query".equalsIgnoreCase(parameterStyle)) { result = ParameterStyle.QUERY; } else if ("template".equalsIgnoreCase(parameterStyle)) { result = ParameterStyle.TEMPLATE; } return result; } /** * Returns the current state when processing the WADL document. * * @return the current state when processing the WADL document. */ private State getState() { final State result = this.states.get(0); return result; } /** * Drops the current state from the stack and returns it. This state * becomes the former current state. * * @return the former current state. */ private MixedContentState popMixedContentState() { return this.mixedContentStates.remove(0); } /** * Drops the current state from the stack and returns it. This state * becomes the former current state. * * @return the former current state. */ private State popState() { return this.states.remove(0); } /** * Adds the given state. * * @param state * The given state. */ private void pushMixedContentState(MixedContentState state) { this.mixedContentStates.add(0, state); } /** * Adds the given state. * * @param state * The given state. */ private void pushState(State state) { this.states.add(0, state); } /** * Receive notification of the beginning of a CDATA section. */ public void startCDATA() throws SAXException { if (getState() == State.DOCUMENTATION) { pushMixedContentState(MixedContentState.CDATA); this.currentMixedContentCDataSection = this.mixedContentDocument .createCDATASection(""); this.currentMixedContentNode .appendChild(this.currentMixedContentCDataSection); } } /** * Receive notification of the beginning of a document. */ @Override public void startDocument() throws SAXException { } public void startDTD(String name, String publicId, String systemId) throws SAXException { } /** * Receive notification of the beginning of an element. * * @param uri * The Namespace URI, or the empty string if the element has * no Namespace URI or if Namespace processing is not being * performed. * @param localName * The local name (without prefix), or the empty string if * Namespace processing is not being performed. * @param qName * The qualified name (with prefix), or the empty string if * qualified names are not available. * @param attrs * The attributes attached to the element. If there are no * attributes, it shall be an empty Attributes object. The * value of this object after startElement returns is * undefined. */ @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (uri.equalsIgnoreCase(APP_NAMESPACE)) { if (localName.equals("application")) { this.currentApplication = new ApplicationInfo(); pushState(State.APPLICATION); } else if (localName.equals("doc")) { this.currentDocumentation = new DocumentationInfo(); this.mixedContentTopNode = this.mixedContentDocument .createDocumentFragment(); this.currentMixedContentNode = mixedContentTopNode; this.currentMixedContentCDataSection = null; if (attrs.getIndex("xml:lang") != -1) { this.currentDocumentation.setLanguage(Language .valueOf(attrs.getValue("xml:lang"))); } if (attrs.getIndex("lang") != -1) { this.currentDocumentation.setLanguage(Language .valueOf(attrs.getValue("lang"))); } if (attrs.getIndex("title") != -1) { this.currentDocumentation.setTitle(attrs .getValue("title")); } if (getState() == State.APPLICATION) { this.currentApplication.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.GRAMMARS) { this.currentGrammars.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.INCLUDE) { this.currentInclude.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.LINK) { this.currentLink.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.METHOD) { this.currentMethod.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.OPTION) { this.currentOption.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.PARAMETER) { this.currentParameter.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.REPRESENTATION) { this.currentRepresentation.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.REQUEST) { this.currentRequest.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.RESOURCE) { this.currentResourcesList.get(0).getDocumentations() .add(this.currentDocumentation); } else if (getState() == State.RESOURCES) { this.currentResources.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.RESOURCETYPE) { this.currentResourceType.getDocumentations().add( this.currentDocumentation); } else if (getState() == State.RESPONSE) { this.currentResponse.getDocumentations().add( this.currentDocumentation); } pushState(State.DOCUMENTATION); } else if (localName.equals("grammars")) { this.currentGrammars = new GrammarsInfo(); if (getState() == State.APPLICATION) { this.currentApplication .setGrammars(this.currentGrammars); } pushState(State.GRAMMARS); } else if (localName.equals("include")) { this.currentInclude = new IncludeInfo(); if (attrs.getIndex("href") != -1) { this.currentInclude.setTargetRef(new Reference(attrs .getValue("href"))); } if (getState() == State.GRAMMARS) { this.currentGrammars.getIncludes().add( this.currentInclude); } pushState(State.INCLUDE); } else if (localName.equals("link")) { this.currentLink = new LinkInfo(); if (attrs.getIndex("rel") != -1) { this.currentLink.setRelationship(attrs.getValue("rel")); } if (attrs.getIndex("rev") != -1) { this.currentLink.setReverseRelationship(attrs .getValue("rev")); } if (attrs.getIndex("resource_type") != -1) { this.currentLink.setResourceType(new Reference(attrs .getValue("resource_type"))); } if (getState() == State.PARAMETER) { this.currentParameter.setLink(this.currentLink); } pushState(State.LINK); } else if (localName.equals("method")) { this.currentMethod = new MethodInfo(); if (attrs.getIndex("href") != -1) { this.currentMethod.setTargetRef(new Reference(attrs .getValue("href"))); } if (attrs.getIndex("id") != -1) { this.currentMethod.setIdentifier(attrs.getValue("id")); } if (attrs.getIndex("name") != -1) { this.currentMethod.setName(Method.valueOf(attrs .getValue("name"))); } if (getState() == State.APPLICATION) { this.currentApplication.getMethods().add( this.currentMethod); } else if (getState() == State.RESOURCE) { this.currentResourcesList.get(0).getMethods().add( this.currentMethod); } else if (getState() == State.RESOURCETYPE) { this.currentResourceType.getMethods().add( this.currentMethod); } pushState(State.METHOD); } else if (localName.equals("option")) { this.currentOption = new OptionInfo(); if (attrs.getIndex("value") != -1) { this.currentOption.setValue(attrs.getValue("value")); } if (getState() == State.PARAMETER) { this.currentParameter.getOptions().add( this.currentOption); } pushState(State.OPTION); } else if (localName.equals("param")) { this.currentParameter = new ParameterInfo(); if (attrs.getIndex("default") != -1) { this.currentParameter.setDefaultValue(attrs .getValue("default")); } if (attrs.getIndex("fixed") != -1) { this.currentParameter.setFixed(attrs.getValue("fixed")); } if (attrs.getIndex("id") != -1) { this.currentParameter.setIdentifier(attrs .getValue("id")); } if (attrs.getIndex("path") != -1) { this.currentParameter.setPath(attrs.getValue("path")); } if (attrs.getIndex("style") != -1) { this.currentParameter.setStyle(getParameterStyle(attrs .getValue("style"))); } if (attrs.getIndex("name") != -1) { this.currentParameter.setName(attrs.getValue("name")); } if (attrs.getIndex("type") != -1) { this.currentParameter.setType(attrs.getValue("type")); } if (attrs.getIndex("repeating") != -1) { this.currentParameter.setRepeating(Boolean .parseBoolean(attrs.getValue("repeating"))); } if (attrs.getIndex("required") != -1) { this.currentParameter.setRequired(Boolean .parseBoolean(attrs.getValue("required"))); } if (getState() == State.REPRESENTATION) { this.currentRepresentation.getParameters().add( this.currentParameter); } else if (getState() == State.REQUEST) { this.currentRequest.getParameters().add( this.currentParameter); } else if (getState() == State.RESOURCE) { this.currentResourcesList.get(0).getParameters().add( this.currentParameter); } else if (getState() == State.RESOURCETYPE) { this.currentRequest.getParameters().add( this.currentParameter); } else if (getState() == State.RESPONSE) { this.currentRequest.getParameters().add( this.currentParameter); } pushState(State.PARAMETER); } else if (localName.equals("representation")) { this.currentRepresentation = new RepresentationInfo(); if (attrs.getIndex("id") != -1) { this.currentRepresentation.setIdentifier(attrs .getValue("id")); } if (attrs.getIndex("mediaType") != -1) { this.currentRepresentation.setMediaType(MediaType .valueOf(attrs.getValue("mediaType"))); } if (attrs.getIndex("element") != -1) { this.currentRepresentation.setXmlElement(attrs .getValue("element")); } if (attrs.getIndex("profile") != -1) { final String[] profiles = attrs.getValue("profile") .split(" "); for (final String string : profiles) { this.currentRepresentation.getProfiles().add( new Reference(string)); } } if (getState() == State.APPLICATION) { this.currentApplication.getRepresentations().add( this.currentRepresentation); } else if (getState() == State.REQUEST) { this.currentRequest.getRepresentations().add( this.currentRepresentation); } else if (getState() == State.RESPONSE) { this.currentResponse.getRepresentations().add( this.currentRepresentation); } pushState(State.REPRESENTATION); } else if (localName.equals("request")) { this.currentRequest = new RequestInfo(); if (getState() == State.METHOD) { this.currentMethod.setRequest(this.currentRequest); } pushState(State.REQUEST); } else if (localName.equals("resource")) { final ResourceInfo resourceInfo = new ResourceInfo(); if (attrs.getIndex("id") != -1) { resourceInfo.setIdentifier(attrs.getValue("id")); } if (attrs.getIndex("path") != -1) { resourceInfo.setPath(attrs.getValue("path")); } if (attrs.getIndex("queryType") != -1) { resourceInfo.setQueryType(MediaType.valueOf(attrs .getValue("queryType"))); } if (attrs.getIndex("type") != -1) { final String[] type = attrs.getValue("type").split(" "); for (final String string : type) { resourceInfo.getType().add(new Reference(string)); } } if (getState() == State.RESOURCE) { this.currentResourcesList.get(0).getChildResources() .add(resourceInfo); } else if (getState() == State.RESOURCES) { this.currentResources.getResources().add(resourceInfo); } this.currentResourcesList.add(0, resourceInfo); pushState(State.RESOURCE); } else if (localName.equals("resources")) { this.currentResources = new ResourcesInfo(); if (attrs.getIndex("base") != -1) { this.currentResources.setBaseRef(new Reference(attrs .getValue("base"))); } if (getState() == State.APPLICATION) { this.currentApplication .setResources(this.currentResources); } pushState(State.RESOURCES); } else if (localName.equals("resource_type")) { this.currentResourceType = new ResourceTypeInfo(); if (attrs.getIndex("id") != -1) { this.currentResourceType.setIdentifier(attrs .getValue("id")); } if (getState() == State.APPLICATION) { this.currentApplication.getResourceTypes().add( this.currentResourceType); } pushState(State.RESOURCETYPE); } else if (localName.equals("response")) { this.currentResponse = new ResponseInfo(); if (attrs.getIndex("status") != -1) { final String[] statuses = attrs.getValue("status") .split(" "); for (final String string : statuses) { this.currentResponse.getStatuses().add( Status.valueOf(Integer.parseInt(string))); } } if (getState() == State.METHOD) { this.currentMethod.getResponses().add( this.currentResponse); } pushState(State.RESPONSE); } } else { if (getState() == State.DOCUMENTATION) { // We are handling a new element pushMixedContentState(MixedContentState.ELEMENT); Node node = null; if (("".equals(qName) || qName == null)) { node = this.mixedContentDocument.createElementNS(uri, localName); } else { node = this.mixedContentDocument.createElementNS(uri, qName); } for (int i = 0; i < attrs.getLength(); i++) { Attr attr = this.mixedContentDocument .createAttributeNS(attrs.getURI(i), attrs .getLocalName(i)); attr.setNodeValue(attrs.getValue(i)); node.getAttributes().setNamedItemNS(attr); } // This element becomes the current one and is added to its // parent. this.currentMixedContentNode.appendChild(node); this.currentMixedContentNode = node; } } } /** * Receive notification of the beginning of an entity. * * @param name * The name of the entity. */ public void startEntity(String name) throws SAXException { pushMixedContentState(MixedContentState.ENTITY); this.currentMixedContentNode.appendChild(mixedContentDocument .createEntityReference(name)); } /** * Receive notification of the beginning of a prefix-URI Namespace * mapping. * * @param name * The name of the entity. */ @Override public void startPrefixMapping(String arg0, String arg1) throws SAXException { this.namespaces.put(arg1, arg0); } } /** Web Application Description Language namespace. */ public static final String APP_NAMESPACE = "http://wadl.dev.java.net/2009/02"; /** The root element of the WADL document. */ private ApplicationInfo application; /** * Constructor. */ public WadlRepresentation() { super(MediaType.APPLICATION_WADL); setNamespaceAware(true); } /** * Constructor. * * @param application * The root element of the WADL document. */ public WadlRepresentation(ApplicationInfo application) { super(MediaType.APPLICATION_WADL); setNamespaceAware(true); this.application = application; } /** * Constructor. * * @param xmlRepresentation * The XML WADL document. * @throws IOException */ public WadlRepresentation(Representation xmlRepresentation) throws IOException { super(xmlRepresentation); setNamespaceAware(true); setMediaType(MediaType.APPLICATION_WADL); // Parse the given document using SAX to produce an ApplicationInfo // instance. parse(new ContentReader(this)); } /** * Constructor. The title of the resource, that is to say the title of its * first documentation tag is transfered to the title of the first * documentation tag of the main application tag. * * @param resource * The root element of the WADL document. */ public WadlRepresentation(ResourceInfo resource) { super(MediaType.APPLICATION_WADL); setNamespaceAware(true); this.application = resource.createApplication(); } @Override public Object evaluate(String expression, javax.xml.namespace.QName returnType) throws Exception { return null; } /** * Returns the root element of the WADL document. * * @return The root element of the WADL document. */ public ApplicationInfo getApplication() { return this.application; } /** * Returns an HTML representation. Note that the internal XSLT stylesheet * used comes from Mark * Nottingham. This stylesheet requires advanced XSLT features, * including EXSLT extensions. Usage of a recent version of Xalan-J is * suggested. It has been tested successfully with Xalan-J 2.7.1. * * @return An HTML representation. */ public Representation getHtmlRepresentation() { Representation representation = null; URL wadl2htmlXsltUrl = Engine .getResource("org/restlet/ext/wadl/wadl2html.xslt"); if (wadl2htmlXsltUrl != null) { try { InputRepresentation xslRep = new InputRepresentation( wadl2htmlXsltUrl.openStream(), MediaType.APPLICATION_W3C_XSLT); representation = new TransformRepresentation(Context .getCurrent(), this, xslRep); representation.setMediaType(MediaType.TEXT_HTML); } catch (IOException e) { Context.getCurrent().getLogger().log(Level.WARNING, "Unable to generate the WADL HTML representation", e); } } return representation; } @Override public javax.xml.transform.sax.SAXSource getSaxSource() throws IOException { return XmlRepresentation.getSaxSource(this); } /** * Sets the root element of the WADL document. * * @param application * The root element of the WADL document. */ public void setApplication(ApplicationInfo application) { this.application = application; } @Override public void write(XmlWriter writer) throws IOException { try { writer.forceNSDecl(APP_NAMESPACE, ""); writer.setDataFormat(true); writer.setIndentStep(3); writer.processingInstruction("xml", "version=\"1.0\" standalone=\"yes\""); writer.processingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"wadl2html.xslt\""); this.application.writeElement(writer); writer.endDocument(); } catch (SAXException e) { Context.getCurrentLogger().log(Level.SEVERE, "Error when writing the WADL Representation.", e); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlConverter.java0000664000175000017500000001011311757206352030146 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import java.io.IOException; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * A converter helper to convert between {@link ApplicationInfo} objects and * {@link WadlRepresentation} ones. * * @author Thierry Boileau */ public class WadlConverter extends ConverterHelper { private static final VariantInfo VARIANT_APPLICATION_WADL = new VariantInfo( MediaType.APPLICATION_WADL); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_APPLICATION_WADL.includes(source)) { result = addObjectClass(result, ApplicationInfo.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (ApplicationInfo.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_APPLICATION_WADL); } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if ((source != null) && (ApplicationInfo.class.isAssignableFrom(target))) { result = 1.0F; } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { if (source instanceof ApplicationInfo) { return 1.0f; } return -1.0f; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (ApplicationInfo.class.isAssignableFrom(target)) { if (source instanceof WadlRepresentation) { result = ((WadlRepresentation) source).getApplication(); } else { result = new WadlRepresentation(source).getApplication(); } } return target.cast(result); } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { if (source instanceof ApplicationInfo) { return new WadlRepresentation((ApplicationInfo) source); } return null; } @Override public void updatePreferences(List> preferences, Class entity) { if (ApplicationInfo.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_WADL, 1.0F); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/LinkInfo.java0000664000175000017500000001401011757206352027100 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.List; import java.util.Map; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Allows description of links between representations and resources. * * @author Jerome Louvel */ public class LinkInfo extends DocumentedInfo { /** * Identifies the relationship of the resource identified by the link to the * resource whose representation the link is embedded in. */ private String relationship; /** * Defines the capabilities of the resource that the link identifies. */ private Reference resourceType; /** * Identifies the relationship of the resource whose representation the link * is embedded in to the resource identified by the link. */ private String reverseRelationship; /** * Constructor. */ public LinkInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public LinkInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public LinkInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public LinkInfo(String documentation) { super(documentation); } /** * Returns the relationship attribute value. * * @return The relationship attribute value. */ public String getRelationship() { return this.relationship; } /** * Returns the reference to the resource type of the linked resource. * * @return The reference to the resource type of the linked resource. */ public Reference getResourceType() { return this.resourceType; } /** * Returns the reverse relationship attribute value. * * @return The reverse relationship attribute value. */ public String getReverseRelationship() { return this.reverseRelationship; } /** * Sets the relationship attribute value. * * @param relationship * The relationship attribute value. */ public void setRelationship(String relationship) { this.relationship = relationship; } /** * Sets the reference to the resource type of the linked resource. * * @param resourceType * The reference to the resource type of the linked resource. */ public void setResourceType(Reference resourceType) { this.resourceType = resourceType; } /** * Sets the reverse relationship attribute value. * * @param reverseRelationship * The reverse relationship attribute value. */ public void setReverseRelationship(String reverseRelationship) { this.reverseRelationship = reverseRelationship; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getRelationship() != null) && !getRelationship().equals("")) { attributes.addAttribute("", "rel", null, "xs:token", getRelationship()); } if ((getReverseRelationship() != null) && !getReverseRelationship().equals("")) { attributes.addAttribute("", "rev", null, "xs:token", getReverseRelationship()); } if ((getResourceType() != null) && (getResourceType().toString() != null)) { attributes.addAttribute("", "resource_type", null, "xs:anyURI", getResourceType().toString()); } if (getDocumentations().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "link", null, attributes); } else { writer.startElement(APP_NAMESPACE, "link", null, attributes); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "link"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/ResponseInfo.java0000664000175000017500000002162011757206352030006 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.restlet.data.Status; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Describes the properties of a response associated to a parent method. * * @author Jerome Louvel */ public class ResponseInfo extends DocumentedInfo { /** * List of faults (representations that denote an error condition). * * @deprecated According to new WADL specification, the fault element has * been removed. */ @Deprecated private List faults; /** List of parameters. */ private List parameters; /** List of representations. */ private List representations; /** * List of statuses associated with this response representation. */ private List statuses; /** * Constructor. */ public ResponseInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResponseInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public ResponseInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public ResponseInfo(String documentation) { super(documentation); } /** * Returns the list of faults (representations that denote an error * condition). * * @return The list of faults (representations that denote an error * condition). * @deprecated According to new WADL specification, the fault element has * been removed. */ @Deprecated public List getFaults() { // Lazy initialization with double-check. List f = this.faults; if (f == null) { synchronized (this) { f = this.faults; if (f == null) { this.faults = f = new ArrayList(); } } } return f; } /** * Returns the list of parameters. * * @return The list of parameters. */ public List getParameters() { // Lazy initialization with double-check. List p = this.parameters; if (p == null) { synchronized (this) { p = this.parameters; if (p == null) { this.parameters = p = new ArrayList(); } } } return p; } /** * Returns the list of representations * * @return The list of representations */ public List getRepresentations() { // Lazy initialization with double-check. List r = this.representations; if (r == null) { synchronized (this) { r = this.representations; if (r == null) { this.representations = r = new ArrayList(); } } } return r; } /** * Returns the list of statuses associated with this response * representation. * * @return The list of statuses associated with this response * representation. */ public List getStatuses() { // Lazy initialization with double-check. List s = this.statuses; if (s == null) { synchronized (this) { s = this.statuses; if (s == null) { this.statuses = s = new ArrayList(); } } } return s; } /** * Sets the list of faults (representations that denote an error condition). * * @param faults * The list of faults (representations that denote an error * condition). * @deprecated According to new WADL specification, the fault element has * been removed. */ @Deprecated public void setFaults(List faults) { this.faults = faults; } /** * Sets the list of parameters. * * @param parameters * The list of parameters. */ public void setParameters(List parameters) { this.parameters = parameters; } /** * Sets the list of representations * * @param representations * The list of representations */ public void setRepresentations(List representations) { this.representations = representations; } /** * Sets the list of statuses associated with this response representation. * * @param statuses * The list of statuses associated with this response * representation. */ public void setStatuses(List statuses) { this.statuses = statuses; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); for (final RepresentationInfo representationInfo : getRepresentations()) { representationInfo.updateNamespaces(namespaces); } for (final RepresentationInfo faultInfo : getFaults()) { faultInfo.updateNamespaces(namespaces); } for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { AttributesImpl attributes = new AttributesImpl(); if ((getStatuses() != null) && !getStatuses().isEmpty()) { StringBuilder builder = new StringBuilder(); for (Iterator iterator = getStatuses().iterator(); iterator .hasNext();) { Status status = iterator.next(); builder.append(status.getCode()); if (iterator.hasNext()) { builder.append(" "); } } attributes.addAttribute("", "status", null, "xs:string", builder .toString()); } if (getDocumentations().isEmpty() && getParameters().isEmpty() && getRepresentations().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "response", null, attributes); } else { writer.startElement(APP_NAMESPACE, "response", null, attributes); for (DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (ParameterInfo parameterInfo : getParameters()) { parameterInfo.writeElement(writer); } for (RepresentationInfo representationInfo : getRepresentations()) { representationInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "response"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/FaultInfo.java0000664000175000017500000000650711757206352027272 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Status; /** * Describes an error condition for response descriptions. * * @author Jerome Louvel * @deprecated This element has been removed from the WADL specification. */ @Deprecated public class FaultInfo extends RepresentationInfo { /** * Constructor. * * @param status * The associated status code. */ public FaultInfo(Status status) { super(); getStatuses().add(status); } /** * Constructor with a single documentation element. * * @param status * The associated status code. * @param documentation * A single documentation element. */ public FaultInfo(Status status, DocumentationInfo documentation) { super(documentation); getStatuses().add(status); } /** * Constructor with a list of documentation elements. * * @param status * The associated status code. * @param documentations * The list of documentation elements. */ public FaultInfo(Status status, List documentations) { super(documentations); getStatuses().add(status); } /** * Constructor with a single documentation element. * * @param status * The associated status code. * @param documentation * A single documentation element. */ public FaultInfo(Status status, String documentation) { this(status, new DocumentationInfo(documentation)); } /** * Constructor with a single documentation element. * * @param status * The associated status code. * @param mediaType * The fault representation's media type. * @param documentation * A single documentation element. */ public FaultInfo(Status status, MediaType mediaType, String documentation) { this(status, new DocumentationInfo(documentation)); setMediaType(mediaType); } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/RequestInfo.java0000664000175000017500000001326511757206352027646 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; /** * Describes the properties of a request associated to a parent method. * * @author Jerome Louvel */ public class RequestInfo extends DocumentedInfo { /** List of parameters. */ private List parameters; /** List of supported input representations. */ private List representations; /** * Constructor. */ public RequestInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public RequestInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public RequestInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public RequestInfo(String documentation) { super(documentation); } /** * Returns the list of parameters. * * @return The list of parameters. */ public List getParameters() { // Lazy initialization with double-check. List p = this.parameters; if (p == null) { synchronized (this) { p = this.parameters; if (p == null) { this.parameters = p = new ArrayList(); } } } return p; } /** * Returns the list of supported input representations. * * @return The list of supported input representations. */ public List getRepresentations() { // Lazy initialization with double-check. List r = this.representations; if (r == null) { synchronized (this) { r = this.representations; if (r == null) { this.representations = r = new ArrayList(); } } } return r; } /** * Sets the list of parameters. * * @param parameters * The list of parameters. */ public void setParameters(List parameters) { this.parameters = parameters; } /** * Sets the list of supported input representations. * * @param representations * The list of supported input representations. */ public void setRepresentations(List representations) { this.representations = representations; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.updateNamespaces(namespaces); } for (final RepresentationInfo representationInfo : getRepresentations()) { representationInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { if (getDocumentations().isEmpty() && getParameters().isEmpty() && getRepresentations().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "request"); } else { writer.startElement(APP_NAMESPACE, "request"); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (final ParameterInfo parameterInfo : getParameters()) { parameterInfo.writeElement(writer); } for (final RepresentationInfo representationInfo : getRepresentations()) { representationInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "request"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/package.html0000664000175000017500000000101711757206352027010 0ustar jamespagejamespage Support the WADL specification. WADL allows you to describe your applications RESTfully.
    This extension allows you to configure a Restlet component or application based on a WADL/XML document or to dynamically generate the WADL/XML document of an existing Restlet application. It also knows how to convert this WADL/XML document into a user friendly HTML document.

    @since Restlet 1.1 @see Web Application Description Language (WADL) restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/GrammarsInfo.java0000664000175000017500000001073711757206352027770 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; /** * Describes the grammars used by representation descriptions. This is * especially useful to formally describe XML representations using XML Schema * or Relax NG standards. * * @author Jerome Louvel */ public class GrammarsInfo extends DocumentedInfo { /** Definitions of data format descriptions to be included by reference. */ private List includes; /** * Constructor. */ public GrammarsInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public GrammarsInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public GrammarsInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public GrammarsInfo(String documentation) { super(documentation); } /** * Returns the list of include elements. * * @return The list of include elements. */ public List getIncludes() { // Lazy initialization with double-check. List i = this.includes; if (i == null) { synchronized (this) { i = this.includes; if (i == null) { this.includes = i = new ArrayList(); } } } return i; } /** * Sets the list of include elements. * * @param includes * The list of include elements. */ public void setIncludes(List includes) { this.includes = includes; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); for (final IncludeInfo includeInfo : getIncludes()) { includeInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { if (getDocumentations().isEmpty() && getIncludes().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "grammars"); } else { writer.startElement(APP_NAMESPACE, "grammars"); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (final IncludeInfo includeInfo : getIncludes()) { includeInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "grammars"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/MethodInfo.java0000664000175000017500000004252311757206352027435 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.resource.AnnotationInfo; import org.restlet.engine.resource.AnnotationUtils; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.restlet.service.MetadataService; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Describes the expected requests and responses of a resource method. * * @author Jerome Louvel */ public class MethodInfo extends DocumentedInfo { /** * Automatically describe a method by discovering the resource's * annotations. * * @param info * The method description to update. * @param resource * The server resource to describe. */ public static void describeAnnotations(MethodInfo info, ServerResource resource) { // Loop over the annotated Java methods MetadataService metadataService = resource.getMetadataService(); List annotations = resource.isAnnotated() ? AnnotationUtils .getAnnotations(resource.getClass()) : null; if (annotations != null && metadataService != null) { for (AnnotationInfo annotationInfo : annotations) { if (info.getName().equals(annotationInfo.getRestletMethod())) { // Describe the request Class[] classes = annotationInfo.getJavaInputTypes(); List requestVariants = annotationInfo .getRequestVariants(resource.getMetadataService(), resource.getConverterService()); if (requestVariants != null) { for (Variant variant : requestVariants) { if ((variant.getMediaType() != null) && ((info.getRequest() == null) || !info .getRequest().getRepresentations() .contains(variant))) { RepresentationInfo representationInfo = null; if (info.getRequest() == null) { info.setRequest(new RequestInfo()); } if (resource instanceof WadlServerResource) { representationInfo = ((WadlServerResource) resource) .describe(info, info.getRequest(), classes[0], variant); } else { representationInfo = new RepresentationInfo( variant); } info.getRequest().getRepresentations().add( representationInfo); } } } // Describe the response Class outputClass = annotationInfo.getJavaOutputType(); if (outputClass != null) { List responseVariants = annotationInfo .getResponseVariants(resource .getMetadataService(), resource .getConverterService()); if (responseVariants != null) { for (Variant variant : responseVariants) { if ((variant.getMediaType() != null) && !info.getResponse() .getRepresentations().contains( variant)) { RepresentationInfo representationInfo = null; if (resource instanceof WadlServerResource) { representationInfo = ((WadlServerResource) resource) .describe(info, info .getResponse(), outputClass, variant); } else { representationInfo = new RepresentationInfo( variant); } info.getResponse().getRepresentations() .add(representationInfo); } } } } } } } } /** Identifier for the method. */ private String identifier; /** Name of the method. */ private Method name; /** Describes the input to the method. */ private RequestInfo request; /** Describes the output of the method. */ private List responses; /** Reference to a method definition element. */ private Reference targetRef; /** * Constructor. */ public MethodInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public MethodInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public MethodInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public MethodInfo(String documentation) { super(documentation); } /** * Adds a new fault to the response. * * @param status * The associated status code. * @param mediaType * The fault representation's media type. * @param documentation * A single documentation element. * @return The created fault description. * @deprecated Use the {@link ResponseInfo#getRepresentations()} method * instead. */ @Deprecated public RepresentationInfo addFault(Status status, MediaType mediaType, String documentation) { RepresentationInfo result = new RepresentationInfo(documentation); result.setMediaType(mediaType); getResponse().getStatuses().add(status); getResponse().getRepresentations().add(result); return result; } /** * Adds a new request parameter. * * @param name * The name of the parameter. * @param required * True if thes parameter is required. * @param type * The type of the parameter. * @param style * The style of the parameter. * @param documentation * A single documentation element. * @return The created parameter description. * @deprecated Use {@link RequestInfo#getParameters()} instead. */ @Deprecated public ParameterInfo addRequestParameter(String name, boolean required, String type, ParameterStyle style, String documentation) { ParameterInfo result = new ParameterInfo(name, required, type, style, documentation); if (getRequest() == null) { setRequest(new RequestInfo()); } getRequest().getParameters().add(result); return result; } /** * Adds a new request representation based on a given variant. * * @param variant * The variant to describe. * @return The created representation description. * @deprecated Use {@link RequestInfo#getRepresentations()} instead. */ @Deprecated public RepresentationInfo addRequestRepresentation(Variant variant) { RepresentationInfo result = new RepresentationInfo(variant); if (getRequest() == null) { setRequest(new RequestInfo()); } getRequest().getRepresentations().add(result); return result; } /** * Adds a new response parameter. * * @param name * The name of the parameter. * @param required * True if the parameter is required. * @param type * The type of the parameter. * @param style * The style of the parameter. * @param documentation * A single documentation element. * @return The created parameter description. * @deprecated Use the {@link ResponseInfo#getParameters()} method instead. */ @Deprecated public ParameterInfo addResponseParameter(String name, boolean required, String type, ParameterStyle style, String documentation) { ParameterInfo result = new ParameterInfo(name, required, type, style, documentation); getResponse().getParameters().add(result); return result; } /** * Adds a new response representation based on a given variant. * * @param variant * The variant to describe. * @return The created representation description. * @deprecated Use {@link ResponseInfo#getRepresentations()} instead. */ @Deprecated public RepresentationInfo addResponseRepresentation(Variant variant) { RepresentationInfo result = new RepresentationInfo(variant); getResponse().getRepresentations().add(result); return result; } /** * Returns the identifier for the method. * * @return The identifier for the method. */ public String getIdentifier() { return this.identifier; } /** * Returns the name of the method. * * @return The name of the method. */ public Method getName() { return this.name; } /** * Returns the input to the method. * * @return The input to the method. */ public RequestInfo getRequest() { return this.request; } /** * Returns the last added response of the method. * * @return The last added response of the method. */ public ResponseInfo getResponse() { if (getResponses().isEmpty()) { getResponses().add(new ResponseInfo()); } return getResponses().get(getResponses().size() - 1); } /** * Returns the output of the method. * * @return The output of the method. */ public List getResponses() { // Lazy initialization with double-check. List r = this.responses; if (r == null) { synchronized (this) { r = this.responses; if (r == null) { this.responses = r = new ArrayList(); } } } return r; } /** * Returns the reference to a method definition element. * * @return The reference to a method definition element. */ public Reference getTargetRef() { return this.targetRef; } /** * Sets the identifier for the method. * * @param identifier * The identifier for the method. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Sets the name of the method. * * @param name * The name of the method. */ public void setName(Method name) { this.name = name; } /** * Sets the input to the method. * * @param request * The input to the method. */ public void setRequest(RequestInfo request) { this.request = request; } /** * Sets the output of the method. * * @param response * The output of the method. * @deprecated Use the {@link #getResponses()} or * {@link #setResponses(List)} methods instead. */ @Deprecated public void setResponsee(ResponseInfo response) { setResponses(new ArrayList()); getResponses().add(response); } /** * Sets the output of the method. * * @param responses * The output of the method. */ public void setResponses(List responses) { this.responses = responses; } /** * Sets the reference to a method definition element. * * @param targetRef * The reference to a method definition element. */ public void setTargetRef(Reference targetRef) { this.targetRef = targetRef; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); if (getRequest() != null) { getRequest().updateNamespaces(namespaces); } if (!getResponses().isEmpty()) { for (ResponseInfo response : getResponses()) { response.updateNamespaces(namespaces); } } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ @SuppressWarnings("deprecation") public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getIdentifier() != null) && !getIdentifier().equals("")) { attributes.addAttribute("", "id", null, "xs:ID", getIdentifier()); } if ((getName() != null) && (getName().toString() != null)) { attributes.addAttribute("", "name", null, "xs:NMTOKEN", getName() .toString()); } if ((getTargetRef() != null) && (getTargetRef().toString() != null)) { attributes.addAttribute("", "href", null, "xs:anyURI", getTargetRef().toString()); } if (getDocumentations().isEmpty() && (getRequest() == null) && (getResponses().isEmpty())) { writer.emptyElement(APP_NAMESPACE, "method", null, attributes); } else { writer.startElement(APP_NAMESPACE, "method", null, attributes); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } if (getRequest() != null) { getRequest().writeElement(writer); } if (!getResponses().isEmpty()) { for (ResponseInfo response : getResponses()) { response.writeElement(writer); // TODO to be removed with the FaultInfo class // Each response's fault generates a new Response if (!response.getFaults().isEmpty()) { for (FaultInfo faultInfo : response.getFaults()) { ResponseInfo r = new ResponseInfo(); // Get the statuses from the faults for (Status status : faultInfo.getStatuses()) { if (!r.getStatuses().contains(status)) { r.getStatuses().add(status); } } r.getRepresentations().add(faultInfo); r.writeElement(writer); } } } } writer.endElement(APP_NAMESPACE, "method"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/OptionInfo.java0000664000175000017500000000767311757206352027474 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.List; import java.util.Map; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Defines a potential value for a parent parameter description. * * @author Jerome Louvel */ public class OptionInfo extends DocumentedInfo { /** Value of this option element. */ private String value; /** * Constructor. */ public OptionInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public OptionInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public OptionInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public OptionInfo(String documentation) { super(documentation); } /** * Returns the value of this option element. * * @return The value of this option element. */ public String getValue() { return this.value; } /** * Sets the value of this option element. * * @param value * The value of this option element. */ public void setValue(String value) { this.value = value; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getValue() != null) && !getValue().equals("")) { attributes.addAttribute("", "id", null, "xs:string", getValue()); } if (getDocumentations().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "option", null, attributes); } else { writer.startElement(APP_NAMESPACE, "option", null, attributes); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "option"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlWrapper.java0000664000175000017500000000464411757206352027633 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import org.restlet.Restlet; import org.restlet.resource.Directory; import org.restlet.util.WrapperRestlet; /** * WADL wrapper for {@link Restlet} instances. Useful if you need to provide the * WADL documentation for instances of classes such as {@link Directory}. * * @author Thierry Boileau */ public abstract class WadlWrapper extends WrapperRestlet implements WadlDescribable { /** The description of the wrapped Restlet. */ private ResourceInfo resourceInfo; /** * Constructor. * * @param wrappedRestlet * The Restlet to wrap. */ public WadlWrapper(Restlet wrappedRestlet) { super(wrappedRestlet); } /** * Returns the description of the wrapped Restlet. * * @return The ResourceInfo object of the wrapped Restlet. */ public ResourceInfo getResourceInfo() { return this.resourceInfo; } /** * Sets the description of the wrapped Restlet. * * @param resourceInfo * The ResourceInfo object of the wrapped Restlet. */ public void setResourceInfo(ResourceInfo resourceInfo) { this.resourceInfo = resourceInfo; } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/wadl2html.xslt0000664000175000017500000010575611757206352027360 0ustar jamespagejamespage http://wadl.dev.java.net/2009/02 # # # <xsl:choose> <xsl:when test="wadl:doc[@title]"> <xsl:value-of select="wadl:doc[@title][1]/@title"/> </xsl:when> <xsl:otherwise>My Web Application</xsl:otherwise> </xsl:choose>

    My Web Application

    Resources

    Representations

    Faults

    /
  • / ;=...

    & ? & ?

    resource-wide template resource-wide matrix
    Methods

    request query request header

    acceptable request representations:

    response header

    available response representations:

    potential faults:

  • XML Schema
    plain header
    parameters
    parameter value description

    (required) (repeating)

    One of:

    Default:

    Fixed:

    • XPath to value:
  • Link:
  • (default)
  • (default)
    0

    Source:

    { } ( Status Code - - ) Status Code - ( ) < > </> /> ="" restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlApplication.java0000664000175000017500000007630111757206352030455 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Application; 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.ClientInfo; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.Directory; import org.restlet.resource.Finder; import org.restlet.resource.ServerResource; import org.restlet.routing.Filter; import org.restlet.routing.Route; import org.restlet.routing.Router; import org.restlet.routing.VirtualHost; /** * WADL enabled application. This {@link Application} subclass can describe * itself in WADL by introspecting its content, supporting the standard WADL/XML * format or a WADL/HTML one based on a built-in XSLT transformation. You can * obtain this representation with an OPTIONS request addressed exactly to the * application URI (e.g. "http://host:port/path/to/application"). By default, * the returned representation gleans the list of all attached * {@link ServerResource} classes and calls {@link #getName()} to get the title * and {@link #getDescription()} the textual content of the WADL document * generated. This default behavior can be customized by overriding the * {@link #getApplicationInfo(Request, Response)} method.
    *
    * In case you want to customize the XSLT stylesheet, you can override the * {@link #createWadlRepresentation(ApplicationInfo)} method and return an * instance of an {@link WadlRepresentation} subclass overriding the * {@link WadlRepresentation#getHtmlRepresentation()} method.
    *
    * In addition, this class can create an instance and configure it with an * user-provided WADL/XML document. In this case, it creates a root * {@link Router} and for each resource found in the WADL document, it tries to * attach a {@link ServerResource} class to the router using its WADL path. For * this, it looks up the qualified name of the {@link ServerResource} subclass * using the WADL's "id" attribute of the "resource" elements. This is the only * Restlet specific convention on the original WADL document.
    *
    * To attach an application configured in this way to an existing component, you * can call the {@link #attachToComponent(Component)} or the * {@link #attachToHost(VirtualHost)} methods. In this case, it uses the "base" * attribute of the WADL "resources" element as the URI attachment path to the * virtual host.
    *
    * For the HTML description to work properly, you will certainly have to update * your classpath with a recent version of Apache Xalan XSLT engine (version * 2.7.1 has been successfully tested). This is due to the XSLT stylesheet bundled * which relies on EXSLT features.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables.
    * * @author Jerome Louvel */ @SuppressWarnings("deprecation") public class WadlApplication extends Application { /** * Indicates if the application should be automatically described via WADL * when an OPTIONS request handles a "*" target URI. */ private volatile boolean autoDescribing; /** The WADL base reference. */ private volatile Reference baseRef; /** The router to {@link ServerResource} classes. */ private volatile Router router; /** * The title of this documented application. Is seen as the title of its * first "doc" tag in a WADL document or as the title of the HTML * representation. */ private volatile String title; /** * Creates an application that can automatically introspect and expose * itself as with a WADL description upon reception of an OPTIONS request on * the "*" target URI. */ public WadlApplication() { this((Context) null); } /** * Creates an application that can automatically introspect and expose * itself as with a WADL description upon reception of an OPTIONS request on * the "*" target URI. * * @param context * The context to use based on parent component context. This * context should be created using the * {@link Context#createChildContext()} method to ensure a proper * isolation with the other applications. */ public WadlApplication(Context context) { super(context); this.autoDescribing = true; } /** * Creates an application described using a WADL document. Creates a router * where Resource classes are attached and set it as the root Restlet. * * By default the application is not automatically described. If you want * to, you can call {@link #setAutoDescribing(boolean)}. * * @param context * The context to use based on parent component context. This * context should be created using the * {@link Context#createChildContext()} method to ensure a proper * isolation with the other applications. * @param wadl * The WADL description document. */ public WadlApplication(Context context, Representation wadl) { super(context); this.autoDescribing = false; try { // Instantiates a WadlRepresentation of the WADL document WadlRepresentation wadlRep = null; if (wadl instanceof WadlRepresentation) { wadlRep = (WadlRepresentation) wadl; } else { wadlRep = new WadlRepresentation(wadl); } final Router root = new Router(getContext()); this.router = root; setInboundRoot(root); if (wadlRep.getApplication() != null) { if (wadlRep.getApplication().getResources() != null) { for (final ResourceInfo resource : wadlRep.getApplication() .getResources().getResources()) { attachResource(resource, null, this.router); } // Analyzes the WADL resources base setBaseRef(wadlRep.getApplication().getResources() .getBaseRef()); } // Set the title of the application as the title of the first // documentation tag. if (!wadlRep.getApplication().getDocumentations().isEmpty()) { this.title = wadlRep.getApplication().getDocumentations() .get(0).getTitle(); } } } catch (Exception e) { getLogger().log(Level.WARNING, "Error during the attachment of the WADL application", e); } } /** * Creates an application described using a WADL document. Creates a router * where Resource classes are attached and set it as the root Restlet. * * By default the application is not automatically described. If you want * to, you can call {@link #setAutoDescribing(boolean)}. * * @param wadl * The WADL description document. */ public WadlApplication(Representation wadl) { this(null, wadl); } /** * Adds the necessary server connectors to the component. * * @param component * The parent component to update. */ private void addConnectors(Component component) { // Create the server connector Protocol protocol = getBaseRef().getSchemeProtocol(); int port = getBaseRef().getHostPort(); boolean exists = false; if (port == -1) { for (Server server : component.getServers()) { if (server.getProtocols().contains(protocol) && (server.getPort() == protocol.getDefaultPort())) { exists = true; } } if (!exists) { component.getServers().add(protocol); } } else { for (Server server : component.getServers()) { if (server.getProtocols().contains(protocol) && (server.getPort() == port)) { exists = true; } } if (!exists) { component.getServers().add(protocol, port); } } } /** * Attaches a resource, as specified in a WADL document, to a specified * router, then recursively attaches its child resources. * * @param currentResource * The resource to attach. * @param parentResource * The parent resource. Needed to correctly resolve the "path" of * the resource. Should be null if the resource is root-level. * @param router * The router to which to attach the resource and its children. * @throws ClassNotFoundException * If the class name specified in the "id" attribute of the * resource does not exist, this exception will be thrown. */ private void attachResource(ResourceInfo currentResource, ResourceInfo parentResource, Router router) throws ClassNotFoundException { String uriPattern = currentResource.getPath(); // If there is a parentResource, add its uriPattern to this one if (parentResource != null) { String parentUriPattern = parentResource.getPath(); if ((parentUriPattern.endsWith("/") == false) && (uriPattern.startsWith("/") == false)) { parentUriPattern += "/"; } uriPattern = parentUriPattern + uriPattern; currentResource.setPath(uriPattern); } else if (!uriPattern.startsWith("/")) { uriPattern = "/" + uriPattern; currentResource.setPath(uriPattern); } Finder finder = createFinder(router, uriPattern, currentResource); if (finder != null) { // Attach the resource itself router.attach(uriPattern, finder); } // Attach children of the resource for (ResourceInfo childResource : currentResource.getChildResources()) { attachResource(childResource, currentResource, router); } } /** * Attaches the application to the given component if the application has a * WADL base reference. The application will be attached to an existing * virtual host if possible, otherwise a new one will be created. * * @param component * The parent component to update. * @return The parent virtual host. */ public VirtualHost attachToComponent(Component component) { VirtualHost result = null; if (getBaseRef() != null) { // Create the virtual host result = getVirtualHost(component); // Attach the application to the virtual host attachToHost(result); // Adds the necessary server connectors addConnectors(component); } else { getLogger() .warning( "The WADL application has no base reference defined. Unable to guess the virtual host."); } return result; } /** * Attaches the application to the given host using the WADL base reference. * * @param host * The virtual host to attach to. */ public void attachToHost(VirtualHost host) { if (getBaseRef() != null) { final String path = getBaseRef().getPath(); if (path == null) { host.attach("", this); } else { host.attach(path, this); } } else { getLogger() .warning( "The WADL application has no base reference defined. Unable to guess the virtual host."); } } /** * Creates a finder for the given resource info. By default, it looks up for * an "id" attribute containing a fully qualified class name. * * @param router * The parent router. * @param resourceInfo * The WADL resource descriptor. * @return The created finder. * @throws ClassNotFoundException */ protected Finder createFinder(Router router, String uriPattern, ResourceInfo resourceInfo) throws ClassNotFoundException { Finder result = null; if (resourceInfo.getIdentifier() != null) { // The "id" attribute conveys the target class name Class targetClass = Engine.loadClass(resourceInfo.getIdentifier()); result = router.createFinder(targetClass); } else { getLogger() .fine( "Unable to find the 'id' attribute of the resource element with this path attribute \"" + uriPattern + "\""); } return result; } /** * Creates a new HTML representation for a given {@link ApplicationInfo} * instance describing an application. * * @param applicationInfo * The application description. * @return The created {@link WadlRepresentation}. */ protected Representation createHtmlRepresentation( ApplicationInfo applicationInfo) { return new WadlRepresentation(applicationInfo).getHtmlRepresentation(); } /** * Creates a new WADL representation for a given {@link ApplicationInfo} * instance describing an application. * * @param applicationInfo * The application description. * @return The created {@link WadlRepresentation}. */ protected Representation createWadlRepresentation( ApplicationInfo applicationInfo) { return new WadlRepresentation(applicationInfo); } /** * Returns a WADL description of the current application. By default, this * method discovers all the resources attached to this application. It can * be overridden to add documentation, list of representations, etc. * * @param request * The current request. * @param response * The current response. * @return An application description. */ protected ApplicationInfo getApplicationInfo(Request request, Response response) { ApplicationInfo applicationInfo = new ApplicationInfo(); applicationInfo.getResources().setBaseRef( request.getResourceRef().getBaseRef()); applicationInfo.getResources().setResources( getResourceInfos(applicationInfo, getFirstRouter(getInboundRoot()), request, response)); return applicationInfo; } /** * Returns the WADL base reference. * * @return The WADL base reference. */ public Reference getBaseRef() { return this.baseRef; } /** * Returns the first router available. * * @param current * The current Restlet to inspect. * @return The first router available. */ private Router getFirstRouter(Restlet current) { Router result = getRouter(); if (result == null) { if (current instanceof Router) { result = (Router) current; } else if (current instanceof Filter) { result = getFirstRouter(((Filter) current).getNext()); } } return result; } /** * Returns the preferred WADL variant according to the client preferences * specified in the request. * * @param clientInfo * The client preferences and info. * @return The preferred WADL variant. */ protected Variant getPreferredWadlVariant(ClientInfo clientInfo) { Variant result = null; // Compute the preferred variant. Get the default language // preference from the Application (if any). result = clientInfo.getPreferredVariant(getWadlVariants(), (getApplication() == null) ? null : getApplication() .getMetadataService()); return result; } /** * Completes the data available about a given Filter instance. * * @param applicationInfo * The parent application. * @param filter * The Filter instance to document. * @param path * The base path. * @param request * The current request. * @param response * The current response. * @return The resource description. */ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo, Filter filter, String path, Request request, Response response) { return getResourceInfo(applicationInfo, filter.getNext(), path, request, response); } /** * Completes the data available about a given Finder instance. * * @param applicationInfo * The parent application. * @param resourceInfo * The ResourceInfo object to complete. * @param finder * The Finder instance to document. * @param request * The current request. * @param response * The current response. */ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo, Finder finder, String path, Request request, Response response) { ResourceInfo result = null; Object resource = null; // Save the current application Application.setCurrent(this); if (finder instanceof Directory) { resource = finder; } else { // The handler instance targeted by this finder. resource = finder.findTarget(request, response); if (resource == null) { ServerResource sr = finder.find(request, response); if (sr != null) { sr.init(getContext(), request, response); sr.updateAllowedMethods(); resource = sr; } } } if (resource != null) { result = new ResourceInfo(); ResourceInfo.describe(applicationInfo, result, resource, path); } return result; } /** * Completes the data available about a given Restlet instance. * * @param applicationInfo * The parent application. * @param resourceInfo * The ResourceInfo object to complete. * @param restlet * The Restlet instance to document. * @param request * The current request. * @param response * The current response. */ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo, Restlet restlet, String path, Request request, Response response) { ResourceInfo result = null; if (restlet instanceof WadlDescribable) { result = ((WadlDescribable) restlet) .getResourceInfo(applicationInfo); result.setPath(path); } else if (restlet instanceof Finder) { result = getResourceInfo(applicationInfo, (Finder) restlet, path, request, response); } else if (restlet instanceof Router) { result = new ResourceInfo(); result.setPath(path); result.setChildResources(getResourceInfos(applicationInfo, (Router) restlet, request, response)); } else if (restlet instanceof Filter) { result = getResourceInfo(applicationInfo, (Filter) restlet, path, request, response); } return result; } /** * Returns the WADL data about the given Route instance. * * @param applicationInfo * The parent application. * @param route * The Route instance to document. * @param basePath * The base path. * @param request * The current request. * @param response * The current response. * @return The WADL data about the given Route instance. */ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo, Route route, String basePath, Request request, Response response) { String path = route.getTemplate().getPattern(); // WADL requires resource paths to be relative to parent path if (path.startsWith("/") && basePath.endsWith("/")) { path = path.substring(1); } ResourceInfo result = getResourceInfo(applicationInfo, route.getNext(), path, request, response); return result; } /** * Completes the list of ResourceInfo instances for the given Router * instance. * * @param applicationInfo * The parent application. * @param router * The router to document. * @param request * The current request. * @param response * The current response. * @return The list of ResourceInfo instances to complete. */ private List getResourceInfos( ApplicationInfo applicationInfo, Router router, Request request, Response response) { List result = new ArrayList(); for (final Route route : router.getRoutes()) { ResourceInfo resourceInfo = getResourceInfo(applicationInfo, route, "/", request, response); if (resourceInfo != null) { result.add(resourceInfo); } } if (router.getDefaultRoute() != null) { ResourceInfo resourceInfo = getResourceInfo(applicationInfo, router .getDefaultRoute(), "/", request, response); if (resourceInfo != null) { result.add(resourceInfo); } } return result; } /** * Returns the router where the {@link ServerResource} classes created from * the WADL description document are attached. * * @return The root router. */ public Router getRouter() { return this.router; } /** * Returns the title of this documented application. * * @return The title of this documented application. * @deprecated Use {@link #getName()} instead */ @Deprecated public String getTitle() { return title; } /** * Returns the virtual host matching the WADL application's base reference. * Creates a new one and attaches it to the component if necessary. * * @param component * The parent component. * @return The related virtual host. */ private VirtualHost getVirtualHost(Component component) { // Create the virtual host if necessary final String hostDomain = this.baseRef.getHostDomain(); final String hostPort = Integer.toString(this.baseRef.getHostPort()); final String hostScheme = this.baseRef.getScheme(); VirtualHost host = null; for (final VirtualHost vh : component.getHosts()) { if (vh.getHostDomain().equals(hostDomain) && vh.getHostPort().equals(hostPort) && vh.getHostScheme().equals(hostScheme)) { host = vh; } } if (host == null) { // A new virtual host needs to be created host = new VirtualHost(component.getContext().createChildContext()); host.setHostDomain(hostDomain); host.setHostPort(hostPort); host.setHostScheme(hostScheme); component.getHosts().add(host); } return host; } /** * Returns the available WADL variants. * * @return The available WADL variants. */ protected List getWadlVariants() { final List result = new ArrayList(); result.add(new Variant(MediaType.APPLICATION_WADL)); result.add(new Variant(MediaType.TEXT_HTML)); return result; } /** * Handles the requests normally in all cases then handles the special case * of the OPTIONS requests that exactly target the application. In this * case, the application is automatically introspected and described as a * WADL representation based on the result of the * {@link #getApplicationInfo(Request, Response)} method.
    * The automatic introspection happens only if the request hasn't already * been successfully handled. That is to say, it lets users provide their * own handling of OPTIONS requests. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { // Preserve the resource reference. Reference rr = request.getResourceRef().clone(); // Do the regular handling super.handle(request, response); // Restore the resource reference request.setResourceRef(rr); // Handle OPTIONS requests. String rp = rr.getRemainingPart(false, false); if (isAutoDescribing() && Method.OPTIONS.equals(request.getMethod()) && (response.getStatus().isClientError() || !response .isEntityAvailable()) && ("/".equals(rp) || "".equals(rp))) { // Make sure that the base of the "resources" element ends with a // "/". if (!rr.getBaseRef().getIdentifier().endsWith("/")) { rr.setBaseRef(rr.getBaseRef() + "/"); } // Returns a WADL representation of the application. response.setEntity(wadlRepresent(request, response)); if (response.isEntityAvailable()) { response.setStatus(Status.SUCCESS_OK); } } } /** * Indicates if the application should be automatically described via WADL * when an OPTIONS request handles a "*" target URI. * * @return True if the application should be automatically described via * WADL. */ public boolean isAutoDescribing() { return autoDescribing; } /** * Indicates if the application should be automatically described via WADL * when an OPTIONS request handles a "*" target URI. * * @param autoDescribed * True if the application should be automatically described via * WADL. */ public void setAutoDescribing(boolean autoDescribed) { this.autoDescribing = autoDescribed; } /** * Sets the WADL base reference. * * @param baseRef * The WADL base reference. */ public void setBaseRef(Reference baseRef) { this.baseRef = baseRef; } /** * Sets the title of this documented application. * * @param title * The title of this documented application. * @deprecated Use {@link #setName(String)} instead */ @Deprecated public void setTitle(String title) { this.title = title; } /** * Represents the resource as a WADL description. * * @param request * The current request. * @param response * The current response. * @return The WADL description. */ protected Representation wadlRepresent(Request request, Response response) { return wadlRepresent(getPreferredWadlVariant(request.getClientInfo()), request, response); } /** * Represents the resource as a WADL description for the given variant. * * @param variant * The WADL variant. * @param request * The current request. * @param response * The current response. * @return The WADL description. */ protected Representation wadlRepresent(Variant variant, Request request, Response response) { Representation result = null; if (variant != null) { ApplicationInfo applicationInfo = getApplicationInfo(request, response); DocumentationInfo doc = null; if ((getTitle() != null) && !"".equals(getTitle())) { if (applicationInfo.getDocumentations().isEmpty()) { doc = new DocumentationInfo(); applicationInfo.getDocumentations().add(doc); } else { doc = applicationInfo.getDocumentations().get(0); } doc.setTitle(getTitle()); } else if ((getName() != null) && !"".equals(getName())) { if (applicationInfo.getDocumentations().isEmpty()) { doc = new DocumentationInfo(); applicationInfo.getDocumentations().add(doc); } else { doc = applicationInfo.getDocumentations().get(0); } doc.setTitle(getName()); } if ((doc != null) && (getDescription() != null) && !"".equals(getDescription())) { doc.setTextContent(getDescription()); } if (MediaType.APPLICATION_WADL.equals(variant.getMediaType())) { result = createWadlRepresentation(applicationInfo); } else if (MediaType.TEXT_HTML.equals(variant.getMediaType())) { result = createHtmlRepresentation(applicationInfo); } } return result; } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/ParameterInfo.java0000664000175000017500000003144711757206352030140 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Describes a parameterized aspect of a parent {@link ResourceInfo}, * {@link RequestInfo}, {@link ResponseInfo}, {@link RepresentationInfo} or * {@link FaultInfo} element. * * @author Jerome Louvel */ public class ParameterInfo extends DocumentedInfo { /** Default value of this parameter. */ private String defaultValue; /** Provides a fixed value for the parameter. */ private String fixed; /** Identifier of this parameter element. */ private String identifier; /** Link element. */ private LinkInfo link; /** Name of this element. */ private String name; /** List of option elements for that element. */ private List options; /** * Path to the value of this parameter (within a parent representation). */ private String path; /** * Indicates whether the parameter is single valued or may have multiple * values. */ private boolean repeating; /** * Indicates whether the parameter is required. */ private boolean required; /** Parameter style. */ private ParameterStyle style; /** Parameter type. */ private String type; /** * Constructor. */ public ParameterInfo() { super(); } /** * Constructor with a single documentation element. * * @param name * The required name of the parameter. * @param style * The required style of the parameter. * @param documentation * A single documentation element. */ public ParameterInfo(String name, ParameterStyle style, DocumentationInfo documentation) { super(documentation); this.name = name; this.style = style; } /** * Constructor with a list of documentation elements. * * @param name * The required name of the parameter. * @param style * The required style of the parameter. * @param documentations * The list of documentation elements. */ public ParameterInfo(String name, ParameterStyle style, List documentations) { super(documentations); this.name = name; this.style = style; } /** * Constructor with a single documentation element. * * @param name * The required name of the parameter. * @param style * The required style of the parameter. * @param documentation * A single documentation element. */ public ParameterInfo(String name, ParameterStyle style, String documentation) { super(documentation); this.name = name; this.style = style; } /** * Constructor. * * @param name * The name of the parameter. * @param required * True if thes parameter is required. * @param type * The type of the parameter. * @param style * The style of the parameter. * @param documentation * A single documentation element. */ public ParameterInfo(String name, boolean required, String type, ParameterStyle style, String documentation) { super(documentation); this.name = name; this.required = required; this.style = style; this.type = type; } /** * Returns the default value of this parameter. * * @return The default value of this parameter. */ public String getDefaultValue() { return this.defaultValue; } /** * Returns the fixed value for the parameter. * * @return The fixed value for the parameter. */ public String getFixed() { return this.fixed; } /** * Returns the identifier of this parameter element. * * @return The identifier of this parameter element. */ public String getIdentifier() { return this.identifier; } /** * Returns the link element. * * @return The link element. */ public LinkInfo getLink() { return this.link; } /** * Returns the name of this element. * * @return The name of this element. */ public String getName() { return this.name; } /** * Returns the list of option elements for that element. * * @return The list of option elements for that element. */ public List getOptions() { // Lazy initialization with double-check. List o = this.options; if (o == null) { synchronized (this) { o = this.options; if (o == null) { this.options = o = new ArrayList(); } } } return o; } /** * Returns the path to the value of this parameter (within a parent * representation). * * @return The path to the value of this parameter (within a parent * representation). */ public String getPath() { return this.path; } /** * Returns the parameter style. * * @return The parameter style. */ public ParameterStyle getStyle() { return this.style; } /** * Returns the parameter type. * * @return The parameter type. */ public String getType() { return this.type; } /** * Returns true if the parameter is single valued or may have multiple * values, false otherwise. * * @return True if the parameter is single valued or may have multiple * values, false otherwise. */ public boolean isRepeating() { return this.repeating; } /** * Indicates whether the parameter is required. * * @return True if the parameter is required, false otherwise. */ public boolean isRequired() { return this.required; } /** * Sets the default value of this parameter. * * @param defaultValue * The default value of this parameter. */ public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } /** * Sets the fixed value for the parameter. * * @param fixed * The fixed value for the parameter. */ public void setFixed(String fixed) { this.fixed = fixed; } /** * Sets the identifier of this parameter element. * * @param identifier * The identifier of this parameter element. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Sets the link element. * * @param link * The link element. */ public void setLink(LinkInfo link) { this.link = link; } /** * Sets the name of this element. * * @param name * The name of this element. */ public void setName(String name) { this.name = name; } /** * Sets the list of option elements for that element. * * @param options * The list of option elements for that element. */ public void setOptions(List options) { this.options = options; } /** * Sets the path to the value of this parameter (within a parent * representation). * * @param path * The path to the value of this parameter (within a parent * representation). */ public void setPath(String path) { this.path = path; } /** * Indicates whether the parameter is single valued or may have multiple * values. * * @param repeating * True if the parameter is single valued or may have multiple * values, false otherwise. */ public void setRepeating(boolean repeating) { this.repeating = repeating; } /** * Indicates whether the parameter is required. * * @param required * True if the parameter is required, false otherwise. */ public void setRequired(boolean required) { this.required = required; } /** * Sets the parameter style. * * @param style * The parameter style. */ public void setStyle(ParameterStyle style) { this.style = style; } /** * Sets the parameter type. * * @param type * The parameter type. */ public void setType(String type) { this.type = type; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); if (getLink() != null) { getLink().updateNamespaces(namespaces); } for (final OptionInfo optionInfo : getOptions()) { optionInfo.updateNamespaces(namespaces); } } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getDefaultValue() != null) && !getDefaultValue().equals("")) { attributes.addAttribute("", "default", null, "xs:string", getDefaultValue()); } if ((getFixed() != null) && !getFixed().equals("")) { attributes.addAttribute("", "fixed", null, "xs:string", getFixed()); } if ((getIdentifier() != null) && !getIdentifier().equals("")) { attributes.addAttribute("", "id", null, "xs:ID", getIdentifier()); } if ((getPath() != null) && !getPath().equals("")) { attributes.addAttribute("", "path", null, "xs:string", getPath()); } if (getStyle() != null) { attributes.addAttribute("", "style", null, "xs:string", getStyle() .toString()); } if ((getName() != null) && !getName().equals("")) { attributes.addAttribute("", "name", null, "xs:NMTOKEN", getName()); } if ((getType() != null) && !getType().equals("")) { attributes.addAttribute("", "type", null, "xs:QName", getType()); } if (isRepeating()) { attributes .addAttribute("", "repeating", null, "xs:boolean", "true"); } if (isRequired()) { attributes.addAttribute("", "required", null, "xs:boolean", "true"); } if ((getLink() == null) && getDocumentations().isEmpty() && getOptions().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "param", null, attributes); } else { writer.startElement(APP_NAMESPACE, "param", null, attributes); if (getLink() != null) { getLink().writeElement(writer); } for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (final OptionInfo optionInfo : getOptions()) { optionInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "param"); } } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlComponent.java0000664000175000017500000001300611757206352030145 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.representation.Representation; /** * Component that can configure itself given a WADL document. First, it creates * the server connectors and the virtual hosts if needed, trying to reuse * existing ones if available. Then it creates a {@link WadlApplication} using * this {@link WadlApplication#WadlApplication(Representation)} constructor.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class WadlComponent extends Component { /** * Main method capable of configuring and starting a whole Restlet Component * based on a list of local WADL documents URIs, for example * "file:///C:/YahooSearch.wadl".
    *
    * The necessary client connectors are automatically created. * * @param args * List of local WADL document URIs. * @throws Exception */ public static void main(String[] args) throws Exception { // Create a new WADL-aware component final WadlComponent component = new WadlComponent(); // For each WADL document URI attach a matching Application for (final String arg : args) { component.attach(arg); } // Start the component component.start(); } /** * Default constructor. */ public WadlComponent() { } /** * Constructor loading a WADL description document at a given URI.
    *
    * The necessary client connectors are automatically created. * * @param wadlRef * The URI reference to the WADL description document. */ public WadlComponent(Reference wadlRef) { attach(wadlRef); } /** * Constructor based on a given WADL description document. * * @param wadl * The WADL description document. */ public WadlComponent(Representation wadl) { attach(wadl); } /** * Constructor loading a WADL description document at a given URI.
    *
    * The necessary client connectors are automatically created. * * @param wadlUri * The URI to the WADL description document. */ public WadlComponent(String wadlUri) { attach(wadlUri); } /** * Attaches an application created from a WADL description document * available at a given URI reference. * * @param wadlRef * The URI reference to the WADL description document. * @return The created WADL application. */ public WadlApplication attach(Reference wadlRef) { WadlApplication result = null; // Adds some common client connectors to load the WADL documents if (!getClients().contains(wadlRef.getSchemeProtocol())) { getClients().add(wadlRef.getSchemeProtocol()); } // Get the WADL document final Response response = getContext().getClientDispatcher().handle( new Request(Method.GET, wadlRef)); if (response.getStatus().isSuccess() && response.isEntityAvailable()) { result = attach(response.getEntity()); } return result; } /** * Attaches an application created from a WADL description document to the * component. * * @param wadl * The WADL description document. * @return The created WADL application. */ public WadlApplication attach(Representation wadl) { final WadlApplication result = new WadlApplication(getContext() .createChildContext(), wadl); result.attachToComponent(this); return result; } /** * Attaches an application created from a WADL description document * available at a given URI. * * @param wadlUri * The URI to the WADL description document. * @return The created WADL application. */ public WadlApplication attach(String wadlUri) { return attach(new Reference(wadlUri)); } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlServerResource.java0000664000175000017500000004556011757206352031173 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import java.util.ArrayList; import java.util.List; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import org.restlet.util.Series; /** * Resource that is able to automatically describe itself with WADL. This * description can be customized by overriding the {@link #describe()} and * {@link #describeMethod(Method, MethodInfo)} methods.
    *
    * When used to describe a class of resources in the context of a parent * application, a special instance will be created using the default constructor * (with no request, response associated). In this case, the resource should do * its best to return the generic information when the WADL description methods * are invoked, like {@link #describe()} and delegate methods. * * @author Jerome Louvel */ public class WadlServerResource extends ServerResource { /** * Indicates if the resource should be automatically described via WADL when * an OPTIONS request is handled. */ private volatile boolean autoDescribing; /** * The description of this documented resource. Is seen as the text content * of the "doc" tag of the "resource" element in a WADL document. */ private volatile String description; /** * The name of this documented resource. Is seen as the title of the "doc" * tag of the "resource" element in a WADL document. */ private volatile String name; /** * Constructor. */ public WadlServerResource() { this.autoDescribing = true; } /** * Indicates if the given method exposes its WADL description. By default, * HEAD and OPTIONS are not exposed. This method is called by * {@link #describe(String, ResourceInfo)}. * * @param method * The method * @return True if the method exposes its description, false otherwise. */ public boolean canDescribe(Method method) { return !(Method.HEAD.equals(method) || Method.OPTIONS.equals(method)); } /** * Creates a new HTML representation for a given {@link ApplicationInfo} * instance describing an application. * * @param applicationInfo * The application description. * @return The created {@link WadlRepresentation}. */ protected Representation createHtmlRepresentation( ApplicationInfo applicationInfo) { return new WadlRepresentation(applicationInfo).getHtmlRepresentation(); } /** * Creates a new WADL representation for a given {@link ApplicationInfo} * instance describing an application. * * @param applicationInfo * The application description. * @return The created {@link WadlRepresentation}. */ protected Representation createWadlRepresentation( ApplicationInfo applicationInfo) { return new WadlRepresentation(applicationInfo); } /** * Describes the resource as a standalone WADL document. * * @return The WADL description. */ protected Representation describe() { return describe(getPreferredWadlVariant()); } /** * Updates the description of the parent application. This is typically used * to add documentation on global representations used by several methods or * resources. Does nothing by default. * * @param applicationInfo * The parent application. */ protected void describe(ApplicationInfo applicationInfo) { } /** * Describes a representation class and variant couple as WADL information. * The variant contains the target media type that can be converted to by * one of the available Restlet converters. * * @param methodInfo * The parent method description. * @param representationClass * The representation bean class. * @param variant * The target variant. * @return The WADL representation information. */ protected RepresentationInfo describe(MethodInfo methodInfo, Class representationClass, Variant variant) { return new RepresentationInfo(variant); } /** * Describes a representation class and variant couple as WADL information * for the given method and request. The variant contains the target media * type that can be converted to by one of the available Restlet converters.
    *
    * By default, it calls {@link #describe(MethodInfo, Class, Variant)}. * * @param methodInfo * The parent method description. * @param requestInfo * The parent request description. * @param representationClass * The representation bean class. * @param variant * The target variant. * @return The WADL representation information. */ protected RepresentationInfo describe(MethodInfo methodInfo, RequestInfo requestInfo, Class representationClass, Variant variant) { return describe(methodInfo, representationClass, variant); } /** * Describes a representation class and variant couple as WADL information * for the given method and response. The variant contains the target media * type that can be converted to by one of the available Restlet converters.
    *
    * By default, it calls {@link #describe(MethodInfo, Class, Variant)}. * * @param methodInfo * The parent method description. * @param responseInfo * The parent response description. * @param representationClass * The representation bean class. * @param variant * The target variant. * @return The WADL representation information. */ protected RepresentationInfo describe(MethodInfo methodInfo, ResponseInfo responseInfo, Class representationClass, Variant variant) { return describe(methodInfo, representationClass, variant); } /** * Returns a WADL description of the current resource, leveraging the * {@link #getResourcePath()} method. * * @param info * WADL description of the current resource to update. */ public void describe(ResourceInfo info) { describe(getResourcePath(), info); } /** * Returns a WADL description of the current resource. * * @param path * Path of the current resource. * @param info * WADL description of the current resource to update. */ public void describe(String path, ResourceInfo info) { ResourceInfo.describe(null, info, this, path); } /** * Describes the resource as a WADL document for the given variant. * * @param variant * The WADL variant. * @return The WADL description. */ protected Representation describe(Variant variant) { Representation result = null; if (variant != null) { ResourceInfo resource = new ResourceInfo(); describe(resource); ApplicationInfo application = resource.createApplication(); describe(application); if (MediaType.APPLICATION_WADL.equals(variant.getMediaType())) { result = createWadlRepresentation(application); } else if (MediaType.TEXT_HTML.equals(variant.getMediaType())) { result = createHtmlRepresentation(application); } } return result; } /** * Describes the DELETE method. * * @param info * The method description to update. */ protected void describeDelete(MethodInfo info) { MethodInfo.describeAnnotations(info, this); } /** * Describes the GET method.
    * By default, it describes the response with the available variants based * on the {@link #getVariants()} method. Thus in the majority of cases, the * method of the super class must be called when overridden. * * @param info * The method description to update. */ protected void describeGet(MethodInfo info) { MethodInfo.describeAnnotations(info, this); } /** * Returns a WADL description of the current method. * * @return A WADL description of the current method. */ protected MethodInfo describeMethod() { MethodInfo result = new MethodInfo(); describeMethod(getMethod(), result); return result; } /** * Returns a WADL description of the given method. * * @param method * The method to describe. * @param info * The method description to update. */ protected void describeMethod(Method method, MethodInfo info) { info.setName(method); if (Method.GET.equals(method)) { describeGet(info); } else if (Method.POST.equals(method)) { describePost(info); } else if (Method.PUT.equals(method)) { describePut(info); } else if (Method.DELETE.equals(method)) { describeDelete(info); } else if (Method.OPTIONS.equals(method)) { describeOptions(info); } } /** * Describes the OPTIONS method.
    * By default it describes the response with the available variants based on * the {@link #getWadlVariants()} method. * * @param info * The method description to update. */ protected void describeOptions(MethodInfo info) { // Describe each variant for (Variant variant : getWadlVariants()) { RepresentationInfo result = new RepresentationInfo(variant); info.getResponse().getRepresentations().add(result); } } /** * Returns the description of the parameters of this resource. Returns null * by default. * * @return The description of the parameters. */ protected List describeParameters() { return null; } /** * Describes the POST method. * * @param info * The method description to update. */ protected void describePost(MethodInfo info) { MethodInfo.describeAnnotations(info, this); } /** * Describes the PUT method. * * @param info * The method description to update. */ protected void describePut(MethodInfo info) { MethodInfo.describeAnnotations(info, this); } @Override protected void doInit() throws ResourceException { super.doInit(); this.autoDescribing = true; } /** * Returns the description of this documented resource. Is seen as the text * content of the "doc" tag of the "resource" element in a WADL document. * * @return The description of this documented resource. */ public String getDescription() { return description; } /** * Returns the set of headers as a collection of {@link Parameter} objects. * * @return The set of headers as a collection of {@link Parameter} objects. */ private Form getHeaders() { return (Form) getRequestAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); } /** * Returns the name of this documented resource. Is seen as the title of the * "doc" tag of the "resource" element in a WADL document. * * @return The name of this documented resource. */ public String getName() { return name; } /** * Returns the first parameter found in the current context (entity, query, * headers, etc) with the given name. * * @param name * The parameter name. * @return The first parameter found with the given name. */ protected Parameter getParameter(String name) { Parameter result = null; Series set = getParameters(name); if (set != null) { result = set.getFirst(name); } return result; } /** * Returns a collection of parameters objects contained in the current * context (entity, query, headers, etc) given a ParameterInfo instance. * * @param parameterInfo * The ParameterInfo instance. * @return A collection of parameters objects */ private Series getParameters(ParameterInfo parameterInfo) { Series result = null; if (parameterInfo.getFixed() != null) { result = new Form(); result.add(parameterInfo.getName(), parameterInfo.getFixed()); } else if (ParameterStyle.HEADER.equals(parameterInfo.getStyle())) { result = getHeaders().subList(parameterInfo.getName()); } else if (ParameterStyle.TEMPLATE.equals(parameterInfo.getStyle())) { Object parameter = getRequest().getAttributes().get( parameterInfo.getName()); if (parameter != null) { result = new Form(); result.add(parameterInfo.getName(), Reference .decode((String) parameter)); } } else if (ParameterStyle.MATRIX.equals(parameterInfo.getStyle())) { result = getMatrix().subList(parameterInfo.getName()); } else if (ParameterStyle.QUERY.equals(parameterInfo.getStyle())) { result = getQuery().subList(parameterInfo.getName()); } else if (ParameterStyle.PLAIN.equals(parameterInfo.getStyle())) { // TODO not yet implemented. } if (result == null && parameterInfo.getDefaultValue() != null) { result = new Form(); result .add(parameterInfo.getName(), parameterInfo .getDefaultValue()); } return result; } /** * Returns a collection of parameters found in the current context (entity, * query, headers, etc) given a parameter name. It returns null if the * parameter name is unknown. * * @param name * The name of the parameter. * @return A collection of parameters. */ protected Series getParameters(String name) { Series result = null; if (describeParameters() != null) { for (ParameterInfo parameter : describeParameters()) { if (name.equals(parameter.getName())) { result = getParameters(parameter); } } } return result; } /** * Returns the preferred WADL variant according to the client preferences * specified in the request. * * @return The preferred WADL variant. */ protected Variant getPreferredWadlVariant() { Variant result = null; // Compute the preferred variant result = getRequest().getClientInfo().getPreferredVariant( getWadlVariants(), (getApplication() == null) ? null : getApplication() .getMetadataService()); return result; } /** * Returns the resource's relative path. * * @return The resource's relative path. */ protected String getResourcePath() { Reference ref = new Reference(getRequest().getRootRef(), getRequest() .getResourceRef()); return ref.getRemainingPart(); } /** * Returns the application resources base URI. * * @return The application resources base URI. */ protected Reference getResourcesBase() { return getRequest().getRootRef(); } /** * Returns the available WADL variants. * * @return The available WADL variants. */ protected List getWadlVariants() { List result = new ArrayList(); result.add(new Variant(MediaType.APPLICATION_WADL)); result.add(new Variant(MediaType.TEXT_HTML)); return result; } /** * Indicates if the resource should be automatically described via WADL when * an OPTIONS request is handled. * * @return True if the resource should be automatically described via WADL. */ public boolean isAutoDescribing() { return this.autoDescribing; } @Override public Representation options() { if (isAutoDescribing()) { return describe(); } return null; } /** * Indicates if the resource should be automatically described via WADL when * an OPTIONS request is handled. * * @param autoDescribed * True if the resource should be automatically described via * WADL. */ public void setAutoDescribing(boolean autoDescribed) { this.autoDescribing = autoDescribed; } /** * Sets the description of this documented resource. Is seen as the text * content of the "doc" tag of the "resource" element in a WADL document. * * @param description * The description of this documented resource. */ public void setDescription(String description) { this.description = description; } /** * Sets the name of this documented resource. Is seen as the title of the * "doc" tag of the "resource" element in a WADL document. * * @param name * The name of this documented resource. */ public void setName(String name) { this.name = name; } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/WadlDescribable.java0000664000175000017500000000401311757206352030400 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import org.restlet.resource.Directory; import org.restlet.resource.ServerResource; /** * Interface that any Restlet can implement in order to provide their own WADL * documentation. This is especially useful for subclasses of {@link Directory} * or other resource finders when the WADL introspection can't reach * {@link ServerResource} or better {@link WadlServerResource} instances. * * @author Thierry Boileau */ public interface WadlDescribable { /** * Returns a full documented {@link ResourceInfo} instance. * * @param applicationInfo * The parent WADL application descriptor. * * @return A full documented {@link ResourceInfo} instance. */ public ResourceInfo getResourceInfo(ApplicationInfo applicationInfo); } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/ParameterStyle.java0000664000175000017500000000353611757206352030343 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; /** * Enumerates the supported styles of parameters. * * @author Jerome Louvel */ public enum ParameterStyle { HEADER, MATRIX, PLAIN, QUERY, TEMPLATE; @Override public String toString() { String result = null; if (equals(HEADER)) { result = "header"; } else if (equals(MATRIX)) { result = "matrix"; } else if (equals(PLAIN)) { result = "plain"; } else if (equals(QUERY)) { result = "query"; } else if (equals(TEMPLATE)) { result = "template"; } return result; } } restlet-2.0.14/org.restlet.ext.wadl/src/org/restlet/ext/wadl/IncludeInfo.java0000664000175000017500000001006511757206352027574 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.wadl; import static org.restlet.ext.wadl.WadlRepresentation.APP_NAMESPACE; import java.util.List; import java.util.Map; import org.restlet.data.Reference; import org.restlet.ext.xml.XmlWriter; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Allows inclusion of grammars by reference. * * @author Jerome Louvel */ public class IncludeInfo extends DocumentedInfo { /** URI for the referenced definitions. */ private Reference targetRef; /** * Constructor. */ public IncludeInfo() { super(); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public IncludeInfo(DocumentationInfo documentation) { super(documentation); } /** * Constructor with a list of documentation elements. * * @param documentations * The list of documentation elements. */ public IncludeInfo(List documentations) { super(documentations); } /** * Constructor with a single documentation element. * * @param documentation * A single documentation element. */ public IncludeInfo(String documentation) { super(documentation); } /** * Returns the URI of the referenced definition. * * @return The URI of the referenced definition. */ public Reference getTargetRef() { return this.targetRef; } /** * Sets the URI of the referenced definition. * * @param href * The URI of the referenced definition. */ public void setTargetRef(Reference href) { this.targetRef = href; } @Override public void updateNamespaces(Map namespaces) { namespaces.putAll(resolveNamespaces()); } /** * Writes the current object as an XML element using the given SAX writer. * * @param writer * The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getTargetRef() != null) && (getTargetRef().toString() != null)) { attributes.addAttribute("", "href", null, "xs:anyURI", getTargetRef().toString()); } if (getDocumentations().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "include", null, attributes); } else { writer.startElement(APP_NAMESPACE, "include", null, attributes); for (final DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "include"); } } } restlet-2.0.14/org.restlet.ext.json/0000775000175000017500000000000012001473207017747 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.json/pom.xml0000600000175000017500000000162312001473207021254 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.json Restlet Extension - JSON Support for JSON representations. org.restlet.jse org.restlet.lib.org.json ${lib-json-version} org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.json/src/0000775000175000017500000000000012001473207020536 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.json/src/META-INF/0000775000175000017500000000000011757206452021713 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.json/src/META-INF/services/0000775000175000017500000000000011757206352023535 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.json/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.json/src/META-INF/services/org.restlet.engine.converter.ConverterHelp0000664000175000017500000000004211757206352033755 0ustar jamespagejamespageorg.restlet.ext.json.JsonConverterrestlet-2.0.14/org.restlet.ext.json/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023344 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.json/src/org/0000775000175000017500000000000011757206352021341 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.json/src/org/restlet/0000775000175000017500000000000011757206352023023 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.json/src/org/restlet/ext/0000775000175000017500000000000011757206352023623 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.json/src/org/restlet/ext/json/0000775000175000017500000000000011757206352024574 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.json/src/org/restlet/ext/json/package.html0000664000175000017500000000107711757206352027062 0ustar jamespagejamespage Support for JSON representations. JSON stands for JavaScript Object Notation and is a lightweight data-interchange format. This extension is based on the JSON library from Java providing by the official JSON.org Web site. This library is useful in simple cases, but not tuned for performance or extensive serialization support of POJOs. If you need such features, you can also consider the XStream extension which supports both XML and JSON serialization.

    @since Restlet 1.0 @see JSON project restlet-2.0.14/org.restlet.ext.json/src/org/restlet/ext/json/JsonConverter.java0000664000175000017500000001540211757206352030242 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.json; import java.io.IOException; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between the JSON API (more precisely {@link JSONArray}, * {@link JSONObject} and {@link JSONTokener} instances) and Representation * classes. * * @author Jerome Louvel */ public class JsonConverter extends ConverterHelper { private static final VariantInfo VARIANT_JSON = new VariantInfo( MediaType.APPLICATION_JSON); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_JSON.isCompatible(source)) { result = addObjectClass(result, JSONArray.class); result = addObjectClass(result, JSONObject.class); result = addObjectClass(result, JSONTokener.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (JSONArray.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_JSON); } else if (JSONObject.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_JSON); } else if (JSONTokener.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_JSON); } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if ((source instanceof JSONArray) || (source instanceof JSONObject) || (source instanceof JSONTokener)) { if (target == null) { result = 0.5F; } else if (MediaType.APPLICATION_JSON.isCompatible(target .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (target != null) { if (JsonRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (JSONArray.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_JSON.isCompatible(source .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } else if (JSONObject.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_JSON.isCompatible(source .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } else if (JSONTokener.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_JSON.isCompatible(source .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } } return result; } @SuppressWarnings("unchecked") @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (JSONArray.class.isAssignableFrom(target)) { try { result = new JSONArray(source.getText()); } catch (JSONException e) { IOException ioe = new IOException( "Unable to convert to JSON array"); ioe.initCause(e); } } else if (JSONObject.class.isAssignableFrom(target)) { try { result = new JSONObject(source.getText()); } catch (JSONException e) { IOException ioe = new IOException( "Unable to convert to JSON object"); ioe.initCause(e); } } else if (JSONTokener.class.isAssignableFrom(target)) { result = new JSONTokener(source.getText()); } else if (JsonRepresentation.class.isAssignableFrom(target)) { result = new JsonRepresentation(source); } return (T) result; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; if (source instanceof JSONArray) { result = new JsonRepresentation((JSONArray) source); } else if (source instanceof JSONObject) { result = new JsonRepresentation((JSONObject) source); } else if (source instanceof JSONTokener) { result = new JsonRepresentation((JSONTokener) source); } return result; } @Override public void updatePreferences(List> preferences, Class entity) { if (JSONArray.class.isAssignableFrom(entity) || JSONObject.class.isAssignableFrom(entity) || JSONTokener.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_JSON, 1.0F); } } } restlet-2.0.14/org.restlet.ext.json/src/org/restlet/ext/json/JsonRepresentation.java0000664000175000017500000002667411757206352031312 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.json; import java.io.IOException; import java.io.Writer; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONStringer; import org.json.JSONTokener; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.WriterRepresentation; /** * Representation based on a JSON document. JSON stands for JavaScript Object * Notation and is a lightweight data-interchange format. * * @author Jerome Louvel * @see JSON home */ public class JsonRepresentation extends WriterRepresentation { /** Indicates if JSON objects and arrays should be indented. */ private boolean indenting; /** Number of spaces to use for indentation. */ private int indentingSize; /** The wrapped JSON value. */ private Object jsonValue; /** The wrapped JSON representation. */ private Representation jsonRepresentation; /** * Constructor from a JSON array. * * @param jsonArray * The JSON array. */ public JsonRepresentation(JSONArray jsonArray) { super(MediaType.APPLICATION_JSON); init(jsonArray); } /** * Constructor from a JSON object. * * @param jsonObject * The JSON object. */ public JsonRepresentation(JSONObject jsonObject) { super(MediaType.APPLICATION_JSON); init(jsonObject); } /** * Constructor from a JSON stringer. * * @param jsonStringer * The JSON stringer. */ public JsonRepresentation(JSONStringer jsonStringer) { super(MediaType.APPLICATION_JSON); init(jsonStringer); } /** * Constructor from a JSON tokener. * * @param jsonTokener * The JSON tokener. */ public JsonRepresentation(JSONTokener jsonTokener) { super(MediaType.APPLICATION_JSON); init(jsonTokener); } /** * Constructor from a map object. * * @param map * The map to convert to JSON. * @see org.json.JSONObject#JSONObject(Map) */ public JsonRepresentation(Map map) { this(new JSONObject(map)); } /** * Constructor from a bean using reflection to generate JSON names. * * @param bean * The bean to convert to JSON. * @see org.json.JSONObject#JSONObject(Object) */ public JsonRepresentation(Object bean) { this(new JSONObject(bean)); } /** * Constructor. * * @param jsonRepresentation * A source JSON representation to parse. */ public JsonRepresentation(Representation jsonRepresentation) throws IOException { super((jsonRepresentation == null) ? null : jsonRepresentation .getMediaType()); this.jsonRepresentation = jsonRepresentation; } /** * Constructor from a JSON string. * * @param jsonString * The JSON string. */ public JsonRepresentation(String jsonString) { super(MediaType.APPLICATION_JSON); setCharacterSet(CharacterSet.UTF_8); this.jsonRepresentation = new StringRepresentation(jsonString); } /** * Returns the number of spaces to use for indentation. * * @return The number of spaces to use for indentation. */ public int getIndentingSize() { return indentingSize; } /** * Returns the number of spaces to use for indentation. * * @return The number of spaces to use for indentation. * @deprecated Use {@link #getIndentingSize()} instead. */ @Deprecated public int getIndentSize() { return getIndentingSize(); } /** * Gets the wrapped JSON array or converts the wrapped representation if * needed. * * @return The converted JSON array. * @throws JSONException */ public JSONArray getJsonArray() throws JSONException { if (this.jsonValue != null) { return (JSONArray) this.jsonValue; } return toJsonArray(); } /** * Gets the wrapped JSON object or converts the wrapped representation if * needed. * * @return The converted JSON object. * @throws JSONException */ public JSONObject getJsonObject() throws JSONException { if (this.jsonValue != null) { return (JSONObject) this.jsonValue; } return toJsonObject(); } /** * Returns the JSON text for the wrapped JSON object or representation. * * @return The JSON text. * @throws JSONException */ private String getJsonText() throws JSONException { String result = null; if (this.jsonValue != null) { if (this.jsonValue instanceof JSONArray) { JSONArray jsonArray = (JSONArray) this.jsonValue; if (isIndenting()) { result = jsonArray.toString(getIndentingSize()); } else { result = jsonArray.toString(); } } else if (this.jsonValue instanceof JSONObject) { JSONObject jsonObject = (JSONObject) this.jsonValue; if (isIndenting()) { result = jsonObject.toString(getIndentingSize()); } else { result = jsonObject.toString(); } } else if (this.jsonValue instanceof JSONStringer) { JSONStringer jsonStringer = (JSONStringer) this.jsonValue; result = jsonStringer.toString(); } else if (this.jsonValue instanceof JSONTokener) { JSONTokener jsonTokener = (JSONTokener) this.jsonValue; result = jsonTokener.toString(); } } else if (this.jsonRepresentation != null) { try { result = this.jsonRepresentation.getText(); } catch (IOException e) { throw new JSONException(e); } } return result; } /** * Gets the wrapped JSON tokener or converts the wrapped representation if * needed. * * @return The converted JSON tokener. * @throws JSONException */ public JSONTokener getJsonTokener() throws JSONException { if (this.jsonValue != null) { return (JSONTokener) this.jsonValue; } return toJsonTokener(); } @Override public long getSize() { if (this.jsonRepresentation != null) { return this.jsonRepresentation.getSize(); } return super.getSize(); } /** * * @param jsonObject */ private void init(Object jsonObject) { setCharacterSet(CharacterSet.UTF_8); this.jsonValue = jsonObject; this.indenting = false; this.indentingSize = 3; } /** * Indicates if JSON objects and arrays should be indented. * * @return True if JSON objects and arrays should be indented. * @deprecated Use {@link #isIndenting()} instead. */ @Deprecated public boolean isIndent() { return indenting; } /** * Indicates if JSON objects and arrays should be indented. * * @return True if JSON objects and arrays should be indented. */ public boolean isIndenting() { return isIndent(); } /** * Indicates if JSON objects and arrays should be indented. * * @param indenting * True if JSON objects and arrays should be indented. * @deprecated Use {@link #setIndenting(boolean)} instead. */ @Deprecated public void setIndent(boolean indenting) { this.indenting = indenting; } /** * Indicates if JSON objects and arrays should be indented. * * @param indenting * True if JSON objects and arrays should be indented. */ public void setIndenting(boolean indenting) { setIndent(indenting); } /** * Sets the number of spaces to use for indentation. * * @param indentFactor * The number of spaces to use for indentation. */ public void setIndentingSize(int indentFactor) { this.indentingSize = indentFactor; } /** * Sets the number of spaces to use for indentation. * * @param indentFactor * The number of spaces to use for indentation. * @deprecated Use {@link #setIndentingSize(int)} instead */ @Deprecated public void setIndentSize(int indentFactor) { setIndentingSize(indentFactor); } /** * Converts the representation to a JSON array. This method will trigger the * serialization of any wrapped JSON array. * * @return The converted JSON array. * @throws JSONException * @deprecated Use {@link #getJsonArray()} instead. */ @Deprecated public JSONArray toJsonArray() throws JSONException { return new JSONArray(getJsonText()); } /** * Converts the representation to a JSON object. This method will trigger * the serialization of any wrapped JSON object. * * @return The converted JSON object. * @throws JSONException * @deprecated Use {@link #getJsonObject()} instead. */ @Deprecated public JSONObject toJsonObject() throws JSONException { return new JSONObject(getJsonText()); } /** * Converts the representation to a JSON tokener. This method will trigger * the serialization of any wrapped JSON tokener. * * @return The converted JSON tokener. * @throws JSONException * @deprecated Use {@link #getJsonTokener()} instead. */ @Deprecated public JSONTokener toJsonTokener() throws JSONException { return new JSONTokener(getJsonText()); } @Override public void write(Writer writer) throws IOException { try { writer.write(getJsonText()); } catch (JSONException e) { IOException ioe = new IOException(e.getLocalizedMessage()); ioe.initCause(e.getCause()); throw ioe; } } } restlet-2.0.14/org.restlet.ext.lucene/0000775000175000017500000000000012001473210020243 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/pom.xml0000600000175000017500000000334412001473210021552 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.lucene Restlet Extension - Lucene Integration with Apache Lucene, Solr and Tika sub-projects. commons-io commons-io 1.4 org.apache.lucene lucene-core 2.9.2 org.apache.solr solr-core 1.4.0 org.apache.solr solr-solrj 1.4.0 org.apache.tika tika-core 0.6 org.apache.tika tika-parsers 0.6 org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 restlet-2.0.14/org.restlet.ext.lucene/src/0000775000175000017500000000000012001473210021032 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/META-INF/0000775000175000017500000000000011757206452022215 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/META-INF/services/0000775000175000017500000000000011757206352024037 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/META-INF/services/org.restlet.engine.ClientHelper0000664000175000017500000000006111757206352032050 0ustar jamespagejamespageorg.restlet.ext.lucene.SolrClientHelper # SOLR restlet-2.0.14/org.restlet.ext.lucene/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023646 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.lucene/src/org/0000775000175000017500000000000011757206352021643 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/0000775000175000017500000000000011757206352023325 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/0000775000175000017500000000000011757206352024125 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/0000775000175000017500000000000011757206352025400 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/internal/0000775000175000017500000000000011757206352027214 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/internal/SolrRestletParams.java0000664000175000017500000000525711757206352033516 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.lucene.internal; import java.util.Iterator; import org.apache.solr.common.params.SolrParams; import org.restlet.Request; import org.restlet.data.Form; /** * Wrap Restlet query parameters as Solr params. * * @author Remi Dewitte */ public class SolrRestletParams extends SolrParams { private static final long serialVersionUID = 1L; /** The wrapped Restlet request. */ private final Request request; /** * Constructor. * * @param request * The wrapped Restlet request. */ public SolrRestletParams(Request request) { this.request = request; } /** * Returns the request query form. * * @return The request query form. */ protected Form getForm() { return request.getResourceRef().getQueryAsForm(); } /** * Reads parameter from the form returned {@link #getForm()}. * */ @Override public String get(String param) { return getForm().getFirstValue(param); } /** * Reads parameter names from the form returned {@link #getForm()}. * */ @Override public Iterator getParameterNamesIterator() { return getForm().getNames().iterator(); } /** * Reads parameter values from the form returned {@link #getForm()}. * */ @Override public String[] getParams(String param) { return getForm().getValuesArray(param); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/internal/SolrRepresentationContentStream.javarestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/internal/SolrRepresentationContentS0000664000175000017500000000752211757206352034465 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.lucene.internal; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.apache.solr.common.util.ContentStream; import org.restlet.representation.Representation; /** * Solr content stream wrapping a Restlet representation. * * @author Rémi Dewitte */ public class SolrRepresentationContentStream implements ContentStream { /** The wrapped representation. */ private Representation representation; /** * Constructor. * * @param representation * The wrapped representation. */ public SolrRepresentationContentStream(Representation representation) { this.representation = representation; } /** * Returns the wrapped representation's media type. * * @return The wrapped representation's media type. * @see ContentStream#getContentType() */ public String getContentType() { if (representation.getMediaType() != null) return representation.getMediaType().getName(); return null; } /** * Returns the wrapped representation's download name. * * @return The wrapped representation's download name. * @see ContentStream#getName() */ public String getName() { if (representation.getDisposition() != null) { representation.getDisposition().getFilename(); } return null; } /** * Returns the wrapped representation's reader. * * @return The wrapped representation's reader. * @see ContentStream#getReader() */ public Reader getReader() throws IOException { return representation.getReader(); } /** * Returns the wrapped representation's size. * * @return The wrapped representation's size. * @see ContentStream#getSize() */ public Long getSize() { long s = representation.getSize(); if (s == Representation.UNKNOWN_SIZE) return null; return s; } /** * Returns the wrapped representation's identifier. * * @return The wrapped representation's identifier. * @see ContentStream#getSourceInfo() */ public String getSourceInfo() { if (representation.getLocationRef() != null) return representation.getLocationRef().toString(); return null; } /** * Returns the wrapped representation's stream. * * @return The wrapped representation's stream. * @see ContentStream#getStream() */ public InputStream getStream() throws IOException { return representation.getStream(); } } restlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/internal/SolrRepresentation.java0000664000175000017500000000720511757206352033725 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.lucene.internal; import java.io.IOException; import java.io.Writer; import org.apache.solr.request.JSONResponseWriter; import org.apache.solr.request.QueryResponseWriter; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrQueryResponse; import org.apache.solr.request.XMLResponseWriter; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.representation.WriterRepresentation; /** * Representation wrapping a Solr query and exposing its response either as XML * or JSON. * * @author Remi Dewitte */ public class SolrRepresentation extends WriterRepresentation { /** The wrapped Solr query request. */ protected SolrQueryRequest solrQueryRequest; /** The wrapped Solr query response. */ protected SolrQueryResponse solrQueryResponse; /** * Constructor. Note that the character set is UTF-8 by default. * * @param mediaType * The media type. * @param solrQueryRequest * The wrapped Solr query request. * @param solrQueryResponse * The wrapped Solr query response. */ public SolrRepresentation(MediaType mediaType, SolrQueryRequest solrQueryRequest, SolrQueryResponse solrQueryResponse) { super(mediaType); setCharacterSet(CharacterSet.UTF_8); this.solrQueryRequest = solrQueryRequest; this.solrQueryResponse = solrQueryResponse; } /** * Constructor. * * @param solrQueryRequest * The wrapped Solr query request. * @param solrQueryResponse * The wrapped Solr query response. * @see #SolrRepresentation(MediaType, SolrQueryRequest, SolrQueryResponse) */ public SolrRepresentation(SolrQueryRequest solrQueryRequest, SolrQueryResponse solrQueryResponse) { this(null, solrQueryRequest, solrQueryResponse); } @Override public void write(Writer writer) throws IOException { QueryResponseWriter qrWriter; if (MediaType.APPLICATION_JSON.isCompatible(getMediaType()) || MediaType.APPLICATION_JAVASCRIPT .isCompatible(getMediaType())) { qrWriter = new JSONResponseWriter(); } else { qrWriter = new XMLResponseWriter(); } qrWriter.write(writer, solrQueryRequest, solrQueryResponse); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/internal/SolrRestletQueryRequest.javarestlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/internal/SolrRestletQueryRequest.ja0000664000175000017500000000424611757206352034417 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.lucene.internal; import java.util.ArrayList; import org.apache.solr.common.util.ContentStream; import org.apache.solr.core.SolrCore; import org.apache.solr.request.SolrQueryRequestBase; import org.restlet.Request; /** * Solr query request wrapping a Restlet request. * * @author Remi Dewitte */ public class SolrRestletQueryRequest extends SolrQueryRequestBase { /** * Constructor. * * @param request * The Restlet request to wrap. * @param core * The Solr core. */ public SolrRestletQueryRequest(Request request, SolrCore core) { super(core, new SolrRestletParams(request)); getContext().put("path", request.getResourceRef().getPath()); ArrayList _streams = new ArrayList(1); _streams.add(new SolrRepresentationContentStream(request.getEntity())); setContentStreams(_streams); } } restlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/TikaRepresentation.java0000664000175000017500000001671111757206352032064 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.lucene; import java.io.IOException; import org.apache.tika.config.TikaConfig; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.HttpHeaders; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.TikaMetadataKeys; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.restlet.engine.util.DateUtils; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.representation.Representation; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * Representation that parses another wrapped representation using Lucene Tika * metadata extraction engine. * * Tika can be configured to indicates a specific parser to used, otherwise a * special auto-detect parser is used. Tike metadata can also be customized if * wanted. * * @author Jerome Louvel */ public class TikaRepresentation extends SaxRepresentation { /** The Tika metadata used for both input and output. */ private Metadata metadata; /** The wrapped representation to analyze. */ private Representation representation; /** The optional Tika configuration. */ private TikaConfig tikaConfig; /** The optional Tika parser. */ private Parser tikaParser; /** * Constructor. * * @param representation * The wrapped representation to analyze. */ public TikaRepresentation(Representation representation) { this(representation, null); } /** * Constructor. * * @param representation * The wrapped representation to analyze. * @param tikaConfig * The optional Tika configuration. */ public TikaRepresentation(Representation representation, TikaConfig tikaConfig) { this(representation, tikaConfig, null); } /** * Constructor. * * @param representation * The wrapped representation to analyze. * @param tikaConfig * The optional Tika configuration. * @param tikaParser * The optional Tika parser. */ public TikaRepresentation(Representation representation, TikaConfig tikaConfig, Parser tikaParser) { super((representation == null) ? null : representation.getMediaType()); setNamespaceAware(true); this.tikaConfig = tikaConfig; this.representation = representation; this.metadata = new Metadata(); } /** * Returns the Tika metadata used for both input and output. * * @return The Tika metadata used for both input and output. */ public Metadata getMetadata() { return metadata; } /** * Returns the optional Tika configuration. * * @return The Tika configuration or null. */ public TikaConfig getTikaConfig() { return tikaConfig; } /** * Returns the optional Tika parser. * * @return The Tika parser or null. */ public Parser getTikaParser() { return tikaParser; } /** * Parsed the wrapped representation with Tika to extract the useful * metadata and produce structural SAX events (in XHTML format) and send * them to the given SAX content handler. * * @param contentHandler * The target SAX handler. */ @Override public void parse(ContentHandler contentHandler) throws IOException { if (this.representation != null) { try { // Add common HTTP metadata if (this.representation.getDisposition() != null) { String name = this.representation.getDisposition() .getFilename(); if (name != null) { getMetadata().set(TikaMetadataKeys.RESOURCE_NAME_KEY, name); getMetadata() .set(HttpHeaders.CONTENT_DISPOSITION, name); } } getMetadata().set(HttpHeaders.CONTENT_TYPE, this.representation.getMediaType().toString()); if (this.representation.getSize() != UNKNOWN_SIZE) { getMetadata().set(HttpHeaders.CONTENT_LENGTH, Long.toString(this.representation.getSize())); } if (this.representation.getModificationDate() != null) { getMetadata().set( HttpHeaders.LAST_MODIFIED, DateUtils.format(this.representation .getModificationDate())); } // Prepare the Tika parser Parser parser = (getTikaParser() != null) ? getTikaParser() : (getTikaConfig() != null) ? new AutoDetectParser( getTikaConfig()) : new AutoDetectParser(); // Parse the wrapped representation parser.parse(this.representation.getStream(), contentHandler, getMetadata(), new ParseContext()); } catch (SAXException e) { throw new IOException("SAX exception: " + e.getLocalizedMessage()); } catch (TikaException e) { throw new IOException("Tika exception: " + e.getLocalizedMessage()); } } else { throw new IOException("No wrapped representation to parse."); } } /** * The Tika metadata used for both input and output. * * @param metadata * The Tika metadata. */ public void setMetadata(Metadata metadata) { this.metadata = metadata; } /** * Sets the optional Tika configuration. * * @param tikaConfig * The Tika configuration. */ public void setTikaConfig(TikaConfig tikaConfig) { this.tikaConfig = tikaConfig; } /** * Sets the optional Tika parser. * * @param tikaParser * The Tika parser. */ public void setTikaParser(Parser tikaParser) { this.tikaParser = tikaParser; } } restlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/package.html0000664000175000017500000000072411757206352027664 0ustar jamespagejamespage Integration with Apache Lucene 2.9. This extension provides a client connector for Lucene Solr 1.3 sub-project (complete search and indexing engine) that can be used as an alternative to deployment within a Servlet container. There is also support for automatic extraction of metadata from Restlet representation by leveraging Lucene Tika 0.4 sub-project. @since Restlet 2.0 @see Apache Lucene restlet-2.0.14/org.restlet.ext.lucene/src/org/restlet/ext/lucene/SolrClientHelper.java0000664000175000017500000001624411757206352031470 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.lucene; import java.io.File; import java.net.URI; import java.util.logging.Level; import org.apache.solr.common.params.CommonParams; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.SolrCore; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrQueryResponse; import org.apache.solr.request.SolrRequestHandler; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.ClientHelper; import org.restlet.ext.lucene.internal.SolrRepresentation; import org.restlet.ext.lucene.internal.SolrRestletQueryRequest; /** * Solr client connector. * * There are two ways of initializing the helped core container.
    * First one :
    * *

     * Client solrClient = component.getClients().add(SolrClientHelper.SOLR_PROTOCOL);
     * solrClient.getContext().getAttributes().put("CoreContainer", new CoreContainer(...));
     * 
    * *
    * Second one :
    * *
     * Client solrClient = component.getClients().add(SolrClientHelper.SOLR_PROTOCOL);
     * solrClient.getContext().getParameters().add("directory", "...");
     * solrClient.getContext().getParameters().add("configFile", "...");
     * 
    * *
    * The helper handles "solr://" requests. There is one additional parameter : * "DefaultCore" which gives default core for "solr:///..." requests. * * @author Remi Dewitte */ public class SolrClientHelper extends ClientHelper { public static Protocol SOLR_PROTOCOL = new Protocol("solr", "Solr", "Solr indexer helper", Protocol.UNKNOWN_PORT); /** The core Solr container. */ protected CoreContainer coreContainer; /** * Constructor. * * @param client * The client connector. */ public SolrClientHelper(Client client) { super(client); getProtocols().add(SOLR_PROTOCOL); } @Override public void handle(Request request, Response response) { super.handle(request, response); Reference resRef = request.getResourceRef(); String path = resRef.getPath(); if (path != null) { path = resRef.getPath(true); } String coreName = request.getResourceRef().getHostDomain(); if (coreName == null || "".equals(coreName)) { coreName = getContext().getParameters() .getFirstValue("DefaultCore"); } SolrCore core = coreContainer.getCore(coreName); if (core == null) { response.setStatus(Status.SERVER_ERROR_INTERNAL, "No such core: " + coreName); return; } // Extract the handler from the path or params SolrRequestHandler handler = core.getRequestHandler(path); if (handler == null) { if ("/select".equals(path) || "/select/".equalsIgnoreCase(path)) { String qt = request.getResourceRef().getQueryAsForm() .getFirstValue(CommonParams.QT); handler = core.getRequestHandler(qt); if (handler == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "unknown handler: " + qt); return; } } // Perhaps the path is to manage the cores if (handler == null && coreContainer != null && path.equals(coreContainer.getAdminPath())) { handler = coreContainer.getMultiCoreHandler(); } } if (handler == null) { core.close(); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "unknown handler: " + path); return; } try { SolrQueryRequest solrReq = new SolrRestletQueryRequest(request, core); SolrQueryResponse solrResp = new SolrQueryResponse(); core.execute(handler, solrReq, solrResp); if (solrResp.getException() != null) { response.setStatus(Status.SERVER_ERROR_INTERNAL, solrResp .getException()); } else { response.setEntity(new SolrRepresentation( MediaType.APPLICATION_XML, solrReq, solrResp)); response.setStatus(Status.SUCCESS_OK); } } catch (Exception e) { getLogger().log(Level.WARNING, "Unable to evaluate " + resRef.toString(), e); response.setStatus(Status.SERVER_ERROR_INTERNAL, e); } finally { core.close(); } } @Override public void start() { try { coreContainer = (CoreContainer) getHelped().getContext() .getAttributes().get("CoreContainer"); if (coreContainer == null) { String directory = getHelped().getContext().getParameters() .getFirstValue("directory"); String configFile = getHelped().getContext().getParameters() .getFirstValue("configFile"); if (directory != null && configFile != null) { File config = new File(configFile); if (!config.exists()) { config = new File(new URI(configFile)); } coreContainer = new CoreContainer(directory, config); } } if (coreContainer == null) { throw new RuntimeException( "Could not initialize core container"); } } catch (Exception e) { throw new RuntimeException("Could not initialize core container", e); } } @Override public void stop() throws Exception { super.stop(); } } restlet-2.0.14/org.restlet.ext.jaxb/0000775000175000017500000000000012001473135017722 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/pom.xml0000600000175000017500000000221512001473134021224 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.jaxb Restlet Extension - JAXB Integration with Java XML Binding. javax.xml.bind jaxb-api 2.1 com.sun.xml.bind jaxb-impl 2.1.12 javax.xml.stream stax-api 1.0-2 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.jaxb/src/0000775000175000017500000000000012001473134020510 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/src/META-INF/0000775000175000017500000000000011757206450021664 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/src/META-INF/services/0000775000175000017500000000000011757206346023513 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.jaxb/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.jaxb/src/META-INF/services/org.restlet.engine.converter.ConverterHelp0000664000175000017500000000004211757206346033733 0ustar jamespagejamespageorg.restlet.ext.jaxb.JaxbConverterrestlet-2.0.14/org.restlet.ext.jaxb/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446023324 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.jaxb/src/org/0000775000175000017500000000000011757206344021315 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/0000775000175000017500000000000011757206344022777 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/0000775000175000017500000000000011757206344023577 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/jaxb/0000775000175000017500000000000011757206346024525 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/jaxb/internal/0000775000175000017500000000000011757206346026341 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/jaxb/internal/Marshaller.java0000664000175000017500000001532411757206346031303 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxb.internal; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.logging.Level; import javax.xml.bind.JAXBException; import org.restlet.Context; import org.restlet.ext.jaxb.JaxbRepresentation; /** * This is a utility class to assist in marshaling Java content trees into XML. * Each {@code marshal} method takes a different target for the XML. * * This class is a factory that constructs an instance of itself for multiple * uses. The created instance is thread safe and is optimized to be used for * multiple, possibly concurrent calls. * * @author Overstock.com */ public class Marshaller { /** The parent JAXB representation. */ private final JaxbRepresentation jaxbRepresentation; /** Use thread identity to preserve safety of access to marshalers. */ private final ThreadLocal marshaller = new ThreadLocal() { @Override protected synchronized javax.xml.bind.Marshaller initialValue() { javax.xml.bind.Marshaller m = null; try { m = JaxbRepresentation.getContext(getContextPath(), getClassLoader()).createMarshaller(); m.setProperty("jaxb.formatted.output", getJaxbRepresentation() .isFormattedOutput()); if (getJaxbRepresentation().getSchemaLocation() != null) { m.setProperty("jaxb.schemaLocation", getJaxbRepresentation().getSchemaLocation()); } if (getJaxbRepresentation().getNoNamespaceSchemaLocation() != null) { m.setProperty("jaxb.noNamespaceSchemaLocation", getJaxbRepresentation() .getNoNamespaceSchemaLocation()); } if (Marshaller.this.jaxbRepresentation.getCharacterSet() != null) { m.setProperty("jaxb.encoding", Marshaller.this.jaxbRepresentation .getCharacterSet().getName()); } m.setProperty("jaxb.fragment", getJaxbRepresentation() .isFragment()); } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING, "Problem creating Marshaller", e); return null; } return m; } }; /** The JAXB context path. */ private final String contextPath; /** The JAXB classloader. */ private final ClassLoader classLoader; // This is a factory class. public Marshaller(JaxbRepresentation jaxbRepresentation) { this(jaxbRepresentation, null, null); } /** * Constructor. * * @param jaxbRepresentation * The JAXB representation to marshal. * @param contextPath * The JAXB context path. * @param classLoader * The JAXB classloader. */ public Marshaller(JaxbRepresentation jaxbRepresentation, String contextPath, ClassLoader classLoader) { this.jaxbRepresentation = jaxbRepresentation; this.contextPath = contextPath; this.classLoader = classLoader; } /** * Returns the JAXB context path. * * @return The JAXB context path. */ public String getContextPath() { return this.contextPath; } /** * Returns the JAXB classloader. * * @return The JAXB classloader. */ public ClassLoader getClassLoader() { return this.classLoader; } /** * Returns the parent JAXB representation. * * @return The parent JAXB representation. */ public JaxbRepresentation getJaxbRepresentation() { return jaxbRepresentation; } /** * Returns the JAXB marshaller. * * @return The JAXB marshaller. * @throws JAXBException */ private javax.xml.bind.Marshaller getMarshaller() throws JAXBException { final javax.xml.bind.Marshaller m = this.marshaller.get(); if (m == null) { Context.getCurrentLogger().warning("Unable to locate marshaller."); throw new JAXBException("Unable to locate marshaller."); } return m; } /** * Marshals the content tree rooted at {@code jaxbElement} into an output * stream. * * @param jaxbElement * The root of the content tree to be marshalled. * @param stream * The target output stream write the XML to. * @throws JAXBException * If any unexpected problem occurs during marshalling. */ public void marshal(Object jaxbElement, OutputStream stream) throws JAXBException { marshal(jaxbElement, new OutputStreamWriter(stream)); } /** * Marshal the content tree rooted at {@code jaxbElement} into a writer. * * @param jaxbElement * The root of the content tree to be marshaled. * @param writer * The target writer to write the XML to. * @throws JAXBException * If any unexpected problem occurs during marshaling. */ public void marshal(Object jaxbElement, Writer writer) throws JAXBException { getMarshaller().setEventHandler( getJaxbRepresentation().getValidationEventHandler()); getMarshaller().marshal(jaxbElement, writer); } } restlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/jaxb/internal/Unmarshaller.java0000664000175000017500000001675111757206346031653 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxb.internal; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.logging.Level; import javax.xml.XMLConstants; import javax.xml.bind.JAXBException; import javax.xml.bind.ValidationEventHandler; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.restlet.Context; import org.restlet.ext.jaxb.JaxbRepresentation; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * This is a utility class to assist in unmarshaling XML into a new Java content * tree. * * Each {@code unmarshal} method takes a different source for the XML. This * class caches information to improve unmarshaling performance across calls * using the same schema (package). * * @author Overstock.com */ public class Unmarshaller { /** The JAXB context path. */ private final String contextPath; /** * Use thread identity to preserve safety of access to unmarshallers. */ private final ThreadLocal unmarshaller = new ThreadLocal() { @Override protected synchronized javax.xml.bind.Unmarshaller initialValue() { javax.xml.bind.Unmarshaller m = null; try { m = JaxbRepresentation.getContext(getContextPath(), getClassLoader()).createUnmarshaller(); } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING, "Problem creating Unmarshaller", e); return null; } return m; } }; /** The JAXB classloader. */ private final ClassLoader classLoader; /** * Constructor. * * @param contextPath * The JAXB context path. * @param classloader * The JAXB classloader. */ public Unmarshaller(String contextPath, ClassLoader classloader) { this.contextPath = contextPath; this.classLoader = classloader; } /** * Returns the JAXB classloader. * * @return The JAXB classloader. */ public ClassLoader getClassLoader() { return this.classLoader; } /** * Returns the JAXB context path. * * @return The JAXB context path. */ public String getContextPath() { return this.contextPath; } /** * Returns the JAXB unmarshaller. * * @return The JAXB unmarshaller. * @throws JAXBException */ private javax.xml.bind.Unmarshaller getUnmarshaller() throws JAXBException { final javax.xml.bind.Unmarshaller m = this.unmarshaller.get(); if (m == null) { Context.getCurrentLogger() .warning("Unable to locate unmarshaller."); throw new JAXBException("Unable to locate unmarshaller."); } return m; } /** * Sets the validation handler for this unmarshaller. * * @param handler * A validation handler. * @throws JAXBException * If an error was encountered while setting the event handler. */ public void setEventHandler(ValidationEventHandler handler) throws JAXBException { getUnmarshaller().setEventHandler(handler); } /** * Unmarshal XML data from the specified input stream and return the * resulting Java content tree. * * @param stream * The source input stream. * @return The newly created root object of the Java content tree. * @throws JAXBException * If any unexpected problem occurs during unmarshaling. * @throws IOException * If an error occurs accessing the string representation. */ public Object unmarshal(JaxbRepresentation jaxbRep, InputStream stream) throws JAXBException { return unmarshal(jaxbRep, new InputStreamReader(stream)); } /** * Unmarshal XML data from the specified reader and return the resulting * Java content tree. * * @param reader * The source reader. * @return The newly created root object of the Java content tree. * @throws JAXBException * If any unexpected problem occurs during unmarshaling. * @throws IOException * If an error occurs accessing the string representation. */ public Object unmarshal(JaxbRepresentation jaxbRep, Reader reader) throws JAXBException { SAXSource ss = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); // Keep before the external entity preferences spf.setValidating(jaxbRep.isValidatingDtd()); spf.setXIncludeAware(jaxbRep.isXIncludeAware()); spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, jaxbRep.isSecureProcessing()); spf.setFeature( "http://xml.org/sax/features/external-general-entities", jaxbRep.isExpandingEntityRefs()); spf.setFeature( "http://xml.org/sax/features/external-parameter-entities", jaxbRep.isExpandingEntityRefs()); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); ss = new SAXSource(xmlReader, new InputSource(reader)); } catch (Exception e) { throw new JAXBException("Unable to create customized SAX source", e); } getUnmarshaller().setEventHandler(jaxbRep.getValidationEventHandler()); return getUnmarshaller().unmarshal(ss); } /** * Unmarshal XML data from the specified Restlet string representation and * return the resulting Java content tree. * * @param jaxbRep * The source JAXB representation. * @return The newly created root object of the Java content tree. * @throws JAXBException * If any unexpected problem occurs during unmarshaling. * @throws IOException * If an error occurs accessing the string representation. */ public Object unmarshal(JaxbRepresentation jaxbRep) throws JAXBException, IOException { return unmarshal(jaxbRep, jaxbRep.getReader()); } } restlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/jaxb/JaxbConverter.java0000664000175000017500000001611511757206346030150 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxb; import java.io.IOException; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * A JAXB Converter Helper to convert from JAXB objects to JaxbRepresentations * and vice versa. * * @author Sanjay Acharya */ public class JaxbConverter extends ConverterHelper { private static final VariantInfo VARIANT_APPLICATION_ALL_XML = new VariantInfo( MediaType.APPLICATION_ALL_XML); private static final VariantInfo VARIANT_APPLICATION_XML = new VariantInfo( MediaType.APPLICATION_XML); private static final VariantInfo VARIANT_TEXT_XML = new VariantInfo( MediaType.TEXT_XML); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_APPLICATION_ALL_XML.isCompatible(source) || VARIANT_APPLICATION_XML.isCompatible(source) || VARIANT_TEXT_XML.isCompatible(source)) { result = addObjectClass(result, JaxbRepresentation.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (isJaxbRootElementClass(source) || JaxbRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_APPLICATION_ALL_XML); result = addVariant(result, VARIANT_APPLICATION_XML); result = addVariant(result, VARIANT_TEXT_XML); } return result; } /** * Indicates if the class has JAXB annotations. * * @param source * The class to test. * @return True if the class has JAXB annotations. */ private boolean isJaxbRootElementClass(Class source) { return source != null && source.isAnnotationPresent(XmlRootElement.class); } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source != null && (source instanceof JaxbRepresentation || isJaxbRootElementClass(source .getClass()))) { if (target == null) { result = 0.8F; } else if (MediaType.APPLICATION_ALL_XML.isCompatible(target .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_XML.isCompatible(target .getMediaType())) { result = 1.0F; } else if (MediaType.TEXT_XML.isCompatible(target.getMediaType())) { result = 1.0F; } else { // Allow for JAXB object to be used for JSON and other // representations result = 0.7F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (source != null) { if (source instanceof JaxbRepresentation) { result = 1.0F; } else if (JaxbRepresentation.class.isAssignableFrom(source .getClass())) { result = 1.0F; } else if (isJaxbRootElementClass(target) || JaxbRepresentation.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_ALL_XML.isCompatible(source .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_XML.isCompatible(source .getMediaType())) { result = 1.0F; } else if (MediaType.TEXT_XML.isCompatible(source .getMediaType())) { result = 1.0F; } else { // Allow for JAXB object to be used for JSON and other // representations result = 0.7F; } } } return result; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (JaxbRepresentation.class.isAssignableFrom(target)) { result = new JaxbRepresentation(source, target); } else if (isJaxbRootElementClass(target)) { result = new JaxbRepresentation(source, target).getObject(); } else if (target == null) { if (source instanceof JaxbRepresentation) { result = ((JaxbRepresentation) source).getObject(); } } return target.cast(result); } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; if (isJaxbRootElementClass(source.getClass())) { result = new JaxbRepresentation(source); } else if (source instanceof JaxbRepresentation) { result = (Representation) source; } return result; } @Override public void updatePreferences(List> preferences, Class entity) { if (JaxbRepresentation.class.isAssignableFrom(entity) || isJaxbRootElementClass(entity)) { updatePreferences(preferences, MediaType.APPLICATION_ALL_XML, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_XML, 1.0F); updatePreferences(preferences, MediaType.TEXT_XML, 1.0F); } } } restlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/jaxb/package.html0000664000175000017500000000044211757206346027006 0ustar jamespagejamespage Integration with Java XML Binding (JAXB) 2.1. JAXB provides a convenient way to process XML content using Java objects by binding it's XML schema to Java representation. @since Restlet 1.1 @see JAXB Web site restlet-2.0.14/org.restlet.ext.jaxb/src/org/restlet/ext/jaxb/JaxbRepresentation.java0000664000175000017500000005233111757206344031201 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxb; import java.io.IOException; import java.io.Writer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.ValidationEventHandler; import javax.xml.bind.util.JAXBSource; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.sax.SAXSource; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.ext.jaxb.internal.Marshaller; import org.restlet.ext.jaxb.internal.Unmarshaller; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.xml.sax.InputSource; /** * An XML representation based on JAXB that provides easy translation between * XML and JAXB element class trees. * * @author Overstock.com * @author Jerome Louvel * @param * The type to wrap. */ public class JaxbRepresentation extends WriterRepresentation { /** Improves performance by caching contexts which are expensive to create. */ private final static ConcurrentMap contexts = new ConcurrentHashMap(); /** * Returns the JAXB context, if possible from the cached contexts. * * @param contextPath * * @param classLoader * * @return The JAXB context. * @throws JAXBException */ public static synchronized JAXBContext getContext(String contextPath, ClassLoader classLoader) throws JAXBException { // Contexts are thread-safe so reuse those. JAXBContext result = contexts.get(contextPath); if (result == null) { result = classLoader == null ? JAXBContext.newInstance(contextPath) : JAXBContext.newInstance(contextPath, classLoader); contexts.put(contextPath, result); } return result; } /** * The classloader to use for JAXB annotated classes. */ private volatile ClassLoader classLoader; /** * The list of Java package names that contain schema derived class and/or * Java to schema (JAXB-annotated) mapped classes. */ private volatile String contextPath; /** * Specifies that the parser will expand entity reference nodes. By default * the value of this is set to true. */ private volatile boolean expandingEntityRefs; /** * Indicates if the resulting XML data should be formatted with line breaks * and indentation. Defaults to false. */ private volatile boolean formattedOutput; /** * Indicates whether or not document level events will be generated by the * Marshaller. */ private volatile boolean fragment; /** The "xsi:noNamespaceSchemaLocation" attribute in the generated XML data. */ private volatile String noNamespaceSchemaLocation; /** The wrapped Java object. */ private volatile T object; /** The "xsi:schemaLocation" attribute in the generated XML data */ private volatile String schemaLocation; /** Limits potential XML overflow attacks. */ private boolean secureProcessing; /** * Indicates the desire for validating this type of XML representations * against a DTD. Note that for XML schema or Relax NG validation, use the * "schema" property instead. * * @see DocumentBuilderFactory#setValidating(boolean) */ private volatile boolean validatingDtd; /** The JAXB validation event handler. */ private volatile ValidationEventHandler validationEventHandler; /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @see DocumentBuilderFactory#setXIncludeAware(boolean) */ private volatile boolean xIncludeAware; /** The source XML representation. */ private volatile Representation xmlRepresentation; /** * Creates a JAXB representation from an existing JAXB content tree. * * @param mediaType * The representation's media type. * @param object * The Java object. */ public JaxbRepresentation(MediaType mediaType, T object) { this(mediaType, object, (object != null) ? object.getClass() .getClassLoader() : null); } /** * Creates a JAXB representation from an existing JAXB content tree. * * @param mediaType * The representation's media type. * @param object * The Java object. * @param classloader * The classloader to use for JAXB annotated classes. */ private JaxbRepresentation(MediaType mediaType, T object, ClassLoader classloader) { super(mediaType); this.classLoader = classloader; this.contextPath = (object != null) ? object.getClass().getPackage() .getName() : null; this.object = object; this.validationEventHandler = null; this.xmlRepresentation = null; this.expandingEntityRefs = false; this.formattedOutput = false; this.fragment = false; this.noNamespaceSchemaLocation = null; this.schemaLocation = null; this.secureProcessing = true; this.validatingDtd = false; this.xIncludeAware = false; } /** * Creates a new JAXB representation, converting the input XML into a Java * content tree. The XML is validated. * * @param xmlRepresentation * The XML wrapped in a representation. * @param type * The type to convert to. * * @throws JAXBException * If the incoming XML does not validate against the schema. * @throws IOException * If unmarshalling XML fails. */ public JaxbRepresentation(Representation xmlRepresentation, Class type) { this(xmlRepresentation, type.getPackage().getName(), null, type .getClassLoader()); } /** * Creates a new JAXB representation, converting the input XML into a Java * content tree. The XML is validated. * * @param xmlRepresentation * The XML wrapped in a representation. * @param type * The type to convert to. * @param validationHandler * A handler for dealing with validation failures. * * @throws JAXBException * If the incoming XML does not validate against the schema. * @throws IOException * If unmarshalling XML fails. */ public JaxbRepresentation(Representation xmlRepresentation, Class type, ValidationEventHandler validationHandler) { this(xmlRepresentation, type.getPackage().getName(), validationHandler, type.getClassLoader()); } /** * Creates a new JAXB representation, converting the input XML into a Java * content tree. The XML is validated. * * @param xmlRepresentation * The XML wrapped in a representation. * @param contextPath * The list of Java package names for JAXB. * * @throws JAXBException * If the incoming XML does not validate against the schema. * @throws IOException * If unmarshalling XML fails. */ public JaxbRepresentation(Representation xmlRepresentation, String contextPath) { this(xmlRepresentation, contextPath, null, null); } /** * Creates a new JAXB representation, converting the input XML into a Java * content tree. The XML is validated. * * @param xmlRepresentation * The XML wrapped in a representation. * @param contextPath * The list of Java package names for JAXB. * @param validationHandler * A handler for dealing with validation failures. * * @throws JAXBException * If the incoming XML does not validate against the schema. * @throws IOException * If unmarshalling XML fails. */ public JaxbRepresentation(Representation xmlRepresentation, String contextPath, ValidationEventHandler validationHandler) { this(xmlRepresentation, contextPath, validationHandler, null); } /** * Creates a new JAXB representation, converting the input XML into a Java * content tree. The XML is validated. * * @param xmlRepresentation * The XML wrapped in a representation. * @param contextPath * The list of Java package names for JAXB. * @param validationHandler * A handler for dealing with validation failures. * @param classLoader * The classloader to use for JAXB annotated classes. * @throws JAXBException * If the incoming XML does not validate against the schema. * @throws IOException * If unmarshalling XML fails. */ private JaxbRepresentation(Representation xmlRepresentation, String contextPath, ValidationEventHandler validationHandler, ClassLoader classLoader) { super(xmlRepresentation.getMediaType()); this.classLoader = classLoader; this.contextPath = contextPath; this.object = null; this.validationEventHandler = validationHandler; this.xmlRepresentation = xmlRepresentation; } /** * Creates a JAXB representation from an existing JAXB content tree with * {@link MediaType#APPLICATION_XML}. * * @param object * The Java object. */ public JaxbRepresentation(T object) { this(MediaType.APPLICATION_XML, object); } /** * Returns the classloader to use for JAXB annotated classes. * * @return The classloader to use for JAXB annotated classes. */ private ClassLoader getClassLoader() { return this.classLoader; } /** * Returns the JAXB context. * * @return The JAXB context. * @throws JAXBException */ public JAXBContext getContext() throws JAXBException { return getContext(getContextPath(), getClassLoader()); } /** * Returns the list of Java package names that contain schema derived class * and/or Java to schema (JAXB-annotated) mapped classes * * @return The list of Java package names. */ public String getContextPath() { return this.contextPath; } /** * Returns the XML representation as a SAX input source. * * @return The SAX input source. * @deprecated */ @Deprecated public InputSource getInputSource() throws IOException { return new InputSource(this.xmlRepresentation.getStream()); } /** * Returns a JAXB SAX source. * * @return A JAXB SAX source. */ public JAXBSource getJaxbSource() throws IOException { try { return new JAXBSource(getContext(), getObject()); } catch (JAXBException e) { throw new IOException( "JAXBException while creating the JAXBSource: " + e.getMessage()); } } /** * Returns the "xsi:noNamespaceSchemaLocation" attribute in the generated * XML data. * * @return The "xsi:noNamespaceSchemaLocation" attribute in the generated * XML data. */ public String getNoNamespaceSchemaLocation() { return noNamespaceSchemaLocation; } /** * Returns the wrapped Java object. * * @return The wrapped Java object. * @throws IOException */ @SuppressWarnings("unchecked") public T getObject() throws IOException { if ((this.object == null) && (this.xmlRepresentation != null)) { // Try to unmarshal the wrapped XML representation final Unmarshaller u = new Unmarshaller(this.contextPath, this.classLoader); if (getValidationEventHandler() != null) { try { u.setEventHandler(getValidationEventHandler()); } catch (JAXBException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to set the event handler", e); throw new IOException("Unable to set the event handler." + e.getMessage()); } } try { this.object = (T) u.unmarshal(this, this.xmlRepresentation.getReader()); } catch (JAXBException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to unmarshal the XML representation", e); throw new IOException( "Unable to unmarshal the XML representation." + e.getMessage()); } } return this.object; } /** * Returns a JAXB SAX source. * * @return A JAXB SAX source. * @deprecated Use {@link #getJaxbSource()} instead. */ @Deprecated public SAXSource getSaxSource() throws IOException { return getJaxbSource(); } /** * Returns the "xsi:schemaLocation" attribute in the generated XML data. * * @return The "xsi:schemaLocation" attribute in the generated XML data. */ public String getSchemaLocation() { return schemaLocation; } /** * Returns the optional validation event handler. * * @return The optional validation event handler. */ public ValidationEventHandler getValidationEventHandler() { return this.validationEventHandler; } /** * Indicates if the parser will expand entity reference nodes. By default * the value of this is set to true. * * @return True if the parser will expand entity reference nodes. */ public boolean isExpandingEntityRefs() { return expandingEntityRefs; } /** * Indicates if the resulting XML data should be formatted with line breaks * and indentation. Defaults to false. * * @return the formattedOutput */ public boolean isFormattedOutput() { return this.formattedOutput; } /** * Indicates whether or not document level events will be generated by the * Marshaller. * * @return True if the document level events will be generated by the * Marshaller. */ public boolean isFragment() { return fragment; } /** * Indicates if it limits potential XML overflow attacks. * * @return True if it limits potential XML overflow attacks. */ public boolean isSecureProcessing() { return secureProcessing; } /** * Indicates the desire for validating this type of XML representations * against an XML schema if one is referenced within the contents. * * @return True if the schema-based validation is enabled. */ public boolean isValidatingDtd() { return validatingDtd; } /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @return The current value of the xIncludeAware flag. */ public boolean isXIncludeAware() { return xIncludeAware; } /** * Sets the list of Java package names that contain schema derived class * and/or Java to schema (JAXB-annotated) mapped classes. * * @param contextPath * The JAXB context path. */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } /** * Indicates if the parser will expand entity reference nodes. By default * the value of this is set to true. * * @param expandEntityRefs * True if the parser will expand entity reference nodes. */ public void setExpandingEntityRefs(boolean expandEntityRefs) { this.expandingEntityRefs = expandEntityRefs; } /** * Indicates if the resulting XML data should be formatted with line breaks * and indentation. * * @param formattedOutput * True if the resulting XML data should be formatted. */ public void setFormattedOutput(boolean formattedOutput) { this.formattedOutput = formattedOutput; } /** * Indicates whether or not document level events will be generated by the * Marshaller. * * @param fragment * True if the document level events will be generated by the * Marshaller. */ public void setFragment(boolean fragment) { this.fragment = fragment; } /** * Sets the "xsi:noNamespaceSchemaLocation" attribute in the generated XML * data. * * @param noNamespaceSchemaLocation * The "xsi:noNamespaceSchemaLocation" attribute in the generated * XML data. */ public void setNoNamespaceSchemaLocation(String noNamespaceSchemaLocation) { this.noNamespaceSchemaLocation = noNamespaceSchemaLocation; } /** * Sets the wrapped Java object. * * @param object * The Java object to set. */ public void setObject(T object) { this.object = object; } /** * Sets the "xsi:schemaLocation" attribute in the generated XML data. * * @param schemaLocation * The "xsi:noNamespaceSchemaLocation" attribute in the generated * XML data. */ public void setSchemaLocation(String schemaLocation) { this.schemaLocation = schemaLocation; } /** * Indicates if it limits potential XML overflow attacks. * * @param secureProcessing * True if it limits potential XML overflow attacks. */ public void setSecureProcessing(boolean secureProcessing) { this.secureProcessing = secureProcessing; } /** * Indicates the desire for validating this type of XML representations * against an XML schema if one is referenced within the contents. * * @param validating * The new validation flag to set. */ public void setValidatingDtd(boolean validating) { this.validatingDtd = validating; } /** * Sets the validation event handler. * * @param validationEventHandler * The optional validation event handler. */ public void setValidationEventHandler( ValidationEventHandler validationEventHandler) { this.validationEventHandler = validationEventHandler; } /** * Indicates the desire for processing XInclude if found in this * type of XML representations. By default the value of this is set to * false. * * @param includeAware * The new value of the xIncludeAware flag. */ public void setXIncludeAware(boolean includeAware) { xIncludeAware = includeAware; } /** * Writes the representation to a stream of characters. * * @param writer * The writer to use when writing. * * @throws IOException * If any error occurs attempting to write the stream. */ @Override public void write(Writer writer) throws IOException { try { new Marshaller(this, this.contextPath, getClassLoader()) .marshal(getObject(), writer); } catch (JAXBException e) { Context.getCurrentLogger().log(Level.WARNING, "JAXB marshalling error caught.", e); // Maybe the tree represents a failure, try that. try { new Marshaller(this, "failure", getClassLoader()).marshal( getObject(), writer); } catch (JAXBException e2) { // We don't know what package this tree is from. throw new IOException(e.getMessage()); } } } } restlet-2.0.14/org.restlet/0000775000175000017500000000000012001473145016201 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/pom.xml0000600000175000017500000000136512001473145017511 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet Restlet Core RESTful Web framework for Java (API and engine). org.osgi org.osgi.core 4.0.0 compile restlet-2.0.14/org.restlet/src/0000775000175000017500000000000012001473145016770 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/META-INF/0000775000175000017500000000000011757206446020147 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/META-INF/MANIFEST.MF0000664000175000017500000000016411757206444021600 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) Class-Path: restlet-2.0.14/org.restlet/src/org/0000775000175000017500000000000011757206346017575 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/0000775000175000017500000000000011757206350021252 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/Server.java0000664000175000017500000004211611757206346023374 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.Arrays; import java.util.List; import org.restlet.data.Protocol; import org.restlet.engine.Engine; import org.restlet.engine.RestletHelper; import org.restlet.resource.Finder; /** * Connector acting as a generic server. It internally uses one of the available * connector helpers registered with the Restlet engine.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class Server extends Connector { /** The listening address if specified. */ private volatile String address; /** The helper provided by the implementation. */ private final RestletHelper helper; /** The listening port if specified. */ private volatile int port; /** The next Restlet. */ private volatile Restlet next; /** * Constructor. * * @param context * The context. * @param protocols * The connector protocols. * @param port * The listening port. * @param next * The next Restlet. */ public Server(Context context, List protocols, int port, Restlet next) { this(context, protocols, null, port, next); } /** * Constructor. * * @param context * The context. * @param protocols * The connector protocols. * @param address * The optional listening IP address (useful if multiple IP * addresses available). You can also use a domain name as an * alias for the IP address to listen to. * @param port * The listening port. * @param next * The next Restlet. */ public Server(Context context, List protocols, String address, int port, Restlet next) { this(context, protocols, address, port, next, null); } /** * Constructor. * * @param context * The context. * @param protocols * The connector protocols. * @param address * The optional listening IP address (useful if multiple IP * addresses available). You can also use a domain name as an * alias for the IP address to listen to. * @param port * The listening port. * @param next * The next Restlet. * @param helperClass * Optional helper class name. */ public Server(Context context, List protocols, String address, int port, Restlet next, String helperClass) { super(context, protocols); this.address = address; this.port = port; this.next = next; if (Engine.getInstance() != null) { this.helper = Engine.getInstance().createHelper(this, helperClass); } else { this.helper = null; } } /** * Constructor. * * @param context * The context. * @param protocol * The connector protocol. * @param nextClass * The next server resource. */ public Server(Context context, Protocol protocol, Class nextClass) { this(context, protocol, null, (protocol == null) ? -1 : protocol .getDefaultPort(), new Finder(Context.getCurrent(), nextClass)); } /** * Constructor. * * @param context * The parent context. * @param protocol * The connector protocol. * @param port * The listening port. */ public Server(Context context, Protocol protocol, int port) { this(context, protocol, port, (Restlet) null); } /** * Constructor. * * @param context * The context. * @param protocol * The connector protocol. * @param port * The listening port. * @param nextClass * The next server resource. */ public Server(Context context, Protocol protocol, int port, Class nextClass) { this(context, protocol, null, port, new Finder(Context.getCurrent(), nextClass)); } /** * Constructor. * * @param context * The context. * @param protocol * The connector protocol. * @param port * The listening port. * @param next * The next Restlet. */ public Server(Context context, Protocol protocol, int port, Restlet next) { this(context, protocol, null, port, next); } /** * Constructor using the protocol's default port. * * @param context * The context. * @param protocol * The connector protocol. * @param next * The next Restlet. */ public Server(Context context, Protocol protocol, Restlet next) { this(context, protocol, null, (protocol == null) ? -1 : protocol .getDefaultPort(), next); } /** * Constructor. * * @param context * The context. * @param protocol * The connector protocol. * @param address * The optional listening IP address (useful if multiple IP * addresses available). You can also use a domain name as an * alias for the IP address to listen to. * @param port * The listening port. * @param next * The next Restlet. */ public Server(Context context, Protocol protocol, String address, int port, Restlet next) { this(context, (protocol == null) ? null : Arrays.asList(protocol), address, port, next); } /** * Constructor. * * @param protocols * The connector protocols. * @param port * The listening port. * @param next * The next Restlet. */ public Server(List protocols, int port, Restlet next) { this((Context) null, protocols, port, next); } /** * Constructor. * * @param protocols * The connector protocols. * @param address * The optional listening IP address (useful if multiple IP * addresses available). You can also use a domain name as an * alias for the IP address to listen to. * @param port * The listening port. * @param next * The next Restlet. */ public Server(List protocols, String address, int port, Restlet next) { this((Context) null, protocols, address, port, next); } /** * Constructor. * * @param protocol * The connector protocol. */ public Server(Protocol protocol) { this((Context) null, protocol, (Restlet) null); } /** * Constructor using the protocol's default port. * * @param protocol * The connector protocol. * @param nextClass * The next server resource. */ public Server(Protocol protocol, Class nextClass) { this((Context) null, protocol, new Finder(Context.getCurrent(), nextClass)); } /** * Constructor. * * @param protocol * The connector protocol. * @param port * The listening port. */ public Server(Protocol protocol, int port) { this((Context) null, protocol, port, (Restlet) null); } /** * Constructor. * * @param protocol * The connector protocol. * @param port * The listening port. * @param nextClass * The next server resource. */ public Server(Protocol protocol, int port, Class nextClass) { this((Context) null, protocol, port, new Finder(Context.getCurrent(), nextClass)); } /** * Constructor. * * @param protocol * The connector protocol. * @param port * The listening port. * @param next * The next Restlet. */ public Server(Protocol protocol, int port, Restlet next) { this((Context) null, protocol, port, next); } /** * Constructor using the protocol's default port. * * @param protocol * The connector protocol. * @param next * The next Restlet. */ public Server(Protocol protocol, Restlet next) { this((Context) null, protocol, next); } /** * Constructor using the protocol's default port. * * @param protocol * The connector protocol. * @param address * The listening IP address (useful if multiple IP addresses * available). You can also use a domain name as an alias for the * IP address to listen to. */ public Server(Protocol protocol, String address) { this((Context) null, protocol, address, protocol.getDefaultPort(), null); } /** * Constructor using the protocol's default port. * * @param protocol * The connector protocol. * @param address * The listening IP address (useful if multiple IP addresses * available). You can also use a domain name as an alias for the * IP address to listen to. * @param nextClass * The next server resource. */ public Server(Protocol protocol, String address, Class nextClass) { this((Context) null, protocol, address, protocol.getDefaultPort(), new Finder(Context.getCurrent(), nextClass)); } /** * Constructor. * * @param protocol * The connector protocol. * @param address * The optional listening IP address (useful if multiple IP * addresses available). You can also use a domain name as an * alias for the IP address to listen to. * @param port * The listening port. */ public Server(Protocol protocol, String address, int port) { this((Context) null, protocol, address, port, null); } /** * Constructor. * * @param protocol * The connector protocol. * @param address * The optional listening IP address (useful if multiple IP * addresses available). You can also use a domain name as an * alias for the IP address to listen to. * @param port * The listening port. * @param next * The next Restlet. */ public Server(Protocol protocol, String address, int port, Restlet next) { this((Context) null, protocol, address, port, next); } /** * Constructor using the protocol's default port. * * @param protocol * The connector protocol. * @param address * The listening IP address (useful if multiple IP addresses * available). You can also use a domain name as an alias for the * IP address to listen to. * @param next * The next Restlet. */ public Server(Protocol protocol, String address, Restlet next) { this((Context) null, protocol, address, protocol.getDefaultPort(), next); } /** * Returns the optional listening IP address (local host used if null). * * @return The optional listening IP address (local host used if null). */ public String getAddress() { return this.address; } /** * Returns the actual ephemeral port used when the listening port is set to * '0'. The default value is '-1' if no ephemeral port is known. See * InetSocketAddress#InetSocketAddress(int) and ServerSocket#getLocalPort() * methods for details. * * @return The actual ephemeral port used. */ public int getEphemeralPort() { return (Integer) getHelper().getAttributes().get("ephemeralPort"); } /** * Returns the internal server. * * @return The internal server. */ private RestletHelper getHelper() { return this.helper; } /** * Returns the next Restlet. * * @return The next Restlet. */ public Restlet getNext() { return getTarget(); } /** * Returns the listening port if specified. * * @return The listening port if specified. */ public int getPort() { return this.port; } /** * Returns the next Restlet. * * @return The next Restlet. * @deprecated Use the {@link #getNext()} method instead. */ @Deprecated public Restlet getTarget() { return this.next; } @Override public void handle(Request request, Response response) { super.handle(request, response); if (getTarget() != null) { getTarget().handle(request, response); } } /** * Indicates if a next Restlet is set. * * @return True if a next Restlet is set. */ public boolean hasNext() { return this.next != null; } /** * Indicates if a next Restlet is set. * * @return True if a next Restlet is set. * @deprecated Use the {@link #hasNext()} method instead. */ @Deprecated public boolean hasTarget() { return hasNext(); } /** * Indicates the underlying connector helper is available. * * @return True if the underlying connector helper is available. */ @Override public boolean isAvailable() { return getHelper() != null; } /** * Sets the optional listening IP address (local host used if null). * * @param address * The optional listening IP address (local host used if null). */ public void setAddress(String address) { this.address = address; } /** * Sets the next Restlet as a Finder for a given resource class. When the * call is delegated to the Finder instance, a new instance of the resource * class will be created and will actually handle the request. * * @param nextClass * The next resource class to attach. */ public void setNext(Class nextClass) { setTarget(new Finder(getContext(), nextClass)); } /** * Sets the next Restlet. * * @param next * The next Restlet. */ public void setNext(Restlet next) { setTarget(next); } /** * Sets the listening port if specified. Note that '0' means that the system * will pick up an ephemeral port at the binding time. This ephemeral can be * retrieved once the server is started using the * {@link #getEphemeralPort()} method. * * @param port * The listening port if specified. */ protected void setPort(int port) { this.port = port; } /** * Sets the next Restlet. * * @param next * The next Restlet. * @deprecated Use the {@link #setNext(Restlet)} method instead. */ @Deprecated public void setTarget(Restlet next) { this.next = next; } @Override public synchronized void start() throws Exception { if (isStopped()) { super.start(); if (getHelper() != null) { getHelper().start(); } } } @Override public synchronized void stop() throws Exception { if (isStarted()) { if (getHelper() != null) { getHelper().stop(); } super.stop(); } } } restlet-2.0.14/org.restlet/src/org/restlet/Message.java0000664000175000017500000003366711757206346023525 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.CacheDirective; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.RecipientInfo; import org.restlet.data.Warning; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; /** * Generic message exchanged between components. * * @author Jerome Louvel */ public abstract class Message { /** The modifiable attributes map. */ private volatile Map attributes; /** The caching directives. */ private volatile List cacheDirectives; /** The date and time at which the message was originated. */ private volatile Date date; /** The payload of the message. */ private volatile Representation entity; /** The optional cached Form. */ private volatile Form entityForm; /** The optional cached text. */ private volatile String entityText; /** Callback invoked after sending the response. */ private volatile Uniform onSent; /** The intermediary recipients info. */ private volatile List recipientsInfo; /** The additional warnings information. */ private volatile List warnings; /** * Constructor. */ public Message() { this((Representation) null); } /** * Constructor. * * @param entity * The payload of the message. */ public Message(Representation entity) { this.attributes = null; this.cacheDirectives = null; this.date = null; this.entity = entity; this.entityForm = null; this.entityText = null; this.onSent = null; this.recipientsInfo = null; this.warnings = null; } /** * Returns the modifiable map of attributes that can be used by developers * to save information relative to the message. Creates a new instance if no * one has been set. This is an easier alternative to the creation of a * wrapper instance around the whole message.
    *
    * * In addition, this map is a shared space between the developer and the * connectors. In this case, it is used to exchange information that is not * uniform across all protocols and couldn't therefore be directly included * in the API. For this purpose, all attribute names starting with * "org.restlet" are reserved. Currently the following attributes are used: * * * * * * * * * * * * * * * * *
    Attribute nameClass nameDescription
    org.restlet.http.headersorg.restlet.data.FormServer HTTP connectors must provide all request headers and client * HTTP connectors must provide all response headers, exactly as they were * received. In addition, developers can also use this attribute to specify * non-standard headers that should be added to the request or to the * response.
    org.restlet.https.clientCertificatesListFor requests received via a secure connector, indicates the ordered * list of client certificates, if they are available and accessible.
    *
    * Most of the standard HTTP headers are directly supported via the Restlet * API. Thus, adding such HTTP headers is forbidden because it could * conflict with the connector's internal behavior, limit portability or * prevent future optimizations. The other standard HTTP headers (that are * not supported) can be added as attributes via the * "org.restlet.http.headers" key.
    * * @return The modifiable attributes map. */ public Map getAttributes() { // Lazy initialization with double-check. Map r = this.attributes; if (r == null) { synchronized (this) { r = this.attributes; if (r == null) { this.attributes = r = new ConcurrentHashMap(); } } } return this.attributes; } /** * Returns the cache directives.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Cache-Control" header. * * @return The cache directives. */ public List getCacheDirectives() { // Lazy initialization with double-check. List r = this.cacheDirectives; if (r == null) { synchronized (this) { r = this.cacheDirectives; if (r == null) { this.cacheDirectives = r = new CopyOnWriteArrayList(); } } } return r; } /** * Returns the date and time at which the message was originated. * * @return The date and time at which the message was originated. */ public Date getDate() { return date; } /** * Returns the entity representation. * * @return The entity representation. */ public Representation getEntity() { return this.entity; } /** * Returns the entity as a form. This method can be called several times and * will always return the same form instance. Note that if the entity is * large this method can result in important memory consumption. * * @return The entity as a form. * @deprecated Will be removed in future release 2.1. */ @Deprecated public Form getEntityAsForm() { if (this.entityForm == null) { this.entityForm = new Form(getEntity()); } return this.entityForm; } /** * Returns the entity as text. This method can be called several times and * will always return the same text. Note that if the entity is large this * method can result in important memory consumption. * * @return The entity as text. */ public String getEntityAsText() { if (this.entityText == null) { try { this.entityText = getEntity().getText(); } catch (java.io.IOException e) { Context.getCurrentLogger().log(java.util.logging.Level.FINE, "Unable to get the entity text.", e); } } return this.entityText; } /** * Returns the callback invoked after sending the message. * * @return The callback invoked after sending the message. */ public Uniform getOnSent() { return onSent; } /** * Returns the intermediary recipient information.
    *
    * Note that when used with HTTP connectors, this property maps to the "Via" * headers. * * @return The intermediary recipient information. */ public List getRecipientsInfo() { // Lazy initialization with double-check. List r = this.recipientsInfo; if (r == null) { synchronized (this) { r = this.recipientsInfo; if (r == null) { this.recipientsInfo = r = new CopyOnWriteArrayList(); } } } return r; } /** * Returns the additional warnings information.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Warning" headers. * * @return The additional warnings information. */ public List getWarnings() { // Lazy initialization with double-check. List r = this.warnings; if (r == null) { synchronized (this) { r = this.warnings; if (r == null) { this.warnings = r = new CopyOnWriteArrayList(); } } } return r; } /** * Indicates if the message was or will be exchanged confidentially, for * example via a SSL-secured connection. * * @return True if the message is confidential. */ public abstract boolean isConfidential(); /** * Indicates if a content is available and can be sent or received. Several * conditions must be met: the content must exists and have some available * data. * * @return True if a content is available and can be sent. */ public boolean isEntityAvailable() { // The declaration of the "result" variable is a workaround for the GWT // platform. Please keep it! boolean result = (getEntity() != null) && getEntity().isAvailable(); return result; } /** * Releases the message's entity if present. * * @see org.restlet.representation.Representation#release() */ public void release() { if (getEntity() != null) { getEntity().release(); } } /** * Sets the modifiable map of attributes. This method clears the current map * and puts all entries in the parameter map. * * @param attributes * A map of attributes */ public void setAttributes(Map attributes) { synchronized (getAttributes()) { if (attributes != getAttributes()) { getAttributes().clear(); if (attributes != null) { getAttributes().putAll(attributes); } } } } /** * Sets the cache directives. Note that when used with HTTP connectors, this * property maps to the "Cache-Control" header. This method clears the * current list and adds all entries in the parameter list. * * @param cacheDirectives * The cache directives. */ public void setCacheDirectives(List cacheDirectives) { synchronized (getCacheDirectives()) { if (cacheDirectives != getCacheDirectives()) { getCacheDirectives().clear(); if (cacheDirectives != null) { getCacheDirectives().addAll(cacheDirectives); } } } } /** * Sets the date and time at which the message was originated. * * @param date * The date and time at which the message was originated. */ public void setDate(Date date) { this.date = date; } /** * Sets the entity representation. * * @param entity * The entity representation. */ public void setEntity(Representation entity) { this.entity = entity; } /** * Sets a textual entity. * * @param value * The represented string. * @param mediaType * The representation's media type. */ public void setEntity(String value, MediaType mediaType) { setEntity(new StringRepresentation(value, mediaType)); } /** * Sets the callback invoked after sending the message. * * @param onSentCallback * The callback invoked after sending the message. */ public void setOnSent(Uniform onSentCallback) { this.onSent = onSentCallback; } /** * Sets the modifiable list of intermediary recipients. Note that when used * with HTTP connectors, this property maps to the "Via" headers. This * method clears the current list and adds all entries in the parameter * list. * * @param recipientsInfo * A list of intermediary recipients. */ public void setRecipientsInfo(List recipientsInfo) { synchronized (getRecipientsInfo()) { if (recipientsInfo != getRecipientsInfo()) { getRecipientsInfo().clear(); if (recipientsInfo != null) { getRecipientsInfo().addAll(recipientsInfo); } } } } /** * Sets the additional warnings information. Note that when used with HTTP * connectors, this property maps to the "Warning" headers. This method * clears the current list and adds all entries in the parameter list. * * @param warnings * The warnings. */ public void setWarnings(List warnings) { synchronized (getWarnings()) { if (warnings != getWarnings()) { getWarnings().clear(); if (warnings != null) { getWarnings().addAll(warnings); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/Context.java0000664000175000017500000002723011757206346023552 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Logger; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.engine.Engine; import org.restlet.util.Series; /** * Contextual data and services provided to a set of Restlets. The context is * the means by which a Restlet may access the software environment within the * framework. It is typically provided by the immediate parent Restlet * (Application is the most common case).
    *
    * Concurrency note: attributes and parameters of a context are stored in * concurrent collections that guarantee thread safe access and modification. If * several threads concurrently access objects and modify these collections, * they should synchronize on the lock of the Context instance. * * @author Jerome Louvel */ public class Context { private static final ThreadLocal CURRENT = new ThreadLocal(); /** * Returns the context associated to the current Restlet. The context can be * the one of a Component, an Application, a Filter or any other Restlet * subclass. * * Warning: this method should only be used under duress. You should by * default prefer obtaining the current context using methods such as * {@link org.restlet.Restlet#getContext()} or * {@link org.restlet.resource.Resource#getContext()}. * * This variable is stored internally as a thread local variable and updated * each time a request is handled by a Restlet via the * {@link Restlet#handle(org.restlet.Request, org.restlet.Response)} method. * * @return The current context. */ public static Context getCurrent() { return CURRENT.get(); } /** * Returns the current context's logger. * * @return The current context's logger. */ public static Logger getCurrentLogger() { return (Context.getCurrent() != null) ? Context.getCurrent() .getLogger() : Engine.getLogger("org.restlet"); } /** * Sets the context to associated with the current thread. * * @param context * The thread's context. */ public static void setCurrent(Context context) { CURRENT.set(context); } /** The client dispatcher. */ private volatile Client clientDispatcher; /** The server dispatcher. */ private volatile Client serverDispatcher; /** The modifiable attributes map. */ private final ConcurrentMap attributes; /** The logger instance to use. */ private volatile Logger logger; /** The modifiable series of parameters. */ private final Series parameters; /** * The enroler that can add the user roles based on Restlet default * authorization model. */ private volatile org.restlet.security.Enroler defaultEnroler; /** * The verifier that can check the validity of user/secret couples based on * Restlet default authorization model. */ private volatile org.restlet.security.Verifier defaultVerifier; /** * Constructor. Writes log messages to "org.restlet". */ public Context() { this("org.restlet"); } /** * Constructor. * * @param logger * The logger instance of use. */ public Context(Logger logger) { this.attributes = new ConcurrentHashMap(); this.logger = logger; this.parameters = new Form(new CopyOnWriteArrayList()); this.clientDispatcher = null; this.defaultEnroler = null; this.serverDispatcher = null; this.defaultVerifier = null; } /** * Constructor. * * @param loggerName * The name of the logger to use. */ public Context(String loggerName) { this(Engine.getLogger(loggerName)); } /** * Creates a protected child context. This is especially useful for new * application attached to their parent component, to ensure their isolation * from the other applications. By default it just creates a new context * instance. * * @return The child context. */ public Context createChildContext() { return new Context(); } /** * Returns a modifiable attributes map that can be used by developers to * save information relative to the context. This is a convenient means to * provide common objects to all the Restlets and Resources composing an * Application.
    *
    * * In addition, this map is a shared space between the developer and the * Restlet implementation. For this purpose, all attribute names starting * with "org.restlet" are reserved. Currently the following attributes are * used: * * * * * * * * * * * *
    Attribute nameClass nameDescription
    org.restlet.applicationorg.restlet.ApplicationThe parent application providing this context, if any.
    * * * @return The modifiable attributes map. */ public ConcurrentMap getAttributes() { return this.attributes; } /** * Returns a request dispatcher to available client connectors. When you ask * the dispatcher to handle a request, it will automatically select the * appropriate client connector for your request, based on the * request.protocol property or on the resource URI's scheme. This call is * blocking and will return an updated response object. * * @return A request dispatcher to available client connectors. */ public Client getClientDispatcher() { return this.clientDispatcher; } /** * Returns an enroler that can add the user roles based on authenticated * user principals. * * @return An enroler. */ public org.restlet.security.Enroler getDefaultEnroler() { return defaultEnroler; } /** * Returns a verifier that can check the validity of the credentials * associated to a request. * * @return A verifier. */ public org.restlet.security.Verifier getDefaultVerifier() { return this.defaultVerifier; } /** * Returns the logger. * * @return The logger. */ public Logger getLogger() { return this.logger; } /** * Returns the modifiable series of parameters. A parameter is a pair * composed of a name and a value and is typically used for configuration * purpose, like Java properties. Note that multiple parameters with the * same name can be declared and accessed. * * @return The modifiable series of parameters. */ public Series getParameters() { return this.parameters; } /** * Returns a request dispatcher to component's virtual hosts. This is useful * for application that want to optimize calls to other applications hosted * in the same component or to the application itself.
    *
    * The processing is the same as what would have been done if the request * came from one of the component's server connectors. It first must match * one of the registered virtual hosts. Then it can be routed to one of the * attached Restlets, typically an Application.
    *
    * Note that the RIAP pseudo protocol isn't supported by this dispatcher, * you should instead rely on the {@link #getClientDispatcher()} method. * * @return A request dispatcher to the server connectors' router. */ public Client getServerDispatcher() { return this.serverDispatcher; } /** * Sets the modifiable map of attributes. This method clears the current map * and puts all entries in the parameter map. * * @param attributes * A map of attributes. */ public void setAttributes(Map attributes) { synchronized (getAttributes()) { if (attributes != getAttributes()) { getAttributes().clear(); if (attributes != null) { getAttributes().putAll(attributes); } } } } /** * Sets the client dispatcher. * * @param clientDispatcher * The new client dispatcher. */ public void setClientDispatcher(Client clientDispatcher) { this.clientDispatcher = clientDispatcher; } /** * Sets an enroler that can add the user roles based on authenticated user * principals. * * @param enroler * An enroler. */ public void setDefaultEnroler(org.restlet.security.Enroler enroler) { this.defaultEnroler = enroler; } /** * Sets a local verifier that can check the validity of user/secret couples * based on Restlet default authorization model. * * @param verifier * A local verifier. */ public void setDefaultVerifier(org.restlet.security.Verifier verifier) { this.defaultVerifier = verifier; } /** * Sets the logger. * * @param logger * The logger. */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets the logger. * * @param loggerName * The name of the logger to use. */ public void setLogger(String loggerName) { setLogger(Engine.getLogger(loggerName)); } /** * Sets the modifiable series of parameters. This method clears the current * series and adds all entries in the parameter series. * * @param parameters * A series of parameters. */ public void setParameters(Series parameters) { synchronized (getParameters()) { if (parameters != getParameters()) { getParameters().clear(); if (parameters != null) { getParameters().addAll(parameters); } } } } /** * Sets the server dispatcher. * * @param serverDispatcher * The new server dispatcher. */ public void setServerDispatcher(Client serverDispatcher) { this.serverDispatcher = serverDispatcher; } } restlet-2.0.14/org.restlet/src/org/restlet/Restlet.java0000664000175000017500000002101111757206350023532 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.data.Status; import org.restlet.engine.Engine; /** * Uniform class that provides a context and life cycle support. It has many * subclasses that focus on specific ways to process calls. The context property * is typically provided by a parent Component as a way to encapsulate access to * shared features such as logging and client connectors.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public abstract class Restlet implements Uniform { /** Error message. */ private static final String UNABLE_TO_START = "Unable to start the Restlet"; /** The author(s). */ private volatile String author; /** The context. */ private volatile Context context; /** The description. */ private volatile String description; /** The display name. */ private volatile String name; /** The owner(s). */ private volatile String owner; /** Indicates if the Restlet was started. */ private volatile boolean started; /** * Constructor with null context. */ public Restlet() { this(null); } /** * Constructor with the Restlet's context which can be the parent's * application context, but shouldn't be the parent Component's context for * security reasons. * * @see Context#createChildContext() * * @param context * The context of the Restlet. * */ public Restlet(Context context) { this.context = context; this.started = false; this.name = toString(); this.description = null; this.author = null; this.owner = null; if (Engine.getInstance() == null) { Context .getCurrentLogger() .severe( "Unable to fully initialize the Restlet. No Restlet engine available."); throw new RuntimeException( "Unable to fully initialize the Restlet. No Restlet engine available."); } org.restlet.engine.component.ChildContext.fireContextChanged(this, context); } /** * Attempts to {@link #stop()} the Restlet if it is still started. */ @Override protected void finalize() throws Throwable { if (isStarted()) { stop(); } } /** * Returns the parent application if it exists, or null. * * @return The parent application if it exists, or null. */ public Application getApplication() { return Application.getCurrent(); } /** * Returns the author(s). * * @return The author(s). */ public String getAuthor() { return this.author; } /** * Returns the context. * * @return The context. */ public Context getContext() { return this.context; } /** * Returns the description. * * @return The description */ public String getDescription() { return this.description; } /** * Returns the context's logger. * * @return The context's logger. */ public Logger getLogger() { Logger result = null; Context context = getContext(); if (context == null) { context = Context.getCurrent(); } if (context != null) { result = context.getLogger(); } if (result == null) { result = Engine.getLogger(this, "org.restlet"); } return result; } /** * Returns the display name. * * @return The display name. */ public String getName() { return this.name; } /** * Returns the owner(s). * * @return The owner(s). */ public String getOwner() { return this.owner; } /** * Handles a call. The default behavior is to initialize the Restlet by * setting the current context using the {@link Context#setCurrent(Context)} * method and by attempting to start it, unless it was already started. If * an exception is thrown during the start action, then the response status * is set to {@link Status#SERVER_ERROR_INTERNAL}. *

    * Subclasses overriding this method should make sure that they call * super.handle(request, response) before adding their own logic. * * @param request * The request to handle. * @param response * The response to update. */ public void handle(Request request, Response response) { // Associate the response to the current thread Response.setCurrent(response); // Associate the context to the current thread if (getContext() != null) { Context.setCurrent(getContext()); } // Check if the Restlet was started if (isStopped()) { try { start(); } catch (Exception e) { // Occurred while starting the Restlet getContext().getLogger().log(Level.WARNING, UNABLE_TO_START, e); response.setStatus(Status.SERVER_ERROR_INTERNAL); } if (!isStarted()) { // No exception raised but the Restlet somehow couldn't be // started getContext().getLogger().log(Level.WARNING, UNABLE_TO_START); response.setStatus(Status.SERVER_ERROR_INTERNAL); } } } /** * Indicates if the Restlet is started. * * @return True if the Restlet is started. */ public boolean isStarted() { return this.started; } /** * Indicates if the Restlet is stopped. * * @return True if the Restlet is stopped. */ public boolean isStopped() { return !this.started; } /** * Sets the author(s). * * @param author * The author(s). */ public void setAuthor(String author) { this.author = author; } /** * Sets the context. * * @param context * The context. */ public void setContext(Context context) { this.context = context; org.restlet.engine.component.ChildContext.fireContextChanged(this, context); } /** * Sets the description. * * @param description * The description. */ public void setDescription(String description) { this.description = description; } /** * Sets the display name. * * @param name * The display name. */ public void setName(String name) { this.name = name; } /** * Sets the owner(s). * * @param owner * The owner(s). */ public void setOwner(String owner) { this.owner = owner; } /** Starts the Restlet. */ public synchronized void start() throws Exception { this.started = true; } /** Stops the Restlet. */ public synchronized void stop() throws Exception { this.started = false; } } restlet-2.0.14/org.restlet/src/org/restlet/Request.java0000664000175000017500000006464411757206346023570 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.CacheDirective; import org.restlet.data.ChallengeResponse; import org.restlet.data.CharacterSet; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Protocol; import org.restlet.data.Range; import org.restlet.data.Reference; import org.restlet.data.Tag; import org.restlet.data.Warning; import org.restlet.engine.util.CookieSeries; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Generic request sent by client connectors. It is then received by server * connectors and processed by Restlets. This request can also be processed by a * chain of Restlets, on both client and server sides. Requests are uniform * across all types of connectors, protocols and components. * * @see org.restlet.Response * @see org.restlet.Uniform * @author Jerome Louvel */ public class Request extends Message { /** * Returns the request associated to the current thread. This is reusing the * {@link Response#getCurrent()} method. * * Warning: this method should only be used under duress. You should by * default prefer obtaining the current context using methods such as * {@link org.restlet.resource.Resource#getRequest()}. * * @return The thread's request. */ public static Request getCurrent() { return (Response.getCurrent() == null) ? null : Response.getCurrent() .getRequest(); } /** The authentication response sent by a client to an origin server. */ private volatile ChallengeResponse challengeResponse; /** The client-specific information. */ private volatile ClientInfo clientInfo; /** The condition data. */ private volatile Conditions conditions; /** The cookies provided by the client. */ private volatile Series cookies; /** The host reference. */ private volatile Reference hostRef; /** The maximum number of intermediaries. */ private volatile int maxForwards; /** The method. */ private volatile Method method; /** Callback invoked on response reception. */ private volatile Uniform onResponse; /** The original reference. */ private volatile Reference originalRef; /** The protocol. */ private volatile Protocol protocol; /** The authentication response sent by a client to a proxy. */ private volatile ChallengeResponse proxyChallengeResponse; /** The ranges to return from the target resource's representation. */ private volatile List ranges; /** The referrer reference. */ private volatile Reference referrerRef; /** The resource reference. */ private volatile Reference resourceRef; /** The application root reference. */ private volatile Reference rootRef; /** * Constructor. */ public Request() { this((Method) null, (Reference) null, (Representation) null); } /** * Constructor. * * @param method * The call's method. * @param resourceRef * The resource reference. */ public Request(Method method, Reference resourceRef) { this(method, resourceRef, null); } /** * Constructor. * * @param method * The call's method. * @param resourceRef * The resource reference. * @param entity * The entity. */ public Request(Method method, Reference resourceRef, Representation entity) { super(entity); this.challengeResponse = null; this.clientInfo = null; this.conditions = null; this.cookies = null; this.hostRef = null; this.maxForwards = -1; this.method = method; this.originalRef = null; this.onResponse = null; this.proxyChallengeResponse = null; this.protocol = null; this.ranges = null; this.referrerRef = null; this.resourceRef = resourceRef; this.rootRef = null; } /** * Constructor. * * @param method * The call's method. * @param resourceUri * The resource URI. */ public Request(Method method, String resourceUri) { this(method, new Reference(resourceUri)); } /** * Constructor. * * @param method * The call's method. * @param resourceUri * The resource URI. * @param entity * The entity. */ public Request(Method method, String resourceUri, Representation entity) { this(method, new Reference(resourceUri), entity); } /** * Copy constructor. * * @param request * The request to copy. */ public Request(Request request) { this(request.getMethod(), new Reference(request.getResourceRef()), request.getEntity()); challengeResponse = request.getChallengeResponse(); // Copy client info ClientInfo rci = request.getClientInfo(); clientInfo = new ClientInfo(); for (Preference o : rci.getAcceptedCharacterSets()) { clientInfo.getAcceptedCharacterSets().add(o); } for (Preference o : rci.getAcceptedEncodings()) { clientInfo.getAcceptedEncodings().add(o); } for (Preference o : rci.getAcceptedLanguages()) { clientInfo.getAcceptedLanguages().add(o); } for (Preference o : rci.getAcceptedMediaTypes()) { clientInfo.getAcceptedMediaTypes().add(o); } clientInfo.setAddress(rci.getAddress()); clientInfo.setAgent(rci.getAgent()); for (String o : rci.getForwardedAddresses()) { clientInfo.getForwardedAddresses().add(o); } clientInfo.setFrom(rci.getFrom()); clientInfo.setPort(rci.getPort()); clientInfo.setAgentAttributes(rci.getAgentAttributes()); clientInfo.setAgentProducts(rci.getAgentProducts()); clientInfo.setAuthenticated(rci.isAuthenticated()); for (org.restlet.data.Expectation o : rci.getExpectations()) { clientInfo.getExpectations().add(o); } for (java.security.Principal o : rci.getPrincipals()) { clientInfo.getPrincipals().add(o); } for (org.restlet.security.Role o : rci.getRoles()) { clientInfo.getRoles().add(o); } clientInfo.setUser(rci.getUser()); // Copy conditions conditions = new Conditions(); for (Tag o : request.getConditions().getMatch()) { conditions.getMatch().add(o); } conditions.setModifiedSince(request.getConditions().getModifiedSince()); for (Tag o : request.getConditions().getNoneMatch()) { conditions.getNoneMatch().add(o); } conditions.setRangeDate(request.getConditions().getRangeDate()); conditions.setRangeTag(request.getConditions().getRangeTag()); conditions.setUnmodifiedSince(request.getConditions() .getUnmodifiedSince()); for (Cookie o : request.getCookies()) { getCookies().add(o); } this.hostRef = request.getHostRef(); this.maxForwards = request.getMaxForwards(); this.originalRef = (request.getOriginalRef() == null) ? null : new Reference(request.getOriginalRef()); this.onResponse = request.getOnResponse(); this.proxyChallengeResponse = request.getProxyChallengeResponse(); this.protocol = request.getProtocol(); for (Range o : request.getRanges()) { getRanges().add(o); } this.referrerRef = (request.getReferrerRef() == null) ? null : new Reference(request.getReferrerRef()); this.rootRef = (request.getRootRef() == null) ? null : request .getRootRef(); for (Entry e : request.getAttributes().entrySet()) { getAttributes().put(e.getKey(), e.getValue()); } for (CacheDirective o : request.getCacheDirectives()) { getCacheDirectives().add(o); } this.setOnSent(request.getOnSent()); for (Warning o : request.getWarnings()) { getWarnings().add(o); } this.setDate(request.getDate()); } /** * Ask the connector to attempt to abort the related network connection, for * example immediately closing the socket. * * @return True if the request was aborted. */ public boolean abort() { return false; } /** * Asks the server connector to immediately commit the given response * associated to this request, making it ready to be sent back to the * client. Note that all server connectors don't necessarily support this * feature. */ public void commit(Response response) { } /** * Returns the authentication response sent by a client to an origin server. * Note that when used with HTTP connectors, this property maps to the * "Authorization" header. * * @return The authentication response sent by a client to an origin server. */ public ChallengeResponse getChallengeResponse() { return this.challengeResponse; } /** * Returns the client-specific information. Creates a new instance if no one * has been set. * * @return The client-specific information. */ public ClientInfo getClientInfo() { // Lazy initialization with double-check. ClientInfo c = this.clientInfo; if (c == null) { synchronized (this) { c = this.clientInfo; if (c == null) { this.clientInfo = c = new ClientInfo(); } } } return c; } /** * Returns the modifiable conditions applying to this request. Creates a new * instance if no one has been set. * * @return The conditions applying to this call. */ public Conditions getConditions() { // Lazy initialization with double-check. Conditions c = this.conditions; if (c == null) { synchronized (this) { c = this.conditions; if (c == null) { this.conditions = c = new Conditions(); } } } return c; } /** * Returns the modifiable series of cookies provided by the client. Creates * a new instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Cookie" header. * * @return The cookies provided by the client. */ public Series getCookies() { // Lazy initialization with double-check. Series c = this.cookies; if (c == null) { synchronized (this) { c = this.cookies; if (c == null) { this.cookies = c = new CookieSeries(); } } } return c; } /** * Returns the host reference. This may be different from the resourceRef's * host, for example for URNs and other URIs that don't contain host * information.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Host" header. * * @return The host reference. */ public Reference getHostRef() { return this.hostRef; } /** * Returns the maximum number of intermediaries. * * @return The maximum number of intermediaries. */ public int getMaxForwards() { return maxForwards; } /** * Returns the method. * * @return The method. */ public Method getMethod() { return this.method; } /** * Returns the callback invoked on response reception. If the value is not * null, then the associated request will be executed asynchronously. * * @return The callback invoked on response reception. */ public Uniform getOnResponse() { return onResponse; } /** * Returns the original reference as requested by the client. Note that this * property is not used during request routing. See the * {@link #getResourceRef()} method for details. * * @return The original reference. * @see #getResourceRef() */ public Reference getOriginalRef() { return this.originalRef; } /** * Returns the protocol used or to be used, if known. * * @return The protocol used or to be used. */ public Protocol getProtocol() { Protocol result = this.protocol; if ((result == null) && (getResourceRef() != null)) { // Attempt to guess the protocol to use // from the target reference scheme result = getResourceRef().getSchemeProtocol(); // Fallback: look at base reference scheme if (result == null) { result = (getResourceRef().getBaseRef() != null) ? getResourceRef() .getBaseRef().getSchemeProtocol() : null; } } return result; } /** * Returns the authentication response sent by a client to a proxy. Note * that when used with HTTP connectors, this property maps to the * "Proxy-Authorization" header. * * @return The authentication response sent by a client to a proxy. */ public ChallengeResponse getProxyChallengeResponse() { return this.proxyChallengeResponse; } /** * Returns the ranges to return from the target resource's representation. * Note that when used with HTTP connectors, this property maps to the * "Range" header. * * @return The ranges to return. */ public List getRanges() { // Lazy initialization with double-check. List r = this.ranges; if (r == null) { synchronized (this) { r = this.ranges; if (r == null) { this.ranges = r = new CopyOnWriteArrayList(); } } } return r; } /** * Returns the referrer reference if available. Note that when used with * HTTP connectors, this property maps to the "Referer" header. * * @return The referrer reference. */ public Reference getReferrerRef() { return this.referrerRef; } /** * Returns the reference of the target resource. This reference is * especially important during routing, dispatching and resource finding. * During such processing, its base reference is constantly updated to * reflect the reference of the parent Restlet or resource and the remaining * part of the URI that must be routed or analyzed. * * If you need to get the URI reference originally requested by the client, * then you should use the {@link #getOriginalRef()} method instead. Also, * note that beside the update of its base property, the resource reference * can be modified during the request processing. * * For example, the {@link org.restlet.service.TunnelService} associated to * an application can extract some special extensions or query parameters * and replace them by semantically equivalent properties on the request * object. Therefore, the resource reference can become different from the * original reference. * * Finally, when sending out requests via a dispatcher such as * {@link Context#getClientDispatcher()} or * {@link Context#getServerDispatcher()}, if the reference contains URI * template variables, those variables are automatically resolved using the * request's attributes. * * @return The reference of the target resource. * @see #getOriginalRef() * @see #getHostRef() */ public Reference getResourceRef() { return this.resourceRef; } /** * Returns the application root reference. * * @return The application root reference. */ public Reference getRootRef() { return this.rootRef; } /** * Implemented based on the {@link Protocol#isConfidential()} method for the * request's protocol returned by {@link #getProtocol()}; */ @Override public boolean isConfidential() { return (getProtocol() == null) ? false : getProtocol().isConfidential(); } /** * Indicates if a content is available and can be sent. Several conditions * must be met: the method must allow the sending of content, the content * must exists and have some available data. * * @return True if a content is available and can be sent. */ @Override public boolean isEntityAvailable() { // The declaration of the "result" variable is a workaround for the GWT // platform. boolean result = (Method.GET.equals(getMethod()) || Method.HEAD.equals(getMethod()) || Method.DELETE .equals(getMethod())); if (result) { return false; } return super.isEntityAvailable(); } /** * Indicates if an associated response is expected. * * @return True if an associated response is expected. */ public boolean isExpectingResponse() { return (getMethod() == null) ? false : getMethod().isReplying(); } /** * Sets the authentication response sent by a client to an origin server. * Note that when used with HTTP connectors, this property maps to the * "Authorization" header. * * @param challengeResponse * The authentication response sent by a client to an origin * server. */ public void setChallengeResponse(ChallengeResponse challengeResponse) { this.challengeResponse = challengeResponse; } /** * Sets the client-specific information. * * @param clientInfo * The client-specific information. */ public void setClientInfo(ClientInfo clientInfo) { this.clientInfo = clientInfo; } /** * Sets the conditions applying to this request. * * @param conditions * The conditions applying to this request. */ public void setConditions(Conditions conditions) { this.conditions = conditions; } /** * Sets the modifiable series of cookies provided by the client. Note that * when used with HTTP connectors, this property maps to the "Cookie" * header. This method clears the current series and adds all entries in the * parameter series. * * @param cookies * A series of cookies provided by the client. */ public void setCookies(Series cookies) { synchronized (getCookies()) { if (cookies != getCookies()) { if (getCookies() != null) { getCookies().clear(); } if (cookies != null) { getCookies().addAll(cookies); } } } } /** * Sets the host reference. Note that when used with HTTP connectors, this * property maps to the "Host" header. * * @param hostRef * The host reference. */ public void setHostRef(Reference hostRef) { this.hostRef = hostRef; } /** * Sets the host reference using an URI string. Note that when used with * HTTP connectors, this property maps to the "Host" header. * * @param hostUri * The host URI. */ public void setHostRef(String hostUri) { setHostRef(new Reference(hostUri)); } /** * Sets the maximum number of intermediaries. * * @param maxForwards * The maximum number of intermediaries. */ public void setMaxForwards(int maxForwards) { this.maxForwards = maxForwards; } /** * Sets the method called. * * @param method * The method called. */ public void setMethod(Method method) { this.method = method; } /** * Sets the callback invoked on response reception. If the value is not * null, then the associated request will be executed asynchronously. * * @param onResponseCallback * The callback invoked on response reception. */ public void setOnResponse(Uniform onResponseCallback) { this.onResponse = onResponseCallback; } /** * Sets the original reference requested by the client. * * @param originalRef * The original reference. * @see #getOriginalRef() */ public void setOriginalRef(Reference originalRef) { this.originalRef = originalRef; } /** * Sets the protocol used or to be used. * * @param protocol * The protocol used or to be used. */ public void setProtocol(Protocol protocol) { this.protocol = protocol; } /** * Sets the authentication response sent by a client to a proxy. Note that * when used with HTTP connectors, this property maps to the * "Proxy-Authorization" header. * * @param challengeResponse * The authentication response sent by a client to a proxy. */ public void setProxyChallengeResponse(ChallengeResponse challengeResponse) { this.proxyChallengeResponse = challengeResponse; } /** * Sets the modifiable list of ranges to return from the target resource's * representation. Note that when used with HTTP connectors, this property * maps to the "Range" header. This method clears the current list and adds * all entries in the parameter list. * * @param ranges * A list of ranges. */ public void setRanges(List ranges) { synchronized (getRanges()) { if (ranges != getRanges()) { getRanges().clear(); if (ranges != null) { getRanges().addAll(ranges); } } } } /** * Sets the referrer reference if available. Note that when used with HTTP * connectors, this property maps to the "Referer" header. * * @param referrerRef * The referrer reference. */ public void setReferrerRef(Reference referrerRef) { this.referrerRef = referrerRef; // A referrer reference must not include a fragment. if ((this.referrerRef != null) && (this.referrerRef.getFragment() != null)) { this.referrerRef.setFragment(null); } } /** * Sets the referrer reference if available using an URI string. Note that * when used with HTTP connectors, this property maps to the "Referer" * header. * * @param referrerUri * The referrer URI. * @see #setReferrerRef(Reference) */ public void setReferrerRef(String referrerUri) { setReferrerRef(new Reference(referrerUri)); } /** * Sets the target resource reference. If the reference is relative, it will * be resolved as an absolute reference. Also, the context's base reference * will be reset. Finally, the reference will be normalized to ensure a * consistent handling of the call. * * @param resourceRef * The resource reference. * @see #getResourceRef() */ public void setResourceRef(Reference resourceRef) { this.resourceRef = resourceRef; } /** * Sets the target resource reference using an URI string. Note that the URI * can be either absolute or relative to the context's base reference. * * @param resourceUri * The resource URI. * @see #setResourceRef(Reference) */ public void setResourceRef(String resourceUri) { if (getResourceRef() != null) { // Allow usage of URIs relative to the current base reference setResourceRef(new Reference(getResourceRef().getBaseRef(), resourceUri)); } else { setResourceRef(new Reference(resourceUri)); } } /** * Sets the application root reference. * * @param rootRef * The application root reference. */ public void setRootRef(Reference rootRef) { this.rootRef = rootRef; } /** * Displays a synthesis of the request like an HTTP request line. * * @return A synthesis of the request like an HTTP request line. */ public String toString() { return ((getMethod() == null) ? "null" : getMethod().toString()) + " " + ((getResourceRef() == null) ? "null" : getResourceRef() .toString()) + " " + ((getProtocol() == null) ? "null" : (getProtocol().getName() + "/" + getProtocol().getVersion())); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/0000775000175000017500000000000011757206354022523 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/component/0000775000175000017500000000000011757206350024521 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/component/HostRoute.java0000664000175000017500000001652111757206346027332 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import java.util.logging.Level; import java.util.regex.Pattern; import org.restlet.Request; import org.restlet.Response; import org.restlet.routing.Route; import org.restlet.routing.Router; import org.restlet.routing.VirtualHost; /** * Route based on a target VirtualHost. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ @SuppressWarnings("deprecation") public class HostRoute extends Route { /** * Constructor. * * @param router * The parent router. * @param target * The target virtual host. */ public HostRoute(Router router, VirtualHost target) { super(router, "", target); } /** * Allows filtering before processing by the next Restlet. Set the base * reference. * * @param request * The request to handle. * @param response * The response to update. * @return The continuation status. */ @Override protected int beforeHandle(Request request, Response response) { if (request.getHostRef() == null) { request.getResourceRef().setBaseRef( request.getResourceRef().getHostIdentifier()); } else { request.getResourceRef().setBaseRef(request.getHostRef()); } if (getLogger().isLoggable(Level.FINE)) { getLogger().fine( "New base URI: " + request.getResourceRef().getBaseRef()); getLogger().fine( "New remaining part: " + request.getResourceRef().getRemainingPart()); } return CONTINUE; } /** * Returns the target virtual host. * * @return The target virtual host. */ public VirtualHost getVirtualHost() { return (VirtualHost) getNext(); } /** * Matches a formatted string against a regex pattern, in a case insensitive * manner. * * @param regex * The pattern to use. * @param formattedString * The formatted string to match. * @return True if the formatted string matched the pattern. */ private boolean matches(String regex, String formattedString) { return Pattern.compile(regex, Pattern.CASE_INSENSITIVE) .matcher(formattedString).matches(); } /** * Returns the score for a given call (between 0 and 1.0). * * @param request * The request to score. * @param response * The response to score. * @return The score for a given call (between 0 and 1.0). */ @Override public float score(Request request, Response response) { float result = 0F; // Prepare the value to be matched String hostDomain = ""; String hostPort = ""; String hostScheme = ""; if (request.getHostRef() != null) { hostDomain = request.getHostRef().getHostDomain(); if (hostDomain == null) { hostDomain = ""; } int basePortValue = request.getHostRef().getHostPort(); if (basePortValue == -1) { basePortValue = request.getHostRef().getSchemeProtocol() .getDefaultPort(); } hostPort = Integer.toString(basePortValue); hostScheme = request.getHostRef().getScheme(); if (hostScheme == null) { hostScheme = ""; } } if (request.getResourceRef() != null) { String resourceDomain = request.getResourceRef().getHostDomain(); if (resourceDomain == null) { resourceDomain = ""; } int resourcePortValue = request.getResourceRef().getHostPort(); if (resourcePortValue == -1) { resourcePortValue = request.getResourceRef() .getSchemeProtocol().getDefaultPort(); } String resourcePort = Integer.toString(resourcePortValue); String resourceScheme = request.getResourceRef().getScheme(); if (resourceScheme == null) { resourceScheme = ""; } String serverAddress = response.getServerInfo().getAddress(); if (serverAddress == null) { serverAddress = ""; } int serverPortValue = response.getServerInfo().getPort(); if (serverPortValue == -1) { serverPortValue = request.getProtocol().getDefaultPort(); } String serverPort = Integer.toString(response.getServerInfo() .getPort()); // Check if all the criteria match if (matches(getVirtualHost().getHostDomain(), hostDomain) && matches(getVirtualHost().getHostPort(), hostPort) && matches(getVirtualHost().getHostScheme(), hostScheme) && matches(getVirtualHost().getResourceDomain(), resourceDomain) && matches(getVirtualHost().getResourcePort(), resourcePort) && matches(getVirtualHost().getResourceScheme(), resourceScheme) && matches(getVirtualHost().getServerAddress(), serverAddress) && matches(getVirtualHost().getServerPort(), serverPort)) { result = 1F; } } // Log the result of the matching if (getLogger().isLoggable(Level.FINER)) { getLogger().finer( "Call score for the \"" + getVirtualHost().getName() + "\" host: " + result); } return result; } /** * Sets the next virtual host. * * @param next * The next virtual host. */ public void setNext(VirtualHost next) { super.setNext(next); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ChildClientDispatcher.java0000664000175000017500000001353411757206346031570 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.LocalReference; import org.restlet.data.Protocol; import org.restlet.engine.TemplateDispatcher; /** * Client dispatcher for a component child. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state as member variables. * * @author Jerome Louvel */ public class ChildClientDispatcher extends TemplateDispatcher { /** * Constructor. * * @param childContext * The child context. */ public ChildClientDispatcher(ChildContext childContext) { super(childContext); } /** * Transmits the call to the parent component except if the call is internal * as denoted by the {@link Protocol#RIAP} protocol and targets this child * application. * * * @param request * The request to handle. * @param response * The response to update. */ @Override public void doHandle(Request request, Response response) { super.doHandle(request, response); final Protocol protocol = request.getProtocol(); if (protocol.equals(Protocol.RIAP)) { // Let's dispatch it final LocalReference cr = new LocalReference(request .getResourceRef()); if (cr.getRiapAuthorityType() == LocalReference.RIAP_APPLICATION) { if ((getChildContext() != null) && (getChildContext().getChild() instanceof Application)) { Application application = (Application) getChildContext() .getChild(); request.getResourceRef().setBaseRef( request.getResourceRef().getHostIdentifier()); application.getInboundRoot().handle(request, response); } } else if (cr.getRiapAuthorityType() == LocalReference.RIAP_COMPONENT) { parentHandle(request, response); } else if (cr.getRiapAuthorityType() == LocalReference.RIAP_HOST) { parentHandle(request, response); } else { getLogger() .warning( "Unknown RIAP authority. Only \"component\", \"host\" and \"application\" are supported."); } } else { if ((getChildContext() != null) && (getChildContext().getChild() instanceof Application)) { Application application = (Application) getChildContext() .getChild(); if (!application.getConnectorService().getClientProtocols() .contains(protocol)) { getLogger() .fine( "The protocol used by this request is not declared in the application's connector service. " + "Please update the list of client connectors used by your application and restart it."); } } parentHandle(request, response); } } /** * Returns the child context. * * @return The child context. */ private ChildContext getChildContext() { return (ChildContext) getContext(); } /** * Asks to the parent component to handle the call. * * @param request * The request to handle. * @param response * The response to update. */ private void parentHandle(Request request, Response response) { if (getChildContext() != null) { if (getChildContext().getParentContext() != null) { if (getChildContext().getParentContext().getClientDispatcher() != null) { getChildContext().getParentContext().getClientDispatcher() .handle(request, response); } else { getLogger() .warning( "The parent context doesn't have a client dispatcher available. Unable to handle call."); } } else { getLogger() .warning( "Your Restlet doesn't have a parent context available."); } } else { getLogger().warning( "Your Restlet doesn't have a context available."); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ChildContext.java0000664000175000017500000001162411757206346027765 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import org.restlet.Component; import org.restlet.Context; import org.restlet.Restlet; /** * Context based on a parent component's context but dedicated to a child * Restlet, typically to an application. * * @author Jerome Louvel */ public class ChildContext extends Context { /** * Indicates that a Restlet's context has changed. * * @param restlet * The Restlet with a changed context. * @param context * The new context. */ public static void fireContextChanged(Restlet restlet, Context context) { if (context != null) { if (context instanceof ChildContext) { ChildContext childContext = (ChildContext) context; if (childContext.getChild() == null) { childContext.setChild(restlet); } } else if (!(restlet instanceof Component) && (context instanceof ComponentContext)) { context .getLogger() .severe( "For security reasons, don't pass the component context to child Restlets anymore. Use the Context#createChildContext() method instead." + restlet.getClass()); } } } /** * Return the best class name. If the class is anonymous, then it returns * the super class name. * * @param clazz * The class to name. * @return The class name. */ public static String getBestClassName(Class clazz) { String result = clazz.getSimpleName(); if ((result == null) || (result.equals(""))) { result = getBestClassName(clazz.getSuperclass()); } return result; } /** * Returns a non-null logger name. It is composed by the canonical class * name of the owner object suffixed by the owner's hash code. * * @param baseName * The base logger name to prepend, without a trailing dot. * @param owner * The context owner. * @return The logger name. */ public static String getLoggerName(String baseName, Object owner) { String result = baseName; if ((owner != null) && (owner.getClass().getSimpleName() != null)) { result += "." + getBestClassName(owner.getClass()); } return result; } /** The child delegate, typically an application. */ private volatile Restlet child; /** The parent context. */ private volatile Context parentContext; /** * Constructor. * * @param parentContext * The parent context. */ public ChildContext(Context parentContext) { this.child = null; this.parentContext = parentContext; setClientDispatcher(new ChildClientDispatcher(this)); setServerDispatcher((getParentContext() != null) ? getParentContext() .getServerDispatcher() : null); } @Override public Context createChildContext() { return new ChildContext(this); } /** * Returns the child. * * @return the child. */ public Restlet getChild() { return this.child; } /** * Returns the parent context. * * @return The parent context. */ protected Context getParentContext() { return this.parentContext; } /** * Sets the child. * * @param child * The child. */ public void setChild(Restlet child) { this.child = child; setLogger(getLoggerName(this.parentContext.getLogger().getName(), child)); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/InternalRouter.java0000664000175000017500000000763711757206350030356 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.resource.Finder; import org.restlet.routing.Router; import org.restlet.routing.Template; /** * Provides the behavior of the internal router of a Component. It overrides the * default behavior of a classic Router. * * @author Thierry Boileau */ public class InternalRouter extends Router { /** * Constructor. * * @param context */ public InternalRouter(Context context) { super(context); // Override Router's default modes setDefaultMatchingMode(Template.MODE_STARTS_WITH); setRoutingMode(Router.MODE_BEST_MATCH); } @SuppressWarnings("deprecation") @Override protected org.restlet.routing.Route createRoute(String uriPattern, Restlet target, int matchingMode) { org.restlet.routing.Route result = new org.restlet.routing.Route(this, uriPattern, target) { @Override protected int beforeHandle(Request request, Response response) { final int result = super.beforeHandle(request, response); // Set the request's root reference in order to help the // retrieval of the relative reference. request.setRootRef(request.getResourceRef().getBaseRef()); return result; } }; result.getTemplate().setMatchingMode(matchingMode); result.setMatchingQuery(getDefaultMatchingQuery()); return result; } @SuppressWarnings("deprecation") @Override public org.restlet.routing.Route attach(Restlet target) { if (target.getContext() == null) { target.setContext(getContext().createChildContext()); } return super.attach(target); } @Override @SuppressWarnings("deprecation") public org.restlet.routing.Route attach(String uriPattern, Restlet target) { if (target.getContext() == null) { target.setContext(getContext().createChildContext()); } return super.attach(uriPattern, target); } @Override @SuppressWarnings("deprecation") public org.restlet.routing.Route attachDefault(Restlet defaultTarget) { if (defaultTarget.getContext() == null) { defaultTarget.setContext(getContext().createChildContext()); } return super.attachDefault(defaultTarget); } @Override public Finder createFinder(Class targetClass) { Finder result = super.createFinder(targetClass); result.setContext(getContext().createChildContext()); return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ClientRoute.java0000664000175000017500000000667311757206346027642 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Protocol; import org.restlet.routing.Route; import org.restlet.routing.Router; /** * Router scorer based on a target client connector. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ @SuppressWarnings("deprecation") public class ClientRoute extends Route { /** * Constructor. * * @param router * The parent router. * @param target * The target client. */ public ClientRoute(Router router, Client target) { super(router, "", target); } /** * Returns the target client. * * @return The target client. */ public Client getClient() { return (Client) getNext(); } /** * Returns the score for a given call (between 0 and 1.0). * * @param request * The request to score. * @param response * The response to score. * @return The score for a given call (between 0 and 1.0). */ @Override public float score(Request request, Response response) { float result = 0F; // Add the protocol score final Protocol protocol = request.getProtocol(); if (protocol == null) { getLogger().warning( "Unable to determine the protocol to use for this call."); } else if (getClient().getProtocols().contains(protocol)) { result = 1.0F; } if (getLogger().isLoggable(Level.FINER)) { getLogger().finer( "Call score for the \"" + getClient().getProtocols().toString() + "\" client: " + result); } return result; } /** * Sets the next client. * * @param next * The next client. */ public void setNext(Client next) { super.setNext(next); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ComponentContext.java0000664000175000017500000000505511757206346030705 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import org.restlet.Context; /** * Context allowing access to the component's connectors. * * @author Jerome Louvel */ public class ComponentContext extends Context { /** The component helper. */ private volatile ComponentHelper componentHelper; /** * Constructor. * * @param componentHelper * The component helper. */ public ComponentContext(ComponentHelper componentHelper) { super(ChildContext.getLoggerName("org.restlet", componentHelper .getHelped())); this.componentHelper = componentHelper; setClientDispatcher(new ComponentClientDispatcher(this)); setServerDispatcher(new ComponentServerDispatcher(this)); } @Override public Context createChildContext() { return new ChildContext(getComponentHelper().getHelped().getContext()); } /** * Returns the component helper. * * @return The component helper. */ protected ComponentHelper getComponentHelper() { return this.componentHelper; } /** * Sets the component helper. * * @param componentHelper * The component helper. */ protected void setComponentHelper(ComponentHelper componentHelper) { this.componentHelper = componentHelper; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ComponentServerDispatcher.java0000664000175000017500000000527111757206350032531 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import org.restlet.Request; import org.restlet.Response; import org.restlet.engine.TemplateDispatcher; /** * Component server dispatcher. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state as member variables. * * @author Jerome Louvel */ public class ComponentServerDispatcher extends TemplateDispatcher { /** * Constructor. * * @param componentContext * The component context. */ public ComponentServerDispatcher(ComponentContext componentContext) { super(componentContext); } @Override protected void doHandle(Request request, Response response) { super.doHandle(request, response); // This causes the baseRef of the resource reference to be set // as if it had actually arrived from a server connector. request.getResourceRef().setBaseRef( request.getResourceRef().getHostIdentifier()); // Ask the server router to actually handle the call getComponentContext().getComponentHelper().getServerRouter().handle( request, response); } /** * Returns the component context. * * @return The component context. */ private ComponentContext getComponentContext() { return (ComponentContext) getContext(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/package.html0000664000175000017500000000012711757206350027002 0ustar jamespagejamespage Supports Restlet components.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ComponentClientDispatcher.java0000664000175000017500000001362211757206350032500 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import java.util.Iterator; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.LocalReference; import org.restlet.data.Protocol; import org.restlet.engine.TemplateDispatcher; import org.restlet.routing.VirtualHost; /** * Component client dispatcher. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state as member variables. * * @author Jerome Louvel */ public class ComponentClientDispatcher extends TemplateDispatcher { /** * Constructor. * * @param componentContext * The component context. */ public ComponentClientDispatcher(ComponentContext componentContext) { super(componentContext); } @Override protected void doHandle(Request request, Response response) { super.doHandle(request, response); Protocol protocol = request.getProtocol(); if (protocol.equals(Protocol.RIAP)) { // Let's dispatch it final LocalReference cr = new LocalReference(request .getResourceRef()); final Component component = getComponent(); if (component != null) { if (cr.getRiapAuthorityType() == LocalReference.RIAP_COMPONENT) { // This causes the baseRef of the resource reference to be // set as if it had actually arrived from a server // connector. request.getResourceRef().setBaseRef( request.getResourceRef().getHostIdentifier()); // Ask the private internal route to handle the call component.getInternalRouter().handle(request, response); } else if (cr.getRiapAuthorityType() == LocalReference.RIAP_HOST) { VirtualHost host = null; VirtualHost currentHost = null; final Integer hostHashCode = VirtualHost.getCurrent(); // Lookup the virtual host for (final Iterator hostIter = getComponent() .getHosts().iterator(); (host == null) && hostIter.hasNext();) { currentHost = hostIter.next(); if (currentHost.hashCode() == hostHashCode) { host = currentHost; } } if ((host == null) && (component.getDefaultHost() != null)) { if (component.getDefaultHost().hashCode() == hostHashCode) { host = component.getDefaultHost(); } } if (host != null) { // This causes the baseRef of the resource reference to // be set as if it had actually arrived from a server // connector. request.getResourceRef().setBaseRef( request.getResourceRef().getHostIdentifier()); // Ask the virtual host to handle the call host.handle(request, response); } else { getLogger() .warning( "No virtual host is available to route the RIAP Host request."); } } else { getLogger() .warning( "Unknown RIAP authority. Only \"component\" is supported."); } } else { getLogger().warning( "No component is available to route the RIAP request."); } } else { getComponentContext().getComponentHelper().getClientRouter() .handle(request, response); } } /** * Returns the parent component. * * @return The parent component. */ private Component getComponent() { Component result = null; if ((getComponentContext() != null) && (getComponentContext().getComponentHelper() != null)) { result = getComponentContext().getComponentHelper().getHelped(); } return result; } /** * Returns the component context. * * @return The component context. */ private ComponentContext getComponentContext() { return (ComponentContext) getContext(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ServerRouter.java0000664000175000017500000001117511757206350030040 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import java.util.logging.Level; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Status; import org.restlet.routing.Router; import org.restlet.routing.VirtualHost; /** * Router that collects calls from all server connectors and dispatches them to * the appropriate host routers. The host routers then dispatch them to the user * applications. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class ServerRouter extends Router { /** The parent component. */ private volatile Component component; /** * Constructor. * * @param component * The parent component. */ public ServerRouter(Component component) { super((component == null) ? null : component.getContext() .createChildContext()); this.component = component; setRoutingMode(MODE_FIRST_MATCH); } /** * Returns the parent component. * * @return The parent component. */ private Component getComponent() { return this.component; } @SuppressWarnings("deprecation") @Override protected void logRoute(org.restlet.routing.Route route) { if (getLogger().isLoggable(Level.FINE)) { if (route instanceof HostRoute) { VirtualHost vhost = ((HostRoute) route).getVirtualHost(); if (getComponent().getDefaultHost() == vhost) { getLogger().fine("The default host was selected."); } else { getLogger().fine( "This virtual host was selected: \"" + vhost.getHostScheme() + "\", \"" + vhost.getHostDomain() + "\", \"" + vhost.getHostPort() + "\""); } } else { super.logRoute(route); } } } /** Starts the Restlet. */ @SuppressWarnings("deprecation") @Override public synchronized void start() throws Exception { // Attach all virtual hosts for (VirtualHost host : getComponent().getHosts()) { getRoutes().add(new HostRoute(this, host)); } // Also attach the default host if it exists if (getComponent().getDefaultHost() != null) { getRoutes().add( new HostRoute(this, getComponent().getDefaultHost())); } // If no host matches, display and error page with a precise message final Restlet noHostMatched = new Restlet(getComponent().getContext() .createChildContext()) { @Override public void handle(Request request, Response response) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND, "No virtual host could handle the request"); } }; setDefaultRoute(new org.restlet.routing.Route(this, "", noHostMatched)); // Start the router super.start(); } @Override public synchronized void stop() throws Exception { getRoutes().clear(); super.stop(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ComponentHelper.java0000664000175000017500000002351511757206346030501 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import java.util.Iterator; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.ChainHelper; import org.restlet.routing.Filter; import org.restlet.routing.TemplateRoute; import org.restlet.routing.VirtualHost; import org.restlet.service.Service; /** * Component helper. * * @author Jerome Louvel */ public class ComponentHelper extends ChainHelper { /** The internal client router. */ private final ClientRouter clientRouter; /** The internal server router. */ private volatile ServerRouter serverRouter; /** * Constructor. * * @param component * The helper component. */ public ComponentHelper(Component component) { super(component); component.setContext(new ComponentContext(this)); this.clientRouter = new ClientRouter(getHelped()); this.serverRouter = new ServerRouter(getHelped()); } /** * Check the applications attached to a virtual host. * * @param host * The parent virtual host. * @return True if the check succeeded. * @throws Exception */ private boolean checkVirtualHost(VirtualHost host) throws Exception { boolean result = true; if (host != null) { for (TemplateRoute route : host.getRoutes()) { Restlet next = route.getNext(); if (next instanceof Application) { Application application = (Application) next; if (application.getConnectorService() != null) { if (application.getConnectorService() .getClientProtocols() != null) { for (Protocol clientProtocol : application .getConnectorService().getClientProtocols()) { boolean clientFound = false; // Try to find a client connector matching the // client protocol Client client; for (Iterator iter = getHelped() .getClients().iterator(); !clientFound && iter.hasNext();) { client = iter.next(); clientFound = client.getProtocols() .contains(clientProtocol); } if (!clientFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Client connector for protocol " + clientProtocol .getName() + " is missing."); result = false; } } } if (application.getConnectorService() .getServerProtocols() != null) { for (Protocol serverProtocol : application .getConnectorService().getServerProtocols()) { boolean serverFound = false; // Try to find a server connector matching the // server protocol Server server; for (Iterator iter = getHelped() .getServers().iterator(); !serverFound && iter.hasNext();) { server = iter.next(); serverFound = server.getProtocols() .contains(serverProtocol); } if (!serverFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Server connector for protocol " + serverProtocol .getName() + " is missing."); result = false; } } } } if (result && application.isStopped()) { application.start(); } } } } return result; } /** * Returns the internal client router. * * @return the internal client router. */ public ClientRouter getClientRouter() { return this.clientRouter; } /** * Returns the internal host router. * * @return the internal host router. */ public ServerRouter getServerRouter() { return this.serverRouter; } /** * Sets the internal server router. * * @param serverRouter * The internal host router. */ public void setServerRouter(ServerRouter serverRouter) { this.serverRouter = serverRouter; } @Override public synchronized void start() throws Exception { // Checking if all applications have proper connectors boolean success = checkVirtualHost(getHelped().getDefaultHost()); if (success) { for (VirtualHost host : getHelped().getHosts()) { success = success && checkVirtualHost(host); } } // Let's actually start the component if (!success) { getHelped().stop(); } else { // Attach the service inbound filters Filter inboundFilter = null; for (Service service : getHelped().getServices()) { if (service.isEnabled()) { inboundFilter = service.createInboundFilter(getContext() .createChildContext()); if (inboundFilter != null) { addFilter(inboundFilter); } } } // Re-attach the original filter's attached Restlet setNext(getServerRouter()); } } @Override public synchronized void stop() throws Exception { // Stop the server's router getServerRouter().stop(); // Stop all applications stopHostApplications(getHelped().getDefaultHost()); for (VirtualHost host : getHelped().getHosts()) { stopHostApplications(host); } } /** * Stop all applications attached to a virtual host * * @param host * @throws Exception */ private void stopHostApplications(VirtualHost host) throws Exception { for (TemplateRoute route : host.getRoutes()) { if (route.getNext().isStarted()) { route.getNext().stop(); } } } /** * Set the new server router that will compute the new routes when the first * request will be received (automatic start). */ @Override public void update() throws Exception { // Note the old router to be able to stop it at the end ServerRouter oldRouter = getServerRouter(); // Set the new server router that will compute the new routes when the // first request will be received (automatic start). setServerRouter(new ServerRouter(getHelped())); // Replace the old server router setNext(getServerRouter()); // Stop the old server router if (oldRouter != null) { oldRouter.stop(); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ComponentXmlParser.java0000664000175000017500000011177311757206350031176 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ 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.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 */ 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", "deprecation" }) private org.restlet.routing.Route attach(Router router, String targetClassName, String uriPattern, boolean defaultRoute) { org.restlet.routing.Route 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 (org.restlet.resource.Resource.class .isAssignableFrom(targetClass)) { final Class resourceClass = (Class) targetClass; if ((uriPattern != null) && !defaultRoute) { route = router.attach(uriPattern, resourceClass); } else { route = router.attachDefault(resourceClass); } } else 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. */ @SuppressWarnings("deprecation") private org.restlet.routing.Route attachWithDescriptor(Router router, String targetDescriptor, String uriPattern, boolean defaultRoute) { org.restlet.routing.Route 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().setLogFormat( 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. */ @SuppressWarnings("deprecation") private void setAttach(Router router, Node node) { final NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final 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"); final boolean bDefault = getBoolean(item, false) || "attachDefault".equals(childNode.getNodeName()); // Attaches a new route. // save the old router context so new routes do not inherit it final Context oldContext = router.getContext(); router.setContext(new Context()); org.restlet.routing.Route 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) { final 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); } } } } // Restore the router's old context router.setContext(oldContext); } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/component/ClientRouter.java0000664000175000017500000000724411757206346030017 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.component; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.routing.Router; /** * Router that collects calls from all applications and dispatches them to the * appropriate client connectors. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class ClientRouter extends Router { /** The parent component. */ private volatile Component component; /** * Constructor. * * @param component * The parent component. */ public ClientRouter(Component component) { super((component == null) ? null : component.getContext() .createChildContext()); this.component = component; } @SuppressWarnings("deprecation") @Override protected void logRoute(org.restlet.routing.Route route) { if (getLogger().isLoggable(Level.FINE)) { if (route instanceof ClientRoute) { Client client = ((ClientRoute) route).getClient(); getLogger().fine( "This client was selected: \"" + client.getProtocols() + "\""); } else { super.logRoute(route); } } } @Override public Restlet getNext(Request request, Response response) { Restlet result = super.getNext(request, response); if (result == null) { getLogger() .warning( "The protocol used by this request is not declared in the list of client connectors. (" + request.getResourceRef() .getSchemeProtocol() + ")"); } return result; } /** * Returns the parent component. * * @return The parent component. */ private Component getComponent() { return this.component; } /** Starts the Restlet. */ @Override public synchronized void start() throws Exception { for (final Client client : getComponent().getClients()) { getRoutes().add(new ClientRoute(this, client)); } super.start(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/0000775000175000017500000000000011757206350023476 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/http/ClientCall.java0000664000175000017500000003112511757206346026362 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.engine.ConnectorHelper; import org.restlet.engine.http.header.DispositionReader; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Low-level HTTP client call. * * @author Jerome Louvel */ public abstract class ClientCall extends Call { /** * Returns the local IP address or 127.0.0.1 if the resolution fails. * * @return The local IP address or 127.0.0.1 if the resolution fails. */ public static String getLocalAddress() { try { return java.net.InetAddress.getLocalHost().getHostAddress(); } catch (java.net.UnknownHostException e) { return "127.0.0.1"; } } /** * Parse the Content-Disposition header value * * @param value * Content-disposition header * @return Filename * @deprecated Use {@link DispositionReader} instead. */ @Deprecated public static String parseContentDisposition(String value) { if (value != null) { String key = "FILENAME=\""; int index = value.toUpperCase().indexOf(key); if (index > 0) { return value .substring(index + key.length(), value.length() - 1); } key = "FILENAME="; index = value.toUpperCase().indexOf(key); if (index > 0) { return value.substring(index + key.length(), value.length()); } } return null; } /** The parent HTTP client helper. */ private volatile HttpClientHelper helper; /** * Constructor setting the request address to the local host. * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. */ public ClientCall(HttpClientHelper helper, String method, String requestUri) { this.helper = helper; setMethod(method); setRequestUri(requestUri); setClientAddress(getLocalAddress()); } /** * Returns the content length of the request entity if know, * {@link Representation#UNKNOWN_SIZE} otherwise. * * @return The request content length. */ protected long getContentLength() { return HeaderUtils.getContentLength(getResponseHeaders()); } /** * Returns the HTTP client helper. * * @return The HTTP client helper. */ public HttpClientHelper getHelper() { return this.helper; } /** * Returns the request entity channel if it exists. * * @return The request entity channel if it exists. */ public abstract java.nio.channels.WritableByteChannel getRequestEntityChannel(); /** * Returns the request entity stream if it exists. * * @return The request entity stream if it exists. */ public abstract OutputStream getRequestEntityStream(); /** * Returns the request head stream if it exists. * * @return The request head stream if it exists. */ public abstract OutputStream getRequestHeadStream(); /** * Returns the response entity if available. Note that no metadata is * associated by default, you have to manually set them from your headers. * * @param response * the Response to get the entity from * @return The response entity if available. */ public Representation getResponseEntity(Response response) { Representation result = null; // boolean available = false; long size = Representation.UNKNOWN_SIZE; // Compute the content length Series responseHeaders = getResponseHeaders(); String transferEncoding = responseHeaders.getFirstValue( HeaderConstants.HEADER_TRANSFER_ENCODING, true); if ((transferEncoding != null) && !"identity".equalsIgnoreCase(transferEncoding)) { size = Representation.UNKNOWN_SIZE; } else { size = getContentLength(); } if (!getMethod().equals(Method.HEAD.getName()) && !response.getStatus().isInformational() && !response.getStatus() .equals(Status.REDIRECTION_NOT_MODIFIED) && !response.getStatus().equals(Status.SUCCESS_NO_CONTENT) && !response.getStatus().equals(Status.SUCCESS_RESET_CONTENT)) { // Make sure that an InputRepresentation will not be instantiated // while the stream is closed. InputStream stream = getUnClosedResponseEntityStream(getResponseEntityStream(size)); java.nio.channels.ReadableByteChannel channel = getResponseEntityChannel(size); if (stream != null) { result = getRepresentation(stream); } else if (channel != null) { result = getRepresentation(channel); // } else { // result = new EmptyRepresentation(); } } result = HeaderUtils.extractEntityHeaders(responseHeaders, result); if (result != null) { result.setSize(size); // Informs that the size has not been specified in the header. if (size == Representation.UNKNOWN_SIZE) { getLogger() .fine("The length of the message body is unknown. The entity must be handled carefully and consumed entirely in order to surely release the connection."); } } // } return result; } /** * Returns the response channel if it exists. * * @param size * The expected entity size or -1 if unknown. * @return The response channel if it exists. */ public abstract java.nio.channels.ReadableByteChannel getResponseEntityChannel( long size); /** * Returns the response entity stream if it exists. * * @param size * The expected entity size or -1 if unknown. * @return The response entity stream if it exists. */ public abstract InputStream getResponseEntityStream(long size); /** * Checks if the given input stream really contains bytes to be read. If so, * returns the inputStream otherwise returns null. * * @param inputStream * the inputStream to check. * @return null if the given inputStream does not contain any byte, an * inputStream otherwise. */ private InputStream getUnClosedResponseEntityStream(InputStream inputStream) { InputStream result = null; if (inputStream != null) { try { if (inputStream.available() > 0) { result = inputStream; } else { java.io.PushbackInputStream is = new java.io.PushbackInputStream( inputStream); int i = is.read(); if (i >= 0) { is.unread(i); result = is; } } } catch (IOException ioe) { getLogger().log(Level.FINER, "End of response entity stream.", ioe); } } return result; } @Override protected boolean isClientKeepAlive() { return true; } @Override protected boolean isServerKeepAlive() { return !HeaderUtils.isConnectionClose(getResponseHeaders()); } /** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * * @param request * The high-level request. * @return the status of the communication */ public Status sendRequest(Request request) { Status result = null; Representation entity = request.isEntityAvailable() ? request .getEntity() : null; // Get the connector service to callback org.restlet.service.ConnectorService connectorService = ConnectorHelper .getConnectorService(); if (connectorService != null) { connectorService.beforeSend(entity); } try { if (entity != null) { // In order to workaround bug #6472250 // (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6472250), // it is very important to reuse that exact same "requestStream" // reference when manipulating the request stream, otherwise // "insufficient data sent" exceptions will occur in // "fixedLengthMode" OutputStream requestStream = getRequestEntityStream(); java.nio.channels.WritableByteChannel requestChannel = getRequestEntityChannel(); if (requestChannel != null) { entity.write(requestChannel); requestChannel.close(); } else if (requestStream != null) { entity.write(requestStream); requestStream.flush(); requestStream.close(); } } // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); } catch (IOException ioe) { getHelper() .getLogger() .log(Level.FINE, "An error occured during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); } finally { if (entity != null) { entity.release(); } // Call-back after writing if (connectorService != null) { connectorService.afterSend(entity); } } return result; } /** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * * @param request * The high-level request. * @param response * The high-level response. * @param callback * The callback invoked upon request completion. */ public void sendRequest(Request request, Response response, org.restlet.Uniform callback) throws Exception { Context.getCurrentLogger().warning( "Currently callbacks are not available for this connector."); } /** * Indicates if the request entity should be chunked. * * @return True if the request should be chunked */ protected boolean shouldRequestBeChunked(Request request) { return request.isEntityAvailable() && (request.getEntity() != null) && (request.getEntity().getSize() == Representation.UNKNOWN_SIZE); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java0000664000175000017500000000763311757206346027575 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.engine.ClientHelper; import org.restlet.engine.http.adapter.ClientAdapter; /** * Base HTTP client connector. Here is the list of parameters that are * supported. They should be set in the Client's context before it is started: * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    adapterStringorg.restlet.engine.http.ClientAdapterClass name of the adapter of low-level HTTP calls into high level * requests and responses.
    * * @author Jerome Louvel */ public abstract class HttpClientHelper extends ClientHelper { /** The adapter from uniform calls to HTTP calls. */ private volatile ClientAdapter adapter; /** * Constructor. * * @param client * The client to help. */ public HttpClientHelper(Client client) { super(client); this.adapter = null; } /** * Creates a low-level HTTP client call from a high-level request. * * @param request * The high-level request. * @return A low-level HTTP client call. */ public abstract ClientCall create(Request request); /** * Returns the adapter from uniform calls to HTTP calls. * * @return the adapter from uniform calls to HTTP calls. */ public ClientAdapter getAdapter() throws Exception { if (this.adapter == null) { String adapterClass = getHelpedParameters().getFirstValue( "adapter", "org.restlet.engine.http.adapter.ClientAdapter"); this.adapter = (ClientAdapter) Class.forName(adapterClass) .getConstructor(Context.class).newInstance(getContext()); } return this.adapter; } @Override public void handle(Request request, Response response) { try { ClientCall clientCall = getAdapter().toSpecific(this, request); getAdapter().commit(clientCall, request, response); } catch (Exception e) { getLogger().log(Level.INFO, "Error while handling an HTTP client call", e); response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, e); } } /** * Sets the adapter from uniform calls to HTTP calls. * * @param adapter * The adapter to set. */ public void setAdapter(ClientAdapter adapter) { this.adapter = adapter; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/HttpResponse.java0000664000175000017500000000732611757206350027007 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Parameter; import org.restlet.data.ServerInfo; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.util.Series; /** * Response wrapper for server HTTP calls. * * @author Jerome Louvel */ public class HttpResponse extends Response { /** * Adds a new header to the given request. * * @param response * The response to update. * @param headerName * The header name to add. * @param headerValue * The header value to add. */ public static void addHeader(Response response, String headerName, String headerValue) { if (response instanceof HttpResponse) { ((HttpResponse) response).getHeaders().add(headerName, headerValue); } } /** The low-level HTTP call. */ private volatile ServerCall httpCall; /** Indicates if the server data was parsed and added. */ private volatile boolean serverAdded; /** * Constructor. * * @param httpCall * The low-level HTTP server call. * @param request * The associated high-level request. */ public HttpResponse(ServerCall httpCall, Request request) { super(request); this.serverAdded = false; this.httpCall = httpCall; // Set the properties setStatus(Status.SUCCESS_OK); } /** * Returns the HTTP headers. * * @return The HTTP headers. */ @SuppressWarnings("unchecked") public Series getHeaders() { return (Series) getAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); } /** * Returns the low-level HTTP call. * * @return The low-level HTTP call. */ public ServerCall getHttpCall() { return this.httpCall; } /** * Returns the server-specific information. * * @return The server-specific information. */ @Override public ServerInfo getServerInfo() { final ServerInfo result = super.getServerInfo(); if (!this.serverAdded) { result.setAddress(this.httpCall.getServerAddress()); result.setAgent(Engine.VERSION_HEADER); result.setPort(this.httpCall.getServerPort()); this.serverAdded = true; } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/Call.java0000664000175000017500000003245711757206346025234 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import java.io.IOException; import java.io.InputStream; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Low-level call for the HTTP connectors. * * @author Jerome Louvel */ public abstract class Call { /** * Returns true if the given exception is caused by a broken connection. * * @param exception * The exception to inspect. * @return True if the given exception is caused by a broken connection. */ public static boolean isBroken(Throwable exception) { boolean result = false; if (exception.getMessage() != null) { result = (exception.getMessage().indexOf("Broken pipe") != -1) || (exception .getMessage() .equals( "An existing connection must have been closed by the remote party.") || (exception .getMessage() .equals("An open connection has been abandonned by your network stack."))); } return result; } /** The client IP address. */ private volatile String clientAddress; /** The client port. */ private volatile int clientPort; /** Indicates if the call is confidential. */ private volatile boolean confidential; /** The hostRef domain. */ private volatile String hostDomain; /** The hostRef port. */ private volatile int hostPort; /** The method. */ private volatile String method; /** The exact protocol. */ private volatile Protocol protocol; /** The reason phrase. */ private volatile String reasonPhrase; /** The request headers. */ private final Series requestHeaders; /** The request URI. */ private volatile String requestUri; /** The response headers. */ private final Series responseHeaders; /** The server IP address. */ private volatile String serverAddress; /** The server port. */ private volatile int serverPort; /** The status code. */ private volatile int statusCode; /** The user principal. */ private volatile java.security.Principal userPrincipal; /** The protocol version. */ private volatile String version; /** * Constructor. */ public Call() { this.hostDomain = null; this.hostPort = -1; this.clientAddress = null; this.clientPort = -1; this.confidential = false; this.method = null; this.protocol = null; this.reasonPhrase = ""; this.requestHeaders = new Form(); this.requestUri = null; this.responseHeaders = new Form(); this.serverAddress = null; this.serverPort = -1; this.statusCode = 200; this.userPrincipal = null; this.version = null; } /** * Returns the client address.
    * Corresponds to the IP address of the requesting client. * * @return The client address. */ public String getClientAddress() { return this.clientAddress; } /** * Returns the client port.
    * Corresponds to the TCP/IP port of the requesting client. * * @return The client port. */ public int getClientPort() { return this.clientPort; } /** * Returns the host domain. * * @return The host domain. */ public String getHostDomain() { return this.hostDomain; } /** * Returns the host port. * * @return The host port. */ public int getHostPort() { return this.hostPort; } /** * Returns the logger. * * @return The logger. */ public Logger getLogger() { return Context.getCurrentLogger(); } /** * Returns the request method. * * @return The request method. */ public String getMethod() { return this.method; } /** * Returns the exact protocol (HTTP or HTTPS). * * @return The exact protocol (HTTP or HTTPS). */ public Protocol getProtocol() { if (this.protocol == null) { this.protocol = isConfidential() ? Protocol.HTTPS : Protocol.HTTP; } return this.protocol; } /** * Returns the reason phrase. * * @return The reason phrase. */ public String getReasonPhrase() { return this.reasonPhrase; } /** * Returns the representation wrapping the given stream. * * @param stream * The response input stream. * @return The wrapping representation. */ protected Representation getRepresentation(InputStream stream) { return new InputRepresentation(stream, null); } /** * Returns the representation wrapping the given channel. * * @param channel * The response channel. * @return The wrapping representation. */ protected Representation getRepresentation( java.nio.channels.ReadableByteChannel channel) { return new org.restlet.representation.ReadableRepresentation(channel, null); } /** * Returns the modifiable list of request headers. * * @return The modifiable list of request headers. */ public Series getRequestHeaders() { return this.requestHeaders; } /** * Returns the URI on the request line (most like a relative reference, but * not necessarily). * * @return The URI on the request line. */ public String getRequestUri() { return this.requestUri; } /** * Returns the modifiable list of server headers. * * @return The modifiable list of server headers. */ public Series getResponseHeaders() { return this.responseHeaders; } /** * Returns the response address.
    * Corresponds to the IP address of the responding server. * * @return The response address. */ public String getServerAddress() { return this.serverAddress; } /** * Returns the server port. * * @return The server port. */ public int getServerPort() { return this.serverPort; } /** * Returns the status code. * * @return The status code. * @throws IOException */ public int getStatusCode() throws IOException { return this.statusCode; } /** * Returns the user principal. * * @return The user principal. */ public java.security.Principal getUserPrincipal() { return this.userPrincipal; } /** * Returns the protocol version used. * * @return The protocol version used. */ public String getVersion() { return this.version; } /** * Indicates if the client wants a persistent connection. * * @return True if the client wants a persistent connection. */ protected abstract boolean isClientKeepAlive(); /** * Indicates if the confidentiality of the call is ensured (ex: via SSL). * * @return True if the confidentiality of the call is ensured (ex: via SSL). */ public boolean isConfidential() { return this.confidential; } /** * Returns true if the given exception is caused by a broken connection. * * @param exception * The exception to inspect. * @return True if the given exception is caused by a broken connection. */ public boolean isConnectionBroken(Throwable exception) { return isBroken(exception); } /** * Indicates if both the client and the server want a persistent connection. * * @return True if the connection should be kept alive after the call * processing. */ protected boolean isKeepAlive() { return isClientKeepAlive() && isServerKeepAlive(); } /** * Indicates if the request entity is chunked. * * @return True if the request entity is chunked. */ protected boolean isRequestChunked() { return HeaderUtils.isChunkedEncoding(getRequestHeaders()); } /** * Indicates if the response entity is chunked. * * @return True if the response entity is chunked. */ protected boolean isResponseChunked() { return HeaderUtils.isChunkedEncoding(getResponseHeaders()); } /** * Indicates if the server wants a persistent connection. * * @return True if the server wants a persistent connection. */ protected abstract boolean isServerKeepAlive(); /** * Sets the client address. * * @param clientAddress * The client address. */ protected void setClientAddress(String clientAddress) { this.clientAddress = clientAddress; } /** * Sets the client port. * * @param clientPort * The client port. */ protected void setClientPort(int clientPort) { this.clientPort = clientPort; } /** * Indicates if the confidentiality of the call is ensured (ex: via SSL). * * @param confidential * True if the confidentiality of the call is ensured (ex: via * SSL). */ protected void setConfidential(boolean confidential) { this.confidential = confidential; } /** * Sets the host domain name. * * @param hostDomain * The baseRef domain name. */ public void setHostDomain(String hostDomain) { this.hostDomain = hostDomain; } /** * Sets the host port. * * @param hostPort * The host port. */ public void setHostPort(int hostPort) { this.hostPort = hostPort; } /** * Sets the request method. * * @param method * The request method. */ protected void setMethod(String method) { this.method = method; } /** * Sets the exact protocol used (HTTP or HTTPS). * * @param protocol * The protocol. */ public void setProtocol(Protocol protocol) { this.protocol = protocol; } /** * Sets the reason phrase. * * @param reasonPhrase * The reason phrase. */ public void setReasonPhrase(String reasonPhrase) { this.reasonPhrase = reasonPhrase; } /** * Sets the full request URI. * * @param requestUri * The full request URI. */ protected void setRequestUri(String requestUri) { if ((requestUri == null) || (requestUri.equals(""))) { requestUri = "/"; } this.requestUri = requestUri; } /** * Sets the response address.
    * Corresponds to the IP address of the responding server. * * @param responseAddress * The response address. */ public void setServerAddress(String responseAddress) { this.serverAddress = responseAddress; } /** * Sets the server port. * * @param serverPort * The server port. */ public void setServerPort(int serverPort) { this.serverPort = serverPort; } /** * Sets the status code. * * @param code * The status code. */ public void setStatusCode(int code) { this.statusCode = code; } /** * Sets the user principal. * * @param principal * The user principal. */ public void setUserPrincipal(java.security.Principal principal) { this.userPrincipal = principal; } /** * Sets the protocol version used. * * @param version * The protocol version used. */ public void setVersion(String version) { this.version = version; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/HttpRequest.java0000664000175000017500000005220211757206350026632 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.CacheDirective; import org.restlet.data.ChallengeResponse; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Range; import org.restlet.data.RecipientInfo; import org.restlet.data.Reference; import org.restlet.data.Tag; import org.restlet.data.Warning; import org.restlet.engine.http.header.CacheDirectiveReader; import org.restlet.engine.http.header.CookieReader; import org.restlet.engine.http.header.ExpectationReader; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.http.header.PreferenceReader; import org.restlet.engine.http.header.RangeReader; import org.restlet.engine.http.header.RecipientInfoReader; import org.restlet.engine.http.header.WarningReader; import org.restlet.engine.security.AuthenticatorUtils; import org.restlet.engine.util.DateUtils; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Request wrapper for server HTTP calls. * * @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. */ public static void addHeader(Request request, String headerName, String headerValue) { if (request instanceof HttpRequest) { ((HttpRequest) request).getHeaders().add(headerName, headerValue); } } /** Indicates if the cache control data was parsed and added. */ private volatile boolean cacheDirectivesAdded; /** Indicates if the client data was parsed and added. */ private volatile boolean clientAdded; /** Indicates if the conditions were parsed and added. */ private volatile boolean conditionAdded; /** The context of the HTTP server connector that issued the call. */ private volatile Context context; /** Indicates if the cookies were parsed and added. */ private volatile boolean cookiesAdded; /** Indicates if the request entity was added. */ private volatile boolean entityAdded; /** The low-level HTTP call. */ private volatile ServerCall httpCall; /** Indicates if the proxy security data was parsed and added. */ private volatile boolean proxySecurityAdded; /** Indicates if the ranges data was parsed and added. */ private volatile boolean rangesAdded; /** Indicates if the referrer was parsed and added. */ private volatile boolean referrerAdded; /** Indicates if the security data was parsed and added. */ private volatile boolean securityAdded; /** Indicates if the warning data was parsed and added. */ private volatile boolean warningsAdded; /** Indicates if the recipients info was parsed and added. */ private volatile boolean recipientsInfoAdded; /** * Constructor. * * @param context * The context of the HTTP server connector that issued the call. * @param httpCall * The low-level HTTP server call. */ public HttpRequest(Context context, ServerCall httpCall) { this.context = context; this.clientAdded = false; this.conditionAdded = false; this.cookiesAdded = false; this.entityAdded = false; this.referrerAdded = false; this.securityAdded = false; this.proxySecurityAdded = false; this.recipientsInfoAdded = false; this.warningsAdded = false; this.httpCall = httpCall; // Set the properties setMethod(Method.valueOf(httpCall.getMethod())); // Set the host reference StringBuilder sb = new StringBuilder(); sb.append(httpCall.getProtocol().getSchemeName()).append("://"); sb.append(httpCall.getHostDomain()); if ((httpCall.getHostPort() != -1) && (httpCall.getHostPort() != httpCall.getProtocol() .getDefaultPort())) { sb.append(':').append(httpCall.getHostPort()); } setHostRef(sb.toString()); // Set the resource reference if (httpCall.getRequestUri() != null) { setResourceRef(new Reference(getHostRef(), httpCall.getRequestUri())); if (getResourceRef().isRelative()) { // Take care of the "/" between the host part and the segments. if (!httpCall.getRequestUri().startsWith("/")) { setResourceRef(new Reference(getHostRef().toString() + "/" + httpCall.getRequestUri())); } else { setResourceRef(new Reference(getHostRef().toString() + httpCall.getRequestUri())); } } setOriginalRef(getResourceRef().getTargetRef()); } // Set the request date String dateHeader = httpCall.getRequestHeaders().getFirstValue( HeaderConstants.HEADER_DATE); Date date = null; if (dateHeader != null) { date = DateUtils.parse(dateHeader); } if (date == null) { date = new Date(); } setDate(date); } @Override public boolean abort() { return getHttpCall().abort(); } @Override public List getCacheDirectives() { List result = super.getCacheDirectives(); if (!cacheDirectivesAdded) { for (Parameter header : getHttpCall().getRequestHeaders().subList( HeaderConstants.HEADER_CACHE_CONTROL)) { CacheDirectiveReader.addValues(header, result); } cacheDirectivesAdded = true; } return result; } @Override public ChallengeResponse getChallengeResponse() { ChallengeResponse result = super.getChallengeResponse(); if (!this.securityAdded) { // Extract the header value String authorization = getHttpCall().getRequestHeaders().getValues( HeaderConstants.HEADER_AUTHORIZATION); // Set the challenge response result = AuthenticatorUtils.parseResponse(this, authorization, getHttpCall().getRequestHeaders()); setChallengeResponse(result); this.securityAdded = true; } return result; } /** * Returns the client-specific information. * * @return The client-specific information. */ @Override public ClientInfo getClientInfo() { final ClientInfo result = super.getClientInfo(); if (!this.clientAdded) { // Extract the header values String acceptMediaType = getHttpCall().getRequestHeaders() .getValues(HeaderConstants.HEADER_ACCEPT); String acceptCharset = getHttpCall().getRequestHeaders().getValues( HeaderConstants.HEADER_ACCEPT_CHARSET); String acceptEncoding = getHttpCall().getRequestHeaders() .getValues(HeaderConstants.HEADER_ACCEPT_ENCODING); String acceptLanguage = getHttpCall().getRequestHeaders() .getValues(HeaderConstants.HEADER_ACCEPT_LANGUAGE); String expect = getHttpCall().getRequestHeaders().getValues( HeaderConstants.HEADER_EXPECT); // Parse the headers and update the call preferences // Parse the Accept* headers. If an error occurs during the parsing // of each header, the error is traced and we keep on with the other // headers. try { PreferenceReader.addCharacterSets(acceptCharset, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { PreferenceReader.addEncodings(acceptEncoding, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { PreferenceReader.addLanguages(acceptLanguage, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { PreferenceReader.addMediaTypes(acceptMediaType, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { ExpectationReader.addValues(expect, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } // Set other properties result.setAgent(getHttpCall().getRequestHeaders().getValues( HeaderConstants.HEADER_USER_AGENT)); result.setFrom(getHttpCall().getRequestHeaders().getFirstValue( HeaderConstants.HEADER_FROM)); result.setAddress(getHttpCall().getClientAddress()); result.setPort(getHttpCall().getClientPort()); if (getHttpCall().getUserPrincipal() != null) { result.getPrincipals().add(getHttpCall().getUserPrincipal()); } if (this.context != null) { // Special handling for the non standard but common // "X-Forwarded-For" header. final boolean useForwardedForHeader = Boolean .parseBoolean(this.context.getParameters() .getFirstValue("useForwardedForHeader", false)); if (useForwardedForHeader) { // Lookup the "X-Forwarded-For" header supported by popular // proxies and caches. final String header = getHttpCall().getRequestHeaders() .getValues(HeaderConstants.HEADER_X_FORWARDED_FOR); if (header != null) { final String[] addresses = header.split(","); for (int i = 0; i < addresses.length; i++) { String address = addresses[i].trim(); result.getForwardedAddresses().add(address); } } } } this.clientAdded = true; } return result; } /** * Returns the condition data applying to this call. * * @return The condition data applying to this call. */ @Override public Conditions getConditions() { final Conditions result = super.getConditions(); if (!this.conditionAdded) { // Extract the header values String ifMatchHeader = getHttpCall().getRequestHeaders().getValues( HeaderConstants.HEADER_IF_MATCH); String ifNoneMatchHeader = getHttpCall().getRequestHeaders() .getValues(HeaderConstants.HEADER_IF_NONE_MATCH); Date ifModifiedSince = null; Date ifUnmodifiedSince = null; String ifRangeHeader = getHttpCall().getRequestHeaders() .getFirstValue(HeaderConstants.HEADER_IF_RANGE); for (Parameter header : getHttpCall().getRequestHeaders()) { if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_MODIFIED_SINCE)) { ifModifiedSince = HeaderReader.readDate(header.getValue(), false); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_UNMODIFIED_SINCE)) { ifUnmodifiedSince = HeaderReader.readDate( header.getValue(), false); } } // Set the If-Modified-Since date if ((ifModifiedSince != null) && (ifModifiedSince.getTime() != -1)) { result.setModifiedSince(ifModifiedSince); } // Set the If-Unmodified-Since date if ((ifUnmodifiedSince != null) && (ifUnmodifiedSince.getTime() != -1)) { result.setUnmodifiedSince(ifUnmodifiedSince); } // Set the If-Match tags List match = null; Tag current = null; if (ifMatchHeader != null) { try { HeaderReader hr = new HeaderReader( ifMatchHeader); String value = hr.readRawValue(); while (value != null) { current = Tag.parse(value); // Is it the first tag? if (match == null) { match = new ArrayList(); result.setMatch(match); } // Add the new tag match.add(current); // Read the next token value = hr.readRawValue(); } } catch (Exception e) { this.context.getLogger().log( Level.INFO, "Unable to process the if-match header: " + ifMatchHeader); } } // Set the If-None-Match tags List noneMatch = null; if (ifNoneMatchHeader != null) { try { HeaderReader hr = new HeaderReader( ifNoneMatchHeader); String value = hr.readRawValue(); while (value != null) { current = Tag.parse(value); // Is it the first tag? if (noneMatch == null) { noneMatch = new ArrayList(); result.setNoneMatch(noneMatch); } noneMatch.add(current); // Read the next token value = hr.readRawValue(); } } catch (Exception e) { this.context.getLogger().log( Level.INFO, "Unable to process the if-none-match header: " + ifNoneMatchHeader); } } if (ifRangeHeader != null && ifRangeHeader.length() > 0) { Tag tag = Tag.parse(ifRangeHeader); if (tag != null) { result.setRangeTag(tag); } else { Date date = HeaderReader.readDate(ifRangeHeader, false); result.setRangeDate(date); } } this.conditionAdded = true; } return result; } /** * Returns the cookies provided by the client. * * @return The cookies provided by the client. */ @Override public Series getCookies() { final Series result = super.getCookies(); if (!this.cookiesAdded) { String cookieValues = getHttpCall().getRequestHeaders().getValues( HeaderConstants.HEADER_COOKIE); if (cookieValues != null) { new CookieReader(cookieValues).addValues(result); } this.cookiesAdded = true; } return result; } /** * Returns the representation provided by the client. * * @return The representation provided by the client. */ @Override public Representation getEntity() { if (!this.entityAdded) { setEntity(((ServerCall) getHttpCall()).getRequestEntity()); this.entityAdded = true; } return super.getEntity(); } /** * Returns the HTTP headers. * * @return The HTTP headers. */ @SuppressWarnings("unchecked") public Series getHeaders() { return (Series) getAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); } /** * Returns the low-level HTTP call. * * @return The low-level HTTP call. */ public ServerCall getHttpCall() { return this.httpCall; } @Override public ChallengeResponse getProxyChallengeResponse() { ChallengeResponse result = super.getProxyChallengeResponse(); if (!this.proxySecurityAdded) { // Extract the header value final String authorization = getHttpCall().getRequestHeaders() .getValues(HeaderConstants.HEADER_PROXY_AUTHORIZATION); // Set the challenge response result = AuthenticatorUtils.parseResponse(this, authorization, getHttpCall().getRequestHeaders()); setProxyChallengeResponse(result); this.proxySecurityAdded = true; } return result; } @Override public List getRanges() { final List result = super.getRanges(); if (!this.rangesAdded) { // Extract the header value final String ranges = getHttpCall().getRequestHeaders().getValues( HeaderConstants.HEADER_RANGE); result.addAll(RangeReader.read(ranges)); this.rangesAdded = true; } return result; } @Override public List getRecipientsInfo() { List result = super.getRecipientsInfo(); if (!recipientsInfoAdded) { for (String header : getHttpCall().getRequestHeaders() .getValuesArray(HeaderConstants.HEADER_VIA)) { new RecipientInfoReader(header).addValues(result); } recipientsInfoAdded = true; } return result; } /** * Returns the referrer reference if available. * * @return The referrer reference. */ @Override public Reference getReferrerRef() { if (!this.referrerAdded) { final String referrerValue = getHttpCall().getRequestHeaders() .getValues(HeaderConstants.HEADER_REFERRER); if (referrerValue != null) { setReferrerRef(new Reference(referrerValue)); } this.referrerAdded = true; } return super.getReferrerRef(); } @Override public List getWarnings() { List result = super.getWarnings(); if (!warningsAdded) { for (String header : getHttpCall().getRequestHeaders() .getValuesArray(HeaderConstants.HEADER_WARNING)) { new WarningReader(header).addValues(result); } warningsAdded = true; } return result; } @Override public void setChallengeResponse(ChallengeResponse response) { super.setChallengeResponse(response); this.securityAdded = true; } @Override public void setEntity(Representation entity) { super.setEntity(entity); this.entityAdded = true; } @Override public void setProxyChallengeResponse(ChallengeResponse response) { super.setProxyChallengeResponse(response); this.proxySecurityAdded = true; } @Override public void setRecipientsInfo(List recipientsInfo) { super.setRecipientsInfo(recipientsInfo); this.recipientsInfoAdded = true; } @Override public void setWarnings(List warnings) { super.setWarnings(warnings); this.warningsAdded = true; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/package.html0000664000175000017500000000012411757206350025754 0ustar jamespagejamespage Supports HTTP connectors.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/http/WebDavProtocolHelper.java0000664000175000017500000000345311757206346030405 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import org.restlet.data.Method; import org.restlet.engine.ProtocolHelper; /** * Protocol helper for the WEBDAV protocol. * * @author Thierry Boileau * */ public class WebDavProtocolHelper extends ProtocolHelper { @Override public void registerMethods() { Method.register(Method.COPY); Method.register(Method.LOCK); Method.register(Method.MKCOL); Method.register(Method.MOVE); Method.register(Method.PROPFIND); Method.register(Method.PROPPATCH); Method.register(Method.UNLOCK); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/0000775000175000017500000000000011757206350025470 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/HttpClientHelper.java0000664000175000017500000000404411757206346031560 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import org.restlet.Client; import org.restlet.data.Protocol; /** * HTTP client helper based on NIO blocking sockets. * * @author Jerome Louvel */ public class HttpClientHelper extends BaseClientHelper { /** * Constructor. * * @param client * The client to help. */ public HttpClientHelper(Client client) { super(client); getProtocols().add(Protocol.HTTP); getProtocols().add(Protocol.HTTPS); } @Override public synchronized void start() throws Exception { getLogger().info("Starting the default HTTP client"); super.start(); } @Override public synchronized void stop() throws Exception { getLogger().info("Stopping the default HTTP client"); super.stop(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/ConnectedRequest.java0000664000175000017500000006414611757206346031626 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.security.Principal; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CacheDirective; import org.restlet.data.ChallengeResponse; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.Range; import org.restlet.data.RecipientInfo; import org.restlet.data.Reference; import org.restlet.data.Tag; import org.restlet.data.Warning; import org.restlet.engine.http.header.CacheDirectiveReader; import org.restlet.engine.http.header.CookieReader; import org.restlet.engine.http.header.ExpectationReader; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.http.header.PreferenceReader; import org.restlet.engine.http.header.RangeReader; import org.restlet.engine.http.header.RecipientInfoReader; import org.restlet.engine.http.header.WarningReader; import org.restlet.engine.security.AuthenticatorUtils; import org.restlet.engine.util.DateUtils; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Request wrapper for server HTTP calls. * * @author Jerome Louvel */ public class ConnectedRequest 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. */ public static void addHeader(Request request, String headerName, String headerValue) { if (request instanceof ConnectedRequest) { ((ConnectedRequest) request).getHeaders().add(headerName, headerValue); } } /** Indicates if the cache control data was parsed and added. */ private volatile boolean cacheDirectivesAdded; /** Indicates if the client data was parsed and added. */ private volatile boolean clientAdded; /** Indicates if the conditions were parsed and added. */ private volatile boolean conditionAdded; /** The parent network connection. */ private final ServerConnection connection; /** The context of the parent connector. */ private final Context context; /** Indicates if the cookies were parsed and added. */ private volatile boolean cookiesAdded; /** Indicates if the proxy security data was parsed and added. */ private volatile boolean proxySecurityAdded; /** Indicates if the ranges data was parsed and added. */ private volatile boolean rangesAdded; /** Indicates if the recipients info was parsed and added. */ private volatile boolean recipientsInfoAdded; /** Indicates if the referrer was parsed and added. */ private volatile boolean referrerAdded; /** Indicates if the security data was parsed and added. */ private volatile boolean securityAdded; /** The user principal. */ private final Principal userPrincipal; /** Indicates if the warning data was parsed and added. */ private volatile boolean warningsAdded; /** * Copy constructor. * * @param request * The request to copy. */ public ConnectedRequest(ConnectedRequest request) { super(request); this.connection = request.getConnection(); this.context = request.context; this.userPrincipal = request.getUserPrincipal(); } /** * Constructor. * * @param context * The context of the parent connector. * @param connection * The associated network connection. * @param method * The protocol method. * @param resourceUri * The target resource URI. * @param version * The protocol version. * @param headers * The request headers. * @param entity * The request entity. * @param confidential * True if received confidentially. * @param userPrincipal * The user principal. */ public ConnectedRequest(Context context, ServerConnection connection, Method method, String resourceUri, String version, Series headers, Representation entity, boolean confidential, Principal userPrincipal) { super(); this.connection = connection; this.context = context; this.userPrincipal = userPrincipal; this.cacheDirectivesAdded = false; this.clientAdded = false; this.conditionAdded = false; this.cookiesAdded = false; this.proxySecurityAdded = false; this.rangesAdded = false; this.recipientsInfoAdded = false; this.referrerAdded = false; this.securityAdded = false; this.warningsAdded = false; // Set the properties setMethod(method); setEntity(entity); // Put the headers in the request's attributes map getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headers); if (version != null) { int slashIndex = version.indexOf('/'); if (slashIndex != -1) { version = version.substring(slashIndex + 1); } else { version = null; } } if (confidential) { List clientCertificates = getConnection() .getSslClientCertificates(); if (clientCertificates != null) { getAttributes().put( HeaderConstants.ATTRIBUTE_HTTPS_CLIENT_CERTIFICATES, clientCertificates); } String cipherSuite = getConnection().getSslCipherSuite(); if (cipherSuite != null) { getAttributes().put( HeaderConstants.ATTRIBUTE_HTTPS_CIPHER_SUITE, cipherSuite); } Integer keySize = getConnection().getSslKeySize(); if (keySize != null) { getAttributes().put(HeaderConstants.ATTRIBUTE_HTTPS_KEY_SIZE, keySize); } } // Set the protocol used for this request Protocol serverProtocol = getConnection().getHelper().getHelped() .getProtocols().get(0); setProtocol(new Protocol(serverProtocol.getSchemeName(), serverProtocol.getName(), serverProtocol.getDescription(), serverProtocol.getDefaultPort(), serverProtocol.isConfidential(), version)); // Parse the host header String host = (getHeaders() == null) ? null : getHeaders() .getFirstValue(HeaderConstants.HEADER_HOST, true); String hostDomain = null; int hostPort = -1; if (host != null) { int colonIndex = host.indexOf(':'); if (colonIndex != -1) { hostDomain = host.substring(0, colonIndex); hostPort = Integer.valueOf(host.substring(colonIndex + 1)); } else { hostDomain = host; hostPort = getProtocol().getDefaultPort(); } } else { if (!Protocol.SIP.getSchemeName().equals( serverProtocol.getSchemeName()) && !Protocol.SIPS.getSchemeName().equals( serverProtocol.getSchemeName())) { Context.getCurrentLogger().info( "Couldn't find the mandatory \"Host\" HTTP header."); } } // Set the host reference Protocol protocol = getConnection().getHelper().getHelped() .getProtocols().get(0); StringBuilder sb = new StringBuilder(); sb.append(protocol.getSchemeName()).append(":"); if (hostDomain != null) { sb.append("//").append(hostDomain); } if ((hostPort != -1) && (hostPort != protocol.getDefaultPort())) { sb.append(':').append(hostPort); } setHostRef(sb.toString()); // Set the resource reference if (resourceUri != null) { setResourceRef(new Reference(getHostRef(), resourceUri)); if (getResourceRef().isRelative()) { // Take care of the "/" between the host part and the segments. if (!resourceUri.startsWith("/")) { setResourceRef(new Reference(getHostRef().toString() + "/" + resourceUri)); } else { setResourceRef(new Reference(getHostRef().toString() + resourceUri)); } } setOriginalRef(getResourceRef().getTargetRef()); } // Set the request date String dateHeader = (getHeaders() == null) ? null : getHeaders() .getFirstValue(HeaderConstants.HEADER_DATE); Date date = null; if (dateHeader != null) { date = DateUtils.parse(dateHeader); } if (date == null) { date = new Date(); } setDate(date); // Set the max forwards String maxForwardsHeader = (getHeaders() == null) ? null : getHeaders() .getFirstValue(HeaderConstants.HEADER_MAX_FORWARDS); if (maxForwardsHeader != null) { try { setMaxForwards(Integer.parseInt(maxForwardsHeader)); } catch (NumberFormatException nfe) { Context.getCurrentLogger().info( "Unable to parse the Max-Forwards header: " + maxForwardsHeader); } } } @Override public boolean abort() { getConnection().close(); return true; } @Override public synchronized void commit(Response response) { if ((response != null) && !response.isCommitted()) { getConnection().commit(response); response.setCommitted(true); } } @Override public List getCacheDirectives() { List result = super.getCacheDirectives(); if (!this.cacheDirectivesAdded) { if (getHeaders() != null) { for (Parameter header : getHeaders().subList( HeaderConstants.HEADER_CACHE_CONTROL)) { CacheDirectiveReader.addValues(header, result); } } this.cacheDirectivesAdded = true; } return result; } @Override public ChallengeResponse getChallengeResponse() { ChallengeResponse result = super.getChallengeResponse(); if (!this.securityAdded) { if (getHeaders() != null) { // Extract the header value String authorization = getHeaders().getValues( HeaderConstants.HEADER_AUTHORIZATION); // Set the challenge response result = AuthenticatorUtils.parseResponse(this, authorization, getHeaders()); setChallengeResponse(result); } this.securityAdded = true; } return result; } /** * Returns the client-specific information. * * @return The client-specific information. */ @Override public ClientInfo getClientInfo() { ClientInfo result = super.getClientInfo(); if (!this.clientAdded) { if (getHeaders() != null) { // Extract the header values String acceptMediaType = getHeaders().getValues( HeaderConstants.HEADER_ACCEPT); String acceptCharset = getHeaders().getValues( HeaderConstants.HEADER_ACCEPT_CHARSET); String acceptEncoding = getHeaders().getValues( HeaderConstants.HEADER_ACCEPT_ENCODING); String acceptLanguage = getHeaders().getValues( HeaderConstants.HEADER_ACCEPT_LANGUAGE); String expect = getHeaders().getValues( HeaderConstants.HEADER_EXPECT); // Parse the headers and update the call preferences // Parse the Accept* headers. If an error occurs during the // parsing of each header, the error is traced and we keep on // with the other headers. try { PreferenceReader.addCharacterSets(acceptCharset, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { PreferenceReader.addEncodings(acceptEncoding, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { PreferenceReader.addLanguages(acceptLanguage, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { PreferenceReader.addMediaTypes(acceptMediaType, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } try { ExpectationReader.addValues(expect, result); } catch (Exception e) { this.context.getLogger().log(Level.INFO, e.getMessage()); } // Set other properties result.setAgent(getHeaders().getValues( HeaderConstants.HEADER_USER_AGENT)); result.setFrom(getHeaders().getFirstValue( HeaderConstants.HEADER_FROM)); result.setAddress(getConnection().getAddress()); result.setPort(getConnection().getPort()); if (userPrincipal != null) { result.getPrincipals().add(userPrincipal); } if (this.context != null) { // Special handling for the non standard but common // "X-Forwarded-For" header. final boolean useForwardedForHeader = Boolean .parseBoolean(this.context.getParameters() .getFirstValue("useForwardedForHeader", false)); if (useForwardedForHeader) { // Lookup the "X-Forwarded-For" header supported by // popular // proxies and caches. final String header = getHeaders().getValues( HeaderConstants.HEADER_X_FORWARDED_FOR); if (header != null) { final String[] addresses = header.split(","); for (int i = 0; i < addresses.length; i++) { String address = addresses[i].trim(); result.getForwardedAddresses().add(address); } } } } } this.clientAdded = true; } return result; } /** * Returns the condition data applying to this call. * * @return The condition data applying to this call. */ @Override public Conditions getConditions() { Conditions result = super.getConditions(); if (!this.conditionAdded) { if (getHeaders() != null) { // Extract the header values String ifMatchHeader = getHeaders().getValues( HeaderConstants.HEADER_IF_MATCH); String ifNoneMatchHeader = getHeaders().getValues( HeaderConstants.HEADER_IF_NONE_MATCH); Date ifModifiedSince = null; Date ifUnmodifiedSince = null; String ifRangeHeader = getHeaders().getFirstValue( HeaderConstants.HEADER_IF_RANGE); for (Parameter header : getHeaders()) { if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_MODIFIED_SINCE)) { ifModifiedSince = HeaderReader.readDate( header.getValue(), false); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_UNMODIFIED_SINCE)) { ifUnmodifiedSince = HeaderReader.readDate( header.getValue(), false); } } // Set the If-Modified-Since date if ((ifModifiedSince != null) && (ifModifiedSince.getTime() != -1)) { result.setModifiedSince(ifModifiedSince); } // Set the If-Unmodified-Since date if ((ifUnmodifiedSince != null) && (ifUnmodifiedSince.getTime() != -1)) { result.setUnmodifiedSince(ifUnmodifiedSince); } // Set the If-Match tags List match = null; Tag current = null; if (ifMatchHeader != null) { try { HeaderReader hr = new HeaderReader( ifMatchHeader); String value = hr.readRawValue(); while (value != null) { current = Tag.parse(value); // Is it the first tag? if (match == null) { match = new ArrayList(); result.setMatch(match); } // Add the new tag match.add(current); // Read the next token value = hr.readRawValue(); } } catch (Exception e) { this.context.getLogger().log( Level.INFO, "Unable to process the if-match header: " + ifMatchHeader); } } // Set the If-None-Match tags List noneMatch = null; if (ifNoneMatchHeader != null) { try { HeaderReader hr = new HeaderReader( ifNoneMatchHeader); String value = hr.readRawValue(); while (value != null) { current = Tag.parse(value); // Is it the first tag? if (noneMatch == null) { noneMatch = new ArrayList(); result.setNoneMatch(noneMatch); } noneMatch.add(current); // Read the next token value = hr.readRawValue(); } } catch (Exception e) { this.context.getLogger().log( Level.INFO, "Unable to process the if-none-match header: " + ifNoneMatchHeader); } } if (ifRangeHeader != null && ifRangeHeader.length() > 0) { Tag tag = Tag.parse(ifRangeHeader); if (tag != null) { result.setRangeTag(tag); } else { Date date = HeaderReader.readDate(ifRangeHeader, false); result.setRangeDate(date); } } } this.conditionAdded = true; } return result; } protected ServerConnection getConnection() { return connection; } /** * Returns the cookies provided by the client. * * @return The cookies provided by the client. */ @Override public Series getCookies() { Series result = super.getCookies(); if (!this.cookiesAdded) { if (getHeaders() != null) { String cookieValues = getHeaders().getValues( HeaderConstants.HEADER_COOKIE); if (cookieValues != null) { new CookieReader(cookieValues).addValues(result); } } this.cookiesAdded = true; } return result; } /** * Returns the HTTP headers. * * @return The HTTP headers. */ @SuppressWarnings("unchecked") public Series getHeaders() { return (Series) getAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); } @Override public ChallengeResponse getProxyChallengeResponse() { ChallengeResponse result = super.getProxyChallengeResponse(); if (!this.proxySecurityAdded) { if (getHeaders() != null) { // Extract the header value final String authorization = getHeaders().getValues( HeaderConstants.HEADER_PROXY_AUTHORIZATION); // Set the challenge response result = AuthenticatorUtils.parseResponse(this, authorization, getHeaders()); setProxyChallengeResponse(result); } this.proxySecurityAdded = true; } return result; } @Override public List getRanges() { final List result = super.getRanges(); if (!this.rangesAdded) { if (getHeaders() != null) { // Extract the header value String ranges = getHeaders().getValues( HeaderConstants.HEADER_RANGE); result.addAll(RangeReader.read(ranges)); } this.rangesAdded = true; } return result; } @Override public List getRecipientsInfo() { List result = super.getRecipientsInfo(); if (!recipientsInfoAdded) { if (getHeaders() != null) { for (String header : getHeaders().getValuesArray( HeaderConstants.HEADER_VIA)) { new RecipientInfoReader(header).addValues(result); } } this.recipientsInfoAdded = true; } return result; } /** * Returns the referrer reference if available. * * @return The referrer reference. */ @Override public Reference getReferrerRef() { if (!this.referrerAdded) { if (getHeaders() != null) { final String referrerValue = getHeaders().getValues( HeaderConstants.HEADER_REFERRER); if (referrerValue != null) { setReferrerRef(new Reference(referrerValue)); } } this.referrerAdded = true; } return super.getReferrerRef(); } public Principal getUserPrincipal() { return userPrincipal; } @Override public List getWarnings() { List result = super.getWarnings(); if (!this.warningsAdded) { if (getHeaders() != null) { for (String warning : getHeaders().getValuesArray( HeaderConstants.HEADER_WARNING)) { new WarningReader(warning).addValues(result); } } this.warningsAdded = true; } return result; } @Override public void setChallengeResponse(ChallengeResponse response) { super.setChallengeResponse(response); this.securityAdded = true; } @Override public void setProxyChallengeResponse(ChallengeResponse response) { super.setProxyChallengeResponse(response); this.proxySecurityAdded = true; } @Override public void setRecipientsInfo(List recipientsInfo) { super.setRecipientsInfo(recipientsInfo); this.recipientsInfoAdded = true; } @Override public void setWarnings(List warnings) { super.setWarnings(warnings); this.warningsAdded = true; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java0000664000175000017500000000332511757206346031443 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; /** * Enumeration of the states of a connection. * * @author Jerome Louvel */ public enum ConnectionState { /** The network connection is being opened. */ OPENING, /** The network connection has been successfully opened. */ OPEN, /** * The network connection will be close as soon as the pending pending * response is sent. */ CLOSING, /** The network connection has been successfully closed. */ CLOSED; } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/BaseTask.java0000664000175000017500000000357311757206346030045 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; public abstract class BaseTask implements Runnable { /** Indicates if the task is running. */ private volatile boolean running; /** * Constructor. */ public BaseTask() { this.running = false; } /** * Indicates if the task is running. * * @return True if the task is running. */ public boolean isRunning() { return running; } /** * Indicates if the task is running. * * @param running * True if the task is running. */ public void setRunning(boolean running) { this.running = running; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/Controller.java0000664000175000017500000002106711757206346030471 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import org.restlet.Response; import org.restlet.engine.Engine; /** * Controls the state of the server helper and its managed connections. * * @author Jerome Louvel */ public class Controller extends BaseTask { /** The parent server helper. */ private final BaseHelper helper; /** Indicates if the controller is overloaded. */ private volatile boolean overloaded; /** * Constructor. * * @param helper * The parent connector helper. */ public Controller(BaseHelper helper) { this.helper = helper; this.overloaded = false; } /** * Control each connection for messages to read or write. * * @throws IOException */ protected void controlConnections() throws IOException { for (final Connection conn : getHelper().getConnections()) { if (conn.getState() == ConnectionState.CLOSED) { getHelper().getConnections().remove(conn); } else if ((conn.getState() == ConnectionState.CLOSING) && !conn.isBusy()) { conn.close(); } else { if ((isOverloaded() && !getHelper().isClientSide()) || conn.canWrite()) { execute(new Runnable() { public void run() { conn.writeMessages(); } @Override public String toString() { return "Write connection messages"; } }); } if ((isOverloaded() && getHelper().isClientSide()) || conn.canRead()) { execute(new Runnable() { public void run() { conn.readMessages(); } @Override public String toString() { return "Read connection messages: " + conn.canRead(); } }); } } } } /** * Control the helper for inbound or outbound messages to handle. */ protected void controlHelper() { // Control if there are some pending requests that could // be processed for (int i = 0; i < getHelper().getInboundMessages().size(); i++) { final Response response = getHelper().getInboundMessages().poll(); if (response != null) { execute(new Runnable() { public void run() { try { getHelper().handleInbound(response); } finally { Engine.clearThreadLocalVariables(); } } @Override public String toString() { return "Handle inbound messages"; } }); } } // Control if some pending responses that could be moved // to their respective connection queues for (int i = 0; i < getHelper().getOutboundMessages().size(); i++) { final Response response = getHelper().getOutboundMessages().poll(); if (response != null) { execute(new Runnable() { public void run() { try { getHelper().handleOutbound(response); } finally { Engine.clearThreadLocalVariables(); } } @Override public String toString() { return "Handle outbound messages"; } }); } } } /** * Executes the next task in a separate thread provided by the worker * service, only if the worker service isn't busy. * * @param task * The next task to execute. */ protected void execute(Runnable task) { try { if (!isOverloaded() && !getWorkerService().isShutdown() && isRunning()) { getWorkerService().execute(task); } } catch (Exception e) { getHelper().getLogger().log( Level.WARNING, "Unable to execute a " + (getHelper().isClientSide() ? "client-side" : "server-side") + " controller task", e); } } /** * Returns the parent connector helper. * * @return The parent connector helper. */ protected BaseHelper getHelper() { return helper; } /** * Returns the helper's worker service. * * @return The helper's worker service. */ protected ExecutorService getWorkerService() { return getHelper().getWorkerService(); } /** * Indicates if the controller is overloaded. * * @return True if the controller is overloaded. */ public boolean isOverloaded() { return overloaded; } /** * Indicates if the helper's worker service is fully busy and can't accept * more tasks. * * @return True if the helper's worker service is fully busy. */ protected boolean isWorkerServiceFull() { return getHelper().isWorkerServiceFull(); } /** * Listens on the given server socket for incoming connections. */ public void run() { setRunning(true); while (isRunning() || !getHelper().getConnections().isEmpty()) { try { if (isOverloaded()) { if (!isWorkerServiceFull()) { setOverloaded(false); getHelper() .getLogger() .log(Level.INFO, "Accepting new connections and transactions again."); } } else { if (isWorkerServiceFull()) { setOverloaded(true); getHelper() .getLogger() .log( Level.INFO, "Stop accepting new connections and transactions. Consider increasing the maximum number of threads."); } controlConnections(); controlHelper(); } // Sleep a bit Thread.sleep(getHelper().getControllerSleepTimeMs()); } catch (Exception ex) { this.helper.getLogger().log(Level.FINE, "Unexpected error while controlling connector", ex); } } } /** * Indicates if the controller is overloaded. * * @param overloaded * True if the controller is overloaded. */ public void setOverloaded(boolean overloaded) { this.overloaded = overloaded; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/BaseHelper.java0000664000175000017500000004332011757206346030354 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.net.Socket; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.restlet.Connector; import org.restlet.Request; import org.restlet.Response; import org.restlet.engine.ConnectorHelper; import org.restlet.engine.io.IoUtils; import org.restlet.engine.log.LoggingThreadFactory; /** * Base connector helper. Here is the list of parameters that are supported. * They should be set in the connector's context before it is started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    controllerDaemonbooleantrueIndicates if the controller thread should be a daemon (not blocking JVM * exit).
    controllerSleepTimeMsint100Time for the controller thread to sleep between each control.
    inboundBufferSizeint{@link IoUtils#BUFFER_SIZE}The size of the buffer when reading messages.
    minThreadsint1Minimum threads waiting to service requests.
    maxThreadsint10Maximum threads that will service requests.
    maxConnectionsPerHostint-1Maximum number of concurrent connections per host (IP address).
    maxTotalConnectionsint-1Maximum number of concurrent connections in total.
    outboundBufferSizeint{@link IoUtils#BUFFER_SIZE}The size of the buffer when writing messages.
    persistingConnectionsbooleantrueIndicates if connections should be kept alive after a call.
    pipeliningConnectionsbooleanfalseIndicates if pipelining connections are supported.
    threadMaxIdleTimeMsint60000Time for an idle thread to wait for an operation before being collected.
    tracingbooleanfalseIndicates if all messages should be printed on the standard console.
    * * @author Jerome Louvel */ public abstract class BaseHelper extends ConnectorHelper { /** Indicates if it is helping a client connector. */ private final boolean clientSide; /** The set of active connections. */ private final Set> connections; /** The controller task. */ private final Controller controller; /** The controller service. */ private volatile ExecutorService controllerService; /** The queue of inbound messages. */ private final Queue inboundMessages; /** The queue of outbound messages. */ private final Queue outboundMessages; /** The worker service. */ private volatile ThreadPoolExecutor workerService; /** * Constructor. * * @param connector * The helped connector. * @param clientSide * True if it is helping a client connector. */ public BaseHelper(T connector, boolean clientSide) { super(connector); this.clientSide = clientSide; this.connections = new CopyOnWriteArraySet>(); this.inboundMessages = new ConcurrentLinkedQueue(); this.outboundMessages = new ConcurrentLinkedQueue(); this.controller = createController(); this.workerService = null; } /** * Creates a connection associated to the given socket. * * @param helper * The parent helper. * @param socket * The underlying BIO socket. * @param socketChannel * The underlying NIO socket channel. * @return The new connection. * @throws IOException */ protected abstract Connection createConnection(BaseHelper helper, Socket socket, SocketChannel socketChannel) throws IOException; /** * Creates a new controller. * * @return A new controller. */ protected Controller createController() { return new Controller(this); } /** * Creates the connector controller service. * * @return The connector controller service. */ protected ExecutorService createControllerService() { return Executors.newSingleThreadExecutor(new LoggingThreadFactory( getLogger(), isControllerDaemon())); } /** * Creates the response object. * * @param request * The associated request. * @return The response object. */ protected Response createResponse(Request request) { return new Response(request); } /** * Creates the handler service. * * @return The handler service. */ protected ThreadPoolExecutor createWorkerService() { int maxThreads = getMaxThreads(); int minThreads = getMinThreads(); ThreadPoolExecutor result = new ThreadPoolExecutor(minThreads, maxThreads, getThreadMaxIdleTimeMs(), TimeUnit.MILLISECONDS, new SynchronousQueue(), new LoggingThreadFactory( getLogger(), true)); result.setRejectedExecutionHandler(new RejectedExecutionHandler() { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { getLogger().warning( "Unable to run the following " + (isClientSide() ? "client-side" : "server-side") + " task: " + r); getLogger().info( "Worker service state: " + (isWorkerServiceFull() ? "Full" : "Normal")); getLogger().info( "Worker service tasks: " + getWorkerService().getQueue().size() + " queued, " + getWorkerService().getActiveCount() + " active, " + getWorkerService().getCompletedTaskCount() + " completed, " + getWorkerService().getTaskCount() + " scheduled."); getLogger().info( "Worker service thread pool: " + getWorkerService().getCorePoolSize() + " core size, " + getWorkerService().getLargestPoolSize() + " largest size, " + getWorkerService().getMaximumPoolSize() + " maximum size, " + getWorkerService().getPoolSize() + " current size"); } }); return result; } /** * Returns the set of active connections. * * @return The set of active connections. */ protected Set> getConnections() { return connections; } /** * Returns the controller task. * * @return The controller task. */ public Controller getController() { return controller; } /** * Returns the time for the controller thread to sleep between each control. * * @return The time for the controller thread to sleep between each control. */ public int getControllerSleepTimeMs() { return Integer.parseInt(getHelpedParameters().getFirstValue( "controllerSleepTimeMs", "100")); } /** * Returns the size of the buffer when reading messages.. * * @return The size of the buffer when reading messages.. */ public int getInboundBufferSize() { return Integer.parseInt(getHelpedParameters().getFirstValue( "inboundBufferSize", Integer.toString(IoUtils.BUFFER_SIZE))); } /** * Returns the queue of inbound messages pending for handling. * * @return The queue of inbound messages. */ protected Queue getInboundMessages() { return inboundMessages; } /** * Returns the maximum concurrent connections per host (IP address). By * default, it is unbounded. * * @return Maximum number of concurrent connections per host (IP address). */ public int getMaxConnectionsPerHost() { return Integer.parseInt(getHelpedParameters().getFirstValue( "maxConnectionsPerHost", "-1")); } /** * Returns the maximum threads that will service requests. * * @return The maximum threads that will service requests. */ public int getMaxThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( "maxThreads", "10")); } /** * Returns the maximum number of concurrent connections allowed. By default, * it is unbounded. * * @return The maximum number of concurrent connections allowed. */ public int getMaxTotalConnections() { return Integer.parseInt(getHelpedParameters().getFirstValue( "maxTotalConnections", "-1")); } /** * Returns the minimum threads waiting to service requests. * * @return The minimum threads waiting to service requests. */ public int getMinThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( "minThreads", "1")); } /** * Returns the size of the buffer when writing messages.. * * @return The size of the buffer when writing messages.. */ public int getOutboundBufferSize() { return Integer.parseInt(getHelpedParameters().getFirstValue( "outboundBufferSize", Integer.toString(IoUtils.BUFFER_SIZE))); } /** * Returns the queue of outbound messages pending for handling. * * @return The queue of outbound messages. */ protected Queue getOutboundMessages() { return outboundMessages; } /** * Returns the time for an idle thread to wait for an operation before being * collected. * * @return The time for an idle thread to wait for an operation before being * collected. */ public int getThreadMaxIdleTimeMs() { return Integer.parseInt(getHelpedParameters().getFirstValue( "threadMaxIdleTimeMs", "60000")); } /** * Returns the connection handler service. * * @return The connection handler service. */ public ThreadPoolExecutor getWorkerService() { return workerService; } /** * Handles an inbound message. * * @param response * The response to handle. */ public abstract void handleInbound(Response response); /** * Handles the next inbound message. */ public void handleNextInbound() { handleInbound(getInboundMessages().poll()); } /** * Handles the next outbound message. */ protected void handleNextOutbound() { handleOutbound(getOutboundMessages().poll()); } /** * Handles an outbound message. * * @param response * The response to handle. */ public abstract void handleOutbound(Response response); /** * Indicates if it is helping a client connector. * * @return True if it is helping a client connector. */ public boolean isClientSide() { return clientSide; } /** * Indicates if the controller thread should be a daemon (not blocking JVM * exit). * * @return True if the controller thread should be a daemon (not blocking * JVM exit). */ public boolean isControllerDaemon() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "controllerDaemon", "true")); } /** * Indicates if persistent connections should be used if possible. * * @return True if persistent connections should be used if possible. */ public boolean isPersistingConnections() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "persistingConnections", "true")); } /** * Indicates if pipelining connections are supported. * * @return True if pipelining connections are supported. */ public boolean isPipeliningConnections() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "pipeliningConnections", "false")); } /** * Indicates if the helper is going through a client proxy or is a server * proxy. * * @return True if the helper is going through a client proxy or is a server * proxy. */ public abstract boolean isProxying(); /** * Indicates if it is helping a server connector. * * @return True if it is helping a server connector. */ public boolean isServerSide() { return !isClientSide(); } /** * Indicates if console tracing is enabled. * * @return True if console tracing is enabled. */ public boolean isTracing() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "tracing", "false")); } /** * Indicates if the worker service is busy. This state is detected by * checking if the number of active task running is superior or equal to the * maximum pool size. * * @return True if the worker service is busy. */ protected boolean isWorkerServiceFull() { return (getWorkerService().getActiveCount()) >= (getWorkerService() .getMaximumPoolSize()); } @Override public void start() throws Exception { super.start(); this.controllerService = createControllerService(); this.workerService = createWorkerService(); this.controllerService.submit(this.controller); } @Override public void stop() throws Exception { // For atomicity purpose ThreadPoolExecutor workerService = getWorkerService(); // Stop accepting connections super.stop(); // Gracefully shutdown the workers if (workerService != null) { workerService.shutdown(); } // Close the open connections for (Connection connection : getConnections()) { connection.setState(ConnectionState.CLOSING); connection.setInboundBusy(false); connection.setOutboundBusy(false); } // Await for completion of pending workers if (workerService != null) { try { workerService.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException ex) { getLogger().log(Level.FINE, "Interruption while shutting down the worker service", ex); } } // Stops the controller if (this.controllerService != null) { this.controller.setRunning(false); this.controllerService.shutdown(); try { this.controllerService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException ex) { getLogger() .log(Level.FINE, "Interruption while shutting down the controller service", ex); } } for (Connection connection : getConnections()) { getLogger().log( Level.WARNING, "The controller is shutdown whereas a connection was found in the state: " + connection.getState()); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java0000664000175000017500000002662111757206346031605 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.nio.channels.SocketChannel; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.util.StringUtils; import org.restlet.util.Series; /** * Generic HTTP-like client connection. * * @author Jerome Louvel */ public class ClientConnection extends Connection { /** * Returns the request URI. * * @param resourceRef * The resource reference. * @param isProxied * Indicates if the request goes through a proxy and requires an * absolute URI. * @return The absolute request URI. */ private static String getRequestUri(Reference resourceRef, boolean isProxied) { String result = null; Reference requestRef = resourceRef.isAbsolute() ? resourceRef : resourceRef.getTargetRef(); if (isProxied) { result = requestRef.getIdentifier(); } else { if (requestRef.hasQuery()) { result = requestRef.getPath() + "?" + requestRef.getQuery(); } else { result = requestRef.getPath(); } if ((result == null) || (result.equals(""))) { result = "/"; } } return result; } /** * Constructor. * * @param helper * The parent connector helper. * @param socket * The underlying BIO socket. * @param socketChannel * The underlying NIO socket channel. * @throws IOException */ public ClientConnection(BaseHelper helper, Socket socket, SocketChannel socketChannel) throws IOException { super(helper, socket, socketChannel); } /** * Adds the request headers. * * @param request * The request to inspect. * @param headers * The headers series to update. */ protected void addRequestHeaders(Request request, Series headers) { HeaderUtils.addRequestHeaders(request, headers); } /** * Indicates whether the client connection can accept a new message. * * @return True if the client connection can accept a new message. */ public boolean canEnqueue() { return !isBusy() && getOutboundMessages().isEmpty() && getInboundMessages().isEmpty(); } @Override public boolean canRead() { // There should be at least one call to read/update return super.canRead() && (getInboundMessages().size() > 0); } @Override public boolean canWrite() { return super.canWrite() && ((getInboundMessages().size() == 0) || isPipelining()); } /** * Copies headers into a response. * * @param headers * The headers to copy. * @param response * The response to update. */ protected void copyResponseTransportHeaders(Series headers, Response response) { HeaderUtils.copyResponseTransportHeaders(headers, response); } /** * Returns the status corresponding to a given status code. * * @param code * The status code. * @return The status corresponding to a given status code. */ protected Status createStatus(int code) { return Status.valueOf(code); } @Override protected void readMessage() throws IOException { @SuppressWarnings("unused") String version = null; Series headers = null; int statusCode = 0; String reasonPhrase = null; // Parse the HTTP version StringBuilder sb = new StringBuilder(); int next = getInboundStream().read(); while ((next != -1) && !HeaderUtils.isSpace(next)) { sb.append((char) next); next = getInboundStream().read(); } if (next == -1) { throw new IOException( "Unable to parse the response HTTP version. End of stream reached too early."); } version = sb.toString(); sb.delete(0, sb.length()); // Parse the status code next = getInboundStream().read(); while ((next != -1) && !HeaderUtils.isSpace(next)) { sb.append((char) next); next = getInboundStream().read(); } if (next == -1) { throw new IOException( "Unable to parse the response status. End of stream reached too early."); } try { statusCode = Integer.parseInt(sb.toString()); } catch (NumberFormatException e) { throw new IOException( "Unable to parse the status code. Non numeric value: " + sb.toString()); } sb.delete(0, sb.length()); // Parse the reason phrase next = getInboundStream().read(); while ((next != -1) && !HeaderUtils.isCarriageReturn(next)) { sb.append((char) next); next = getInboundStream().read(); } if (next == -1) { throw new IOException( "Unable to parse the reason phrase. End of stream reached too early."); } next = getInboundStream().read(); if (HeaderUtils.isLineFeed(next)) { reasonPhrase = sb.toString(); sb.delete(0, sb.length()); // Parse the headers Parameter header = HeaderReader.readHeader(getInboundStream(), sb); while (header != null) { if (headers == null) { headers = new Form(); } headers.add(header); header = HeaderReader.readHeader(getInboundStream(), sb); } } else { throw new IOException( "Unable to parse the reason phrase. The carriage return must be followed by a line feed."); } // Check if the server wants to close the connection if (HeaderUtils.isConnectionClose(headers)) { setState(ConnectionState.CLOSING); } // Prepare the response Response finalResponse = getInboundMessages().peek(); Response response = null; Status status = createStatus(statusCode); if (status.isInformational()) { response = getHelper().createResponse(finalResponse.getRequest()); } else { response = finalResponse; } // Update the response response.setStatus(status, reasonPhrase); response.getServerInfo().setAddress( getSocket().getLocalAddress().toString()); response.getServerInfo().setAgent(Engine.VERSION_HEADER); response.getServerInfo().setPort(getSocket().getPort()); response.setEntity(createInboundEntity(headers)); try { copyResponseTransportHeaders(headers, response); } catch (Throwable t) { getLogger() .log(Level.WARNING, "Error while parsing the headers", t); } // Put the headers in the response's attributes map if (headers != null) { response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headers); } if (!response.getStatus().isInformational()) { getInboundMessages().poll(); } // Add it to the helper queue getHelper().getInboundMessages().add(response); } /** * Write the given response on the socket. * * @param response * The response to write. */ @Override protected void writeMessage(Response response) { // Prepare the headers Series headers = new Form(); Request request = response.getRequest(); try { addGeneralHeaders(request, headers); addRequestHeaders(request, headers); addEntityHeaders(request.getEntity(), headers); writeMessage(response, headers); } catch (IOException e) { getLogger().log(Level.INFO, "An exception occured writing the request", e); response.setStatus(Status.CONNECTOR_ERROR_COMMUNICATION, "An exception occured writing the request"); response.setEntity(null); try { writeMessage(response, headers); } catch (IOException ee) { getLogger().log(Level.WARNING, "Unable to send error request", ee); } } finally { if (request.getOnSent() != null) { request.getOnSent().handle(request, response); } // The request has been written getOutboundMessages().poll(); if (request.isExpectingResponse()) { getInboundMessages().add(response); } // Indicate that we are done with writing the request setOutboundBusy(false); } } @Override protected void writeMessageHeadLine(Response message, OutputStream headStream) throws IOException { Request request = message.getRequest(); headStream.write(StringUtils.getAsciiBytes(request.getMethod() .getName())); headStream.write(' '); headStream.write(StringUtils.getAsciiBytes(getRequestUri( request.getResourceRef(), getHelper().isProxying()))); headStream.write(' '); headStream.write(StringUtils.getAsciiBytes(request.getProtocol() .getTechnicalName())); headStream.write('/'); headStream.write(StringUtils.getAsciiBytes(request.getProtocol() .getVersion())); HeaderUtils.writeCRLF(getOutboundStream()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/package.html0000664000175000017500000000014011757206350027744 0ustar jamespagejamespage New advanced internal HTTP connector.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/Acceptor.java0000664000175000017500000001052211757206346030100 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.ClosedByInterruptException; import java.util.concurrent.CountDownLatch; import java.util.logging.Level; import org.restlet.Server; /** * Listens on the given socket channel for incoming connections and dispatches * them to the given handler pool * * @author Jerome Louvel */ public class Acceptor extends BaseTask { /** The parent server helper. */ private final BaseServerHelper helper; /** * The latch to countdown when the socket is ready to accept connections. */ private final CountDownLatch latch; /** * Constructor. * * @param helper * The target server helper. * @param latch * The latch to countdown when the socket is ready to accept * connections. */ public Acceptor(BaseServerHelper helper, CountDownLatch latch) { this.helper = helper; this.latch = latch; } /** * Returns the parent server helper. * * @return The parent server helper. */ protected BaseServerHelper getHelper() { return helper; } /** * Listens on the given server socket for incoming connections. */ public void run() { this.latch.countDown(); setRunning(true); while (isRunning()) { try { Socket socket = getHelper().getServerSocket().accept(); int connectionsCount = getHelper().getConnections().size(); if ((getHelper().getMaxTotalConnections() == -1) || (connectionsCount <= getHelper() .getMaxTotalConnections())) { Connection connection = getHelper() .createConnection(getHelper(), socket, null); connection.open(); getHelper().getConnections().add(connection); } else { // Rejection connection socket.close(); getHelper() .getLogger() .info( "Maximum number of concurrent connections reached. New connection rejected."); } } catch (ClosedByInterruptException ex) { this.helper.getLogger().log(Level.FINE, "ServerSocket channel was closed by interrupt", ex); break; } catch (AsynchronousCloseException ace) { this.helper.getLogger().log(Level.FINE, "The server socket was closed", ace); } catch (SocketException se) { this.helper.getLogger().log(Level.FINE, "The server socket was closed", se); } catch (IOException ex) { this.helper.getLogger().log(Level.WARNING, "Unexpected error while accepting new connection", ex); } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/ServerConnection.java0000664000175000017500000003504211757206346031632 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.nio.channels.SocketChannel; import java.security.Principal; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Response; import org.restlet.Server; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.util.StringUtils; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Generic HTTP-like server connection. * * @author Jerome Louvel */ public class ServerConnection extends Connection { /** * Constructor. * * @param helper * The parent connector helper. * @param socket * The underlying BIO socket. * @param socketChannel * The underlying NIO socket channel. * @throws IOException */ public ServerConnection(BaseHelper helper, Socket socket, SocketChannel socketChannel) throws IOException { super(helper, socket, socketChannel); } /** * Adds the response headers. * * @param response * The response to inspect. * @param headers * The headers series to update. */ protected void addResponseHeaders(Response response, Series headers) { HeaderUtils.addResponseHeaders(response, headers); } @Override public boolean canRead() { return super.canRead() && ((getInboundMessages().size() == 0) || isPipelining()); } /** * Asks the server connector to immediately commit the given response * associated to this request, making it ready to be sent back to the * client. Note that all server connectors don't necessarily support this * feature. * * @param response * The response to commit. */ public void commit(Response response) { getHelper().getOutboundMessages().add(response); } /** * Creates a new request. * * @param context * The current context. * @param connection * The associated connection. * @param methodName * The method name. * @param resourceUri * The target resource URI. * @param version * The protocol version. * @param headers * The request headers. * @param entity * The request entity. * @param confidential * True if received confidentially. * @param userPrincipal * The user principal. * @return The created request. */ protected ConnectedRequest createRequest(Context context, ServerConnection connection, String methodName, String resourceUri, String version, Series headers, Representation entity, boolean confidential, Principal userPrincipal) { return new ConnectedRequest(getHelper().getContext(), this, Method.valueOf(methodName), resourceUri, version, headers, createInboundEntity(headers), false, null); } /** * Reads the next request sent by the client if available. Note that the * optional entity is not fully read. * * @throws IOException */ @Override protected void readMessage() throws IOException { ConnectedRequest request = null; String requestMethod = null; String requestUri = null; String version = null; Series headers = null; // Parse the request method StringBuilder sb = new StringBuilder(); int next = getInboundStream().read(); while ((next != -1) && !HeaderUtils.isSpace(next)) { sb.append((char) next); next = getInboundStream().read(); } if (next == -1) { throw new IOException( "Unable to parse the request method. End of stream reached too early."); } requestMethod = sb.toString(); sb.delete(0, sb.length()); // Parse the request URI next = getInboundStream().read(); while ((next != -1) && !HeaderUtils.isSpace(next)) { sb.append((char) next); next = getInboundStream().read(); } if (next == -1) { throw new IOException( "Unable to parse the request URI. End of stream reached too early."); } requestUri = sb.toString(); if ((requestUri == null) || (requestUri.equals(""))) { requestUri = "/"; } sb.delete(0, sb.length()); // Parse the protocol version next = getInboundStream().read(); while ((next != -1) && !HeaderUtils.isCarriageReturn(next)) { sb.append((char) next); next = getInboundStream().read(); } if (next == -1) { throw new IOException( "Unable to parse the protocol version. End of stream reached too early."); } next = getInboundStream().read(); if (HeaderUtils.isLineFeed(next)) { version = sb.toString(); sb.delete(0, sb.length()); // Parse the headers Parameter header = HeaderReader.readHeader(getInboundStream(), sb); while (header != null) { if (headers == null) { headers = new Form(); } headers.add(header); header = HeaderReader.readHeader(getInboundStream(), sb); } } else { throw new IOException( "Unable to parse the protocol version. The carriage return must be followed by a line feed."); } // Check if the client wants to close the connection if (HeaderUtils.isConnectionClose(headers)) { setState(ConnectionState.CLOSING); } // Create the request and the associated response request = createRequest(getHelper().getContext(), this, requestMethod, requestUri, version, headers, createInboundEntity(headers), false, null); Response response = getHelper().createResponse(request); // Update the response response.getServerInfo().setAddress( getHelper().getHelped().getAddress()); response.getServerInfo().setPort(getHelper().getHelped().getPort()); if (request != null) { if (request.isExpectingResponse()) { // Add it to the connection queue getInboundMessages().add(response); } // Add it to the helper queue getHelper().getInboundMessages().add(response); } } /** * Write the given response on the socket. * * @param response * The response to write. */ @Override protected void writeMessage(Response response) { // Prepare the headers Series headers = new Form(); ConnectedRequest request = (ConnectedRequest) response.getRequest(); try { if ((request.getMethod() != null) && request.getMethod().equals(Method.HEAD)) { addEntityHeaders(response.getEntity(), headers); response.setEntity(null); } else if (Method.GET.equals(request.getMethod()) && Status.SUCCESS_OK.equals(response.getStatus()) && (!response.isEntityAvailable())) { addEntityHeaders(response.getEntity(), headers); getLogger() .warning( "A response with a 200 (Ok) status should have an entity. Make sure that resource \"" + request.getResourceRef() + "\" returns one or sets the status to 204 (No content)."); } else if (response.getStatus().equals(Status.SUCCESS_NO_CONTENT)) { addEntityHeaders(response.getEntity(), headers); if (response.isEntityAvailable()) { getLogger() .fine("Responses with a 204 (No content) status generally don't have an entity. Only adding entity headers for resource \"" + request.getResourceRef() + "\"."); response.setEntity(null); } } else if (response.getStatus() .equals(Status.SUCCESS_RESET_CONTENT)) { if (response.isEntityAvailable()) { getLogger() .warning( "Responses with a 205 (Reset content) status can't have an entity. Ignoring the entity for resource \"" + request.getResourceRef() + "\"."); response.setEntity(null); } } else if (response.getStatus().equals( Status.REDIRECTION_NOT_MODIFIED)) { if (response.getEntity() != null) { HeaderUtils.addNotModifiedEntityHeaders( response.getEntity(), headers); response.setEntity(null); } } else if (response.getStatus().isInformational()) { if (response.isEntityAvailable()) { getLogger() .warning( "Responses with an informational (1xx) status can't have an entity. Ignoring the entity for resource \"" + request.getResourceRef() + "\"."); response.setEntity(null); } addGeneralHeaders(response, headers); addResponseHeaders(response, headers); } else { addGeneralHeaders(response, headers); addResponseHeaders(response, headers); addEntityHeaders(response.getEntity(), headers); if (!response.isEntityAvailable()) { if ((response.getEntity() != null) && response.getEntity().getSize() != 0) { getLogger() .warning( "A response with an unavailable and non empty entity was returned. Ignoring the entity for resource \"" + response.getRequest() .getResourceRef() + "\"."); } response.setEntity(null); } } // Write the response to the client writeMessage(response, headers); } catch (Exception e) { getLogger().log(Level.FINE, "An exception occured while writing the response", e); response.setStatus(Status.SERVER_ERROR_INTERNAL, "An exception occured while writing the response"); response.setEntity(null); try { writeMessage(response, headers); } catch (IOException ioe) { getLogger().log(Level.FINE, "Unable to send error response", ioe); } } finally { // Make sure that the optional request entity is released if (!response.getStatus().isInformational() && (request.getEntity() != null)) { try { request.getEntity().exhaust(); } catch (IOException e) { getLogger().log(Level.FINE, "Unable to exhaust request entity", e); } finally { request.getEntity().release(); } } if (response.getOnSent() != null) { response.getOnSent().handle(request, response); } // Free the connection outbound for next responses getOutboundMessages().poll(); setOutboundBusy(false); } } @Override protected void writeMessageHeadLine(Response response, OutputStream headStream) throws IOException { Protocol protocol = response.getRequest().getProtocol(); String protocolVersion = protocol.getVersion(); String version = protocol.getTechnicalName() + '/' + ((protocolVersion == null) ? "1.1" : protocolVersion); headStream.write(StringUtils.getAsciiBytes(version)); headStream.write(' '); headStream.write(StringUtils.getAsciiBytes(Integer.toString(response .getStatus().getCode()))); headStream.write(' '); if (response.getStatus().getName() != null) { headStream.write(StringUtils.getLatin1Bytes(response.getStatus() .getName())); } else { headStream.write(StringUtils.getAsciiBytes(("Status " + response .getStatus().getCode()))); } headStream.write(13); // CR headStream.write(10); // LF } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/BaseClientHelper.java0000664000175000017500000006567011757206346031527 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.SocketChannel; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.util.Iterator; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.net.SocketFactory; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.io.NioUtils; /** * Base client helper based on NIO blocking sockets. Here is the list of * parameters that are supported. They should be set in the Client's context * before it is started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    proxyHostStringSystem property "http.proxyHost"The host name of the HTTP proxy.
    proxyPortintSystem property "http.proxyPort"The port of the HTTP proxy.
    tcpNoDelaybooleanfalseIndicate if Nagle's TCP_NODELAY algorithm should be used.
    keystorePathString${user.home}/.keystoreSSL keystore path.
    keystorePasswordStringSystem property "javax.net.ssl.keyStorePassword"SSL keystore password.
    keystoreTypeStringJKSSSL keystore type
    keyPasswordStringSystem property "javax.net.ssl.keyStorePassword"SSL key password.
    certAlgorithmStringSunX509SSL certificate algorithm.
    secureRandomAlgorithmStringnull (see java.security.SecureRandom)Name of the RNG algorithm. (see java.security.SecureRandom class).
    securityProviderStringnull (see javax.net.ssl.SSLContext)Java security provider name (see java.security.Provider class).
    sslProtocolStringTLSSSL protocol.
    truststoreTypeStringSystem property "javax.net.ssl.trustStoreType"Trust store type
    truststorePathStringnullPath to trust store
    truststorePasswordStringSystem property "javax.net.ssl.trustStorePassword"Trust store password
    * * @author Jerome Louvel */ public class BaseClientHelper extends BaseHelper { private static final String CONNECTOR_LATCH = "org.restlet.engine.http.connector.latch"; /** The regular socket factory. */ private volatile SocketFactory regularSocketFactory; /** The secure socket factory. */ private volatile SocketFactory secureSocketFactory; /** * Constructor. * * @param connector * The helped client connector. */ public BaseClientHelper(Client connector) { super(connector, true); this.regularSocketFactory = null; this.secureSocketFactory = null; } @Override protected Connection createConnection(BaseHelper helper, Socket socket, SocketChannel socketChannel) throws IOException { return new ClientConnection(helper, socket, socketChannel); } /** * Creates a properly configured secure socket factory. * * @return Properly configured secure socket factory. * @throws IOException * @throws GeneralSecurityException */ protected SocketFactory createSecureSocketFactory() throws IOException, GeneralSecurityException { // Retrieve the configuration variables String certAlgorithm = getCertAlgorithm(); String keystorePath = getKeystorePath(); String keystorePassword = getKeystorePassword(); String keyPassword = getKeyPassword(); String truststoreType = getTruststoreType(); String truststorePath = getTruststorePath(); String truststorePassword = getTruststorePassword(); String secureRandomAlgorithm = getSecureRandomAlgorithm(); String securityProvider = getSecurityProvider(); // Initialize a key store InputStream keystoreInputStream = null; if ((keystorePath != null) && (new File(keystorePath).exists())) { keystoreInputStream = new FileInputStream(keystorePath); } KeyStore keystore = null; if (keystoreInputStream != null) { try { keystore = KeyStore.getInstance(getKeystoreType()); keystore.load( keystoreInputStream, keystorePassword == null ? null : keystorePassword .toCharArray()); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to load the key store", ioe); keystore = null; } } KeyManager[] keyManagers = null; if ((keystore != null) && (keyPassword != null)) { // Initialize a key manager KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(certAlgorithm); keyManagerFactory.init(keystore, keyPassword.toCharArray()); keyManagers = keyManagerFactory.getKeyManagers(); } // Initialize the trust store InputStream truststoreInputStream = null; if ((truststorePath != null) && (new File(truststorePath).exists())) { truststoreInputStream = new FileInputStream(truststorePath); } KeyStore truststore = null; if ((truststoreType != null) && (truststoreInputStream != null)) { try { truststore = KeyStore.getInstance(truststoreType); truststore.load( truststoreInputStream, truststorePassword == null ? null : truststorePassword .toCharArray()); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to load the trust store", ioe); truststore = null; } } TrustManager[] trustManagers = null; if (truststore != null) { // Initialize the trust manager TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(certAlgorithm); trustManagerFactory.init(truststore); trustManagers = trustManagerFactory.getTrustManagers(); } // Initialize the SSL context SecureRandom secureRandom = secureRandomAlgorithm == null ? null : SecureRandom.getInstance(secureRandomAlgorithm); SSLContext context = securityProvider == null ? SSLContext .getInstance(getSslProtocol()) : SSLContext.getInstance( getSslProtocol(), securityProvider); context.init(keyManagers, trustManagers, secureRandom); // Return the SSL socket factory return context.getSocketFactory(); } /** * Creates the socket that will be used to send the request and get the * response. This method is called by {@link #getBestConnection(Request)} * when a new connection is to be created. By default, calls the * {@link #createSocket(boolean, String, int)} method. * * @param secure * Indicates if messages will be exchanged confidentially, for * example via a SSL-secured connection. * @param socketAddress * The holder of a host/port pair. * @return The created socket. * @throws UnknownHostException * @throws IOException */ protected Socket createSocket(boolean secure, InetSocketAddress socketAddress) throws UnknownHostException, IOException { return createSocket(secure, socketAddress.getHostName(), socketAddress.getPort()); } /** * Creates the socket that will be used to send the request and get the * response. * * @param secure * Indicates if messages will be exchanged confidentially, for * example via a SSL-secured connection. * @param hostDomain * The target host domain name. * @param hostPort * The target host port. * @return The created socket. * @throws UnknownHostException * @throws IOException */ protected Socket createSocket(boolean secure, String hostDomain, int hostPort) throws UnknownHostException, IOException { Socket result = null; SocketFactory factory = getSocketFactory(secure); if (factory != null) { result = factory.createSocket(); InetSocketAddress address = new InetSocketAddress(hostDomain, hostPort); result.connect(address, getConnectTimeout()); result.setTcpNoDelay(getTcpNoDelay()); } return result; } /** * Creates a normal or secure socket factory. * * @param secure * Indicates if the sockets should be secured. * @return A normal or secure socket factory. */ protected SocketFactory createSocketFactory(boolean secure) { SocketFactory result = null; if (secure) { try { return createSecureSocketFactory(); } catch (IOException ex) { getLogger().log( Level.SEVERE, "Could not create secure socket factory: " + ex.getMessage(), ex); } catch (GeneralSecurityException ex) { getLogger().log( Level.SEVERE, "Could not create secure socket factory: " + ex.getMessage(), ex); } } else { result = SocketFactory.getDefault(); } return result; } /** * Tries to reuse an existing connection for the given request, or creates a * new one. It may return null if the maximum number of connections per host * or in general is reached. * * @param request * The request to handle. * @return An existing connection able to handle the request or new one. * @throws UnknownHostException * @throws IOException */ protected Connection getBestConnection(Request request) throws UnknownHostException, IOException { Connection result = null; // Try to reuse an existing connection for the same host and // port int hostConnectionCount = 0; int bestCount = 0; boolean foundConn = false; // Determine the target host domain and port of the request. InetSocketAddress socketAddress = getSocketAddress(request); if (socketAddress == null) { getLogger() .log(Level.WARNING, "Unable to create a socket address related to the request."); } else { // Associate the given request to the first available connection // opened on the same host domain and port. for (Iterator> iterator = getConnections() .iterator(); !foundConn && iterator.hasNext();) { ClientConnection currConn = (ClientConnection) iterator.next(); if (socketAddress.getAddress().equals( currConn.getSocket().getInetAddress()) && socketAddress.getPort() == currConn.getSocket() .getPort()) { if (currConn.getState().equals(ConnectionState.OPEN) && currConn.canEnqueue()) { result = currConn; foundConn = true; } else { // Assign the request to the busy connection that // handles the less number of messages. This is usefull // in case the maximum number of connections has been // reached. As a drawback, the message will only be // handled as soon as possible. int currCount = currConn.getOutboundMessages().size(); if (bestCount > currCount) { bestCount = currCount; result = currConn; } hostConnectionCount++; } } } // No connection has been found, try to create a new one that will // handle the message soon. if (!foundConn && ((getMaxTotalConnections() == -1) || (getConnections() .size() < getMaxTotalConnections())) && ((getMaxConnectionsPerHost() == -1) || (hostConnectionCount < getMaxConnectionsPerHost()))) { // Create a new connection result = createConnection(this, createSocket(request.isConfidential(), socketAddress), null); result.open(); } } return result; } /** * Returns the SSL certificate algorithm. * * @return The SSL certificate algorithm. */ public String getCertAlgorithm() { return getHelpedParameters().getFirstValue("certAlgorithm", "SunX509"); } /** * Returns the connection timeout. * * @return The connection timeout. */ public int getConnectTimeout() { return getHelped().getConnectTimeout(); } /** * Returns the SSL key password. * * @return The SSL key password. */ public String getKeyPassword() { return getHelpedParameters().getFirstValue("keyPassword", System.getProperty("javax.net.ssl.keyStorePassword")); } /** * Returns the SSL keystore password. * * @return The SSL keystore password. */ public String getKeystorePassword() { return getHelpedParameters().getFirstValue("keystorePassword", System.getProperty("javax.net.ssl.keyStorePassword")); } /** * Returns the SSL keystore path. * * @return The SSL keystore path. */ public String getKeystorePath() { return getHelpedParameters().getFirstValue("keystorePath", System.getProperty("user.home") + File.separator + ".keystore"); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ public String getKeystoreType() { return getHelpedParameters().getFirstValue("keystoreType", "JKS"); } /** * Returns the host name of the HTTP proxy, if specified. * * @return the host name of the HTTP proxy, if specified. */ public String getProxyHost() { return getHelpedParameters().getFirstValue("proxyHost", System.getProperty("http.proxyHost")); } /** * Returns the port of the HTTP proxy, if specified, 3128 otherwise. * * @return the port of the HTTP proxy. */ public int getProxyPort() { String proxyPort = getHelpedParameters().getFirstValue("proxyPort", System.getProperty("http.proxyPort")); if (proxyPort == null) { proxyPort = "3128"; } return Integer.parseInt(proxyPort); } /** * Returns the regular socket factory. * * @return The regular socket factory. */ public SocketFactory getRegularSocketFactory() { return regularSocketFactory; } /** * Returns the name of the RNG algorithm. * * @return The name of the RNG algorithm. */ public String getSecureRandomAlgorithm() { return getHelpedParameters().getFirstValue("secureRandomAlgorithm", null); } /** * Returns the secure socket factory. * * @return The secure socket factory. */ public SocketFactory getSecureSocketFactory() { return secureSocketFactory; } /** * Returns the Java security provider name. * * @return The Java security provider name. */ public String getSecurityProvider() { return getHelpedParameters().getFirstValue("securityProvider", null); } /** * Returns an IP socket address representing the target host domain and port * for a given request. If the helper relies on a proxy, the socket * represents the domain and port of the proxy host. Used by the * {@link #getBestConnection(Request)} method. * * @param request * The given request * @return The IP socket address representing the target host domain and * port for a given request. * @throws UnknownHostException * If the proxy port is invalid or the host unresolved. */ protected InetSocketAddress getSocketAddress(Request request) throws UnknownHostException { InetSocketAddress result = null; String hostDomain = null; int hostPort = 0; // Does this helper relies on a proxy? String proxyDomain = getProxyHost(); if (proxyDomain != null && !"".equals(proxyDomain)) { hostDomain = proxyDomain; try { hostPort = getProxyPort(); } catch (NumberFormatException nfe) { getLogger().log(Level.WARNING, "The proxy port must be a valid numeric value.", nfe); throw new UnknownHostException(); } } else { // Resolve relative references Reference resourceRef = request.getResourceRef().isRelative() ? request .getResourceRef().getTargetRef() : request.getResourceRef(); // Extract the host info hostDomain = resourceRef.getHostDomain(); hostPort = resourceRef.getHostPort(); if (hostPort == -1) { if (resourceRef.getSchemeProtocol() != null) { hostPort = resourceRef.getSchemeProtocol().getDefaultPort(); } else { hostPort = getProtocols().get(0).getDefaultPort(); } } } if (hostDomain != null) { result = new InetSocketAddress(hostDomain, hostPort); if (result != null && result.getAddress() == null) { throw new UnknownHostException(hostDomain); } } return result; } /** * Returns the socket factory. * * @param secure * Indicates if a factory for secure sockets is expected. * @return The socket factory. */ public SocketFactory getSocketFactory(boolean secure) { return secure ? getSecureSocketFactory() : getRegularSocketFactory(); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ public String getSslProtocol() { return getHelpedParameters().getFirstValue("sslProtocol", "TLS"); } /** * Indicates if the protocol will use Nagle's algorithm * * @return True to enable TCP_NODELAY, false to disable. * @see java.net.Socket#setTcpNoDelay(boolean) */ public boolean getTcpNoDelay() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "tcpNoDelay", "false")); } /** * Returns the SSL trust store password. * * @return The SSL trust store password. */ public String getTruststorePassword() { return getHelpedParameters().getFirstValue("truststorePassword", System.getProperty("javax.net.ssl.keyStorePassword")); } /** * Returns the SSL trust store path. * * @return The SSL trust store path. */ public String getTruststorePath() { return getHelpedParameters().getFirstValue("truststorePath", null); } /** * Returns the SSL trust store type. * * @return The SSL trust store type. */ public String getTruststoreType() { return getHelpedParameters().getFirstValue("truststoreType", System.getProperty("javax.net.ssl.trustStoreType")); } @Override public void handle(Request request, Response response) { try { if (request.getOnResponse() == null) { // Synchronous mode CountDownLatch latch = new CountDownLatch(1); request.getAttributes().put(CONNECTOR_LATCH, latch); // Add the message to the outbound queue for processing getOutboundMessages().add(response); // Await on the latch if (!latch.await(NioUtils.NIO_TIMEOUT, TimeUnit.MILLISECONDS)) { // Timeout detected response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, "The calling thread timed out while waiting for a response to unblock it."); } } else { // Add the message to the outbound queue for processing getOutboundMessages().add(response); } } catch (Exception e) { getLogger().log( Level.INFO, "Error while handling a " + request.getProtocol().getName() + " client request", e); response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, e); } } @Override public void handleInbound(Response response) { if (response != null) { if (response.getRequest().getOnResponse() != null) { response.getRequest().getOnResponse() .handle(response.getRequest(), response); } if (!response.getStatus().isInformational()) { unblock(response); } } } @Override public void handleOutbound(Response response) { if ((response != null) && (response.getRequest() != null)) { try { Connection bestConn = getBestConnection(response .getRequest()); if (bestConn != null) { bestConn.getOutboundMessages().add(response); getConnections().add(bestConn); if (!response.getRequest().isExpectingResponse()) { // Attempt to directly write the response, preventing a // thread context switch bestConn.writeMessages(); // Unblock the possibly waiting thread. // NB : the request may not be written at this time. unblock(response); } } else { getLogger().log(Level.WARNING, "Unable to find a connection to send the request"); response.setStatus(Status.CONNECTOR_ERROR_COMMUNICATION, "Unable to find a connection to send the request"); unblock(response); } } catch (Throwable t) { getLogger() .log(Level.FINE, "An error occured during the communication with the remote server.", t); response.setStatus(Status.CONNECTOR_ERROR_COMMUNICATION, t); unblock(response); } } } /** * Sets the regular socket factory. * * @param regularSocketFactory * The regular socket factory. */ public void setRegularSocketFactory(SocketFactory regularSocketFactory) { this.regularSocketFactory = regularSocketFactory; } /** * Sets the secure socket factory. * * @param secureSocketFactory * The secure socket factory. */ public void setSecureSocketFactory(SocketFactory secureSocketFactory) { this.secureSocketFactory = secureSocketFactory; } @Override public synchronized void start() throws Exception { setRegularSocketFactory(createSocketFactory(false)); setSecureSocketFactory(createSocketFactory(true)); super.start(); } @Override public synchronized void stop() throws Exception { setRegularSocketFactory(null); setSecureSocketFactory(null); super.stop(); } /** * Unblocks the thread that handles the given request/response pair. * * @param response * The response. */ private void unblock(Response response) { CountDownLatch latch = (CountDownLatch) response.getRequest() .getAttributes().get(CONNECTOR_LATCH); if (latch != null) { latch.countDown(); } } @Override public boolean isProxying() { return getProxyHost() != null; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/BaseServerHelper.java0000664000175000017500000002403211757206346031542 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.restlet.Request; import org.restlet.Response; import org.restlet.Server; import org.restlet.engine.io.NioUtils; import org.restlet.engine.log.LoggingThreadFactory; /** * Base server helper based on NIO blocking sockets. Here is the list of * parameters that are supported. They should be set in the Server's context * before it is started: * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    useForwardedForHeaderbooleanfalseLookup the "X-Forwarded-For" header supported by popular proxies and * caches and uses it to populate the Request.getClientAddresses() method * result. This information is only safe for intermediary components within your * local network. Other addresses could easily be changed by setting a fake * header and should not be trusted for serious security checks.
    * * @author Jerome Louvel */ public abstract class BaseServerHelper extends BaseHelper { /** The acceptor task. */ private volatile Acceptor acceptor; /** The connection acceptor service. */ private volatile ExecutorService acceptorService; /** The synchronization aid between listener and handler service. */ private volatile CountDownLatch latch; /** The server socket. */ private volatile ServerSocket serverSocket; /** * Constructor. * * @param server * The server to help. */ public BaseServerHelper(Server server) { super(server, false); // Clear the ephemeral port getAttributes().put("ephemeralPort", -1); } /** * Creates the handler service. * * @return The handler service. */ protected ExecutorService createAcceptorService() { return Executors.newSingleThreadExecutor(new LoggingThreadFactory( getLogger(), false)); } /** * Create a server socket channel and bind it to the given address * * @return Bound server socket channel. * @throws IOException */ protected ServerSocket createServerSocket() throws IOException { ServerSocket result = new ServerSocket(); result.setReuseAddress(true); result.bind(createSocketAddress()); return result; } /** * Creates a socket address to listen on. * * @return The created socket address. * @throws IOException */ protected SocketAddress createSocketAddress() throws IOException { if (getHelped().getAddress() == null) { return new InetSocketAddress(getHelped().getPort()); } return new InetSocketAddress(getHelped().getAddress(), getHelped() .getPort()); } /** * Returns the server socket. * * @return The server socket. */ public ServerSocket getServerSocket() { return serverSocket; } /** * Handles a call by invoking the helped Server's * {@link Server#handle(Request, Response)} method. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { super.handle(request, response); getHelped().handle(request, response); } @Override public void handleInbound(Response response) { if ((response != null) && (response.getRequest() != null)) { ConnectedRequest request = (ConnectedRequest) response.getRequest(); // Effectively handle the request handle(request, response); if (!response.isCommitted() && response.isAutoCommitting()) { getOutboundMessages().add(response); response.setCommitted(true); } } handleNextOutbound(); } @Override public void handleOutbound(Response response) { if (response != null) { ConnectedRequest request = (ConnectedRequest) response.getRequest(); ServerConnection connection = request.getConnection(); if (request.isExpectingResponse()) { // Check if the response is indeed the next one to be written // for this connection Response nextResponse = connection.getInboundMessages().peek(); if ((nextResponse != null) && (nextResponse.getRequest() == request)) { // Add the response to the outbound queue connection.getOutboundMessages().add(response); // Check if a final response was received for the request if (!response.getStatus().isInformational()) { // Remove the matching request from the inbound queue connection.getInboundMessages().remove(nextResponse); } // Attempt to directly write the response, preventing a // thread context switch connection.writeMessages(); } else { // Put the response at the end of the queue getOutboundMessages().add(response); } } else { // The request expects no response, the connection is free to // read. connection.setInboundBusy(false); } } } @Override public boolean isProxying() { return false; } /** * Sets the ephemeral port in the attributes map if necessary. * * @param localPort * The ephemeral local port. */ public void setEphemeralPort(int localPort) { // If an ephemeral port is used, make sure we update the attribute for // the API if (getHelped().getPort() == 0) { getAttributes().put("ephemeralPort", localPort); } } /** * Sets the ephemeral port in the attributes map if necessary. * * @param socket * The bound server socket. */ public void setEphemeralPort(ServerSocket socket) { setEphemeralPort(socket.getLocalPort()); } @Override public synchronized void start() throws Exception { super.start(); // Create the thread services this.acceptorService = createAcceptorService(); // Create the server socket this.serverSocket = createServerSocket(); // Sets the ephemeral port is necessary setEphemeralPort(this.serverSocket); // Start the socket listener service this.latch = new CountDownLatch(1); this.acceptor = new Acceptor(this, this.latch); this.acceptorService.submit(this.acceptor); // Wait for the listener to start up and count down the latch // This blocks until the server is ready to receive connections try { if (!this.latch.await(NioUtils.NIO_TIMEOUT, TimeUnit.MILLISECONDS)) { // Timeout detected getLogger() .warning( "The calling thread timed out while waiting for the connector to be ready to accept connections."); } } catch (InterruptedException ex) { getLogger() .log(Level.WARNING, "Interrupted while waiting for starting latch. Stopping...", ex); stop(); } } @Override public synchronized void stop() throws Exception { // Stop accepting connections if (this.acceptorService != null) { try { // This must be forcefully interrupted because the thread // is most likely blocked on channel.accept() getServerSocket().close(); this.acceptor.setRunning(false); this.acceptorService.shutdown(); this.acceptorService.awaitTermination(30, TimeUnit.SECONDS); } catch (Exception ex) { getLogger() .log(Level.FINE, "Interruption while shutting down the acceptor service", ex); } } // Close the server socket if (this.serverSocket != null) { this.serverSocket.close(); } super.stop(); // Clear the ephemeral port getAttributes().put("ephemeralPort", -1); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/Connection.java0000664000175000017500000007345511757206346030455 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; import java.security.cert.Certificate; import java.util.Arrays; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import org.restlet.Connector; import org.restlet.Message; import org.restlet.Response; import org.restlet.data.Parameter; import org.restlet.engine.ConnectorHelper; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.http.io.ChunkedInputStream; import org.restlet.engine.http.io.ChunkedOutputStream; import org.restlet.engine.http.io.ClosingInputStream; import org.restlet.engine.http.io.InboundStream; import org.restlet.engine.http.io.Notifiable; import org.restlet.engine.http.io.OutboundStream; import org.restlet.engine.http.io.SizedInputStream; import org.restlet.engine.io.TraceInputStream; import org.restlet.engine.io.TraceOutputStream; import org.restlet.engine.security.SslUtils; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.ReadableRepresentation; import org.restlet.representation.Representation; import org.restlet.service.ConnectorService; import org.restlet.util.Series; /** * A network connection though which requests and responses are exchanged by * connectors. * * @param * The parent connector type. * @author Jerome Louvel */ public abstract class Connection implements Notifiable { /** The parent connector helper. */ private final BaseHelper helper; /** Indicates if the input of the socket is busy. */ private volatile boolean inboundBusy; /** The queue of inbound messages. */ private final Queue inboundMessages; /** The inbound BIO stream. */ private final InputStream inboundStream; /** Indicates if the output of the socket is busy. */ private volatile boolean outboundBusy; /** The queue of outbound messages. */ private final Queue outboundMessages; /** The outbound BIO stream. */ private final OutputStream outboundStream; /** Indicates if the connection should be persisted across calls. */ private volatile boolean persistent; /** Indicates if idempotent sequences of requests can be pipelined. */ private volatile boolean pipelining; /** The underlying BIO socket. */ private final Socket socket; /** The underlying NIO socket channel. */ private final SocketChannel socketChannel; /** The state of the connection. */ private volatile ConnectionState state; /** * Constructor. * * @param helper * The parent connector helper. * @param socket * The underlying BIO socket. * @param socketChannel * The underlying NIO socket channel. * @throws IOException */ public Connection(BaseHelper helper, Socket socket, SocketChannel socketChannel) throws IOException { this.helper = helper; this.inboundMessages = new ConcurrentLinkedQueue(); this.outboundMessages = new ConcurrentLinkedQueue(); this.persistent = helper.isPersistingConnections(); this.pipelining = helper.isPipeliningConnections(); this.state = ConnectionState.OPENING; this.socket = socket; this.socketChannel = socketChannel; this.inboundBusy = false; this.outboundBusy = false; if (getHelper().isTracing()) { this.inboundStream = new TraceInputStream( new InboundStream(getSocket().getInputStream(), helper.getInboundBufferSize())); this.outboundStream = new TraceOutputStream(new OutboundStream( getSocket().getOutputStream(), helper.getOutboundBufferSize())); } else { this.inboundStream = new InboundStream( getSocket().getInputStream(), helper.getInboundBufferSize()); this.outboundStream = new OutboundStream(getSocket() .getOutputStream(), helper.getOutboundBufferSize()); } } /** * Adds the entity headers for the given response. * * @param entity * The entity to inspect. */ protected void addEntityHeaders(Representation entity, Series headers) { HeaderUtils.addEntityHeaders(entity, headers); } /** * Adds the general headers from the {@link Message} to the {@link Series}. * * @param message * The source {@link Message}. * @param headers * The target headers {@link Series}. */ protected void addGeneralHeaders(Message message, Series headers) { if (!isPersistent()) { headers.set(HeaderConstants.HEADER_CONNECTION, "close", true); } if (shouldBeChunked(message.getEntity())) { headers.add(HeaderConstants.HEADER_TRANSFER_ENCODING, "chunked"); } HeaderUtils.addGeneralHeaders(message, headers); } /** * Indicates if the connection's socket can be read for inbound data. * * @return True if the connection's socket can be read for inbound data. * @throws IOException */ public boolean canRead() { return (getState() == ConnectionState.OPEN) && !isInboundBusy(); } /** * Indicates if the connection's socket can be written for outbound data. * * @return True if the connection's socket can be written for outbound data. * @throws IOException */ public boolean canWrite() { return (getState() == ConnectionState.OPEN) && !isOutboundBusy() && (getOutboundMessages().size() > 0); } /** * Closes the connection. By default, set the state to * {@link ConnectionState#CLOSED}. */ public void close() { try { if (!getSocket().isClosed()) { // Flush the output stream getSocket().getOutputStream().flush(); if (!(getSocket() instanceof SSLSocket)) { getSocket().shutdownInput(); getSocket().shutdownOutput(); } } } catch (IOException ex) { getLogger().log(Level.FINE, "Unable to properly shutdown socket", ex); } try { if (!getSocket().isClosed()) { getSocket().close(); } } catch (IOException ex) { getLogger().log(Level.FINE, "Unable to properly close socket", ex); } finally { setState(ConnectionState.CLOSED); } } /** * Returns the inbound message entity if available. * * @param headers * The headers to use. * @return The inbound message if available. */ public Representation createInboundEntity(Series headers) { Representation result = null; long contentLength = HeaderUtils.getContentLength(headers); boolean chunkedEncoding = HeaderUtils.isChunkedEncoding(headers); // In some cases there is an entity without a content-length header boolean connectionClosed = HeaderUtils.isConnectionClose(headers); // Create the representation if ((contentLength != Representation.UNKNOWN_SIZE && contentLength != 0) || chunkedEncoding || connectionClosed) { InputStream inboundEntityStream = getInboundEntityStream( contentLength, chunkedEncoding); ReadableByteChannel inboundEntityChannel = getInboundEntityChannel( contentLength, chunkedEncoding); if (inboundEntityStream != null) { result = new InputRepresentation(inboundEntityStream, null, contentLength) { @Override public String getText() throws IOException { try { return super.getText(); } catch (IOException ioe) { throw ioe; } finally { release(); } } @Override public void release() { if (getHelper().isTracing()) { synchronized (System.out) { System.out.println("\n"); } } super.release(); setInboundBusy(false); } }; } else if (inboundEntityChannel != null) { result = new ReadableRepresentation(inboundEntityChannel, null, contentLength) { @Override public void release() { super.release(); setInboundBusy(false); } }; } result.setSize(contentLength); } else { result = new EmptyRepresentation(); // Mark the inbound as free so new messages can be read if possible setInboundBusy(false); } if (headers != null) { try { result = HeaderUtils.extractEntityHeaders(headers, result); } catch (Throwable t) { getLogger().log(Level.WARNING, "Error while parsing entity headers", t); } } return result; } /** * Returns the socket IP address. * * @return The socket IP address. */ public String getAddress() { return (getSocket().getInetAddress() == null) ? null : getSocket() .getInetAddress().getHostAddress(); } /** * Returns the parent connector helper. * * @return The parent connector helper. */ public BaseHelper getHelper() { return helper; } /** * Returns the inbound message entity channel if it exists. * * @param size * The expected entity size or -1 if unknown. * * @return The inbound message entity channel if it exists. */ public ReadableByteChannel getInboundEntityChannel(long size, boolean chunked) { return null; } /** * Returns the inbound message entity stream if it exists. * * @param size * The expected entity size or -1 if unknown. * * @return The inbound message entity stream if it exists. */ public InputStream getInboundEntityStream(long size, boolean chunked) { InputStream result = null; if (chunked) { result = new ChunkedInputStream(this, getInboundStream()); } else if (size >= 0) { result = new SizedInputStream(this, getInboundStream(), size); } else { result = new ClosingInputStream(this, getInboundStream()); } return result; } /** * Returns the queue of inbound messages. * * @return The queue of inbound messages. */ public Queue getInboundMessages() { return inboundMessages; } /** * Returns the inbound stream. * * @return The inbound stream. */ public InputStream getInboundStream() { return this.inboundStream; } /** * Returns the logger. * * @return The logger. */ public Logger getLogger() { return getHelper().getLogger(); } /** * Returns the response channel if it exists. * * @return The response channel if it exists. */ public WritableByteChannel getOutboundEntityChannel(boolean chunked) { return null; } /** * Returns the response entity stream if it exists. * * @return The response entity stream if it exists. */ public OutputStream getOutboundEntityStream(boolean chunked) { OutputStream result = getOutboundStream(); if (chunked) { result = new ChunkedOutputStream(result); } return result; } /** * Returns the queue of outbound messages. * * @return The queue of outbound messages. */ public Queue getOutboundMessages() { return outboundMessages; } /** * Returns the outbound stream. * * @return The outbound stream. */ public OutputStream getOutboundStream() { return this.outboundStream; } /** * Returns the socket port. * * @return The socket port. */ public int getPort() { return getSocket().getPort(); } /** * Returns the representation wrapping the given stream. * * @param stream * The response input stream. * @return The wrapping representation. */ protected Representation getRepresentation(InputStream stream) { return new InputRepresentation(stream, null); } /** * Returns the representation wrapping the given channel. * * @param channel * The response channel. * @return The wrapping representation. */ protected Representation getRepresentation( java.nio.channels.ReadableByteChannel channel) { return new org.restlet.representation.ReadableRepresentation(channel, null); } /** * Returns the underlying socket. * * @return The underlying socket. */ public Socket getSocket() { return socket; } /** * Returns the underlying NIO socket channel. * * @return The underlying NIO socket channel. */ public SocketChannel getSocketChannel() { return socketChannel; } /** * Returns the SSL cipher suite. * * @return The SSL cipher suite. */ public String getSslCipherSuite() { if (getSocket() instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) getSocket(); SSLSession sslSession = sslSocket.getSession(); if (sslSession != null) { return sslSession.getCipherSuite(); } } return null; } /** * Returns the list of client SSL certificates. * * @return The list of client SSL certificates. */ public List getSslClientCertificates() { if (getSocket() instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) getSocket(); SSLSession sslSession = sslSocket.getSession(); if (sslSession != null) { try { List clientCertificates = Arrays .asList(sslSession.getPeerCertificates()); return clientCertificates; } catch (SSLPeerUnverifiedException e) { getHelper().getLogger().log(Level.FINE, "Can't get the client certificates.", e); } } } return null; } /** * Returns the SSL key size, if available and accessible. * * @return The SSL key size, if available and accessible. */ public Integer getSslKeySize() { Integer keySize = null; String sslCipherSuite = getSslCipherSuite(); if (sslCipherSuite != null) { keySize = SslUtils.extractKeySize(sslCipherSuite); } return keySize; } /** * Returns the state of the connection. * * @return The state of the connection. */ public ConnectionState getState() { return state; } /** * Indicates if the connection is busy. * * @return True if the connection is busy. */ public boolean isBusy() { return isInboundBusy() || isOutboundBusy(); } /** * Indicates if it is a client-side connection. * * @return True if it is a client-side connection. */ public boolean isClientSide() { return getHelper().isClientSide(); } /** * Indicates if the input of the socket is busy. * * @return True if the input of the socket is busy. */ public boolean isInboundBusy() { return inboundBusy; } /** * Indicates if the output of the socket is busy. * * @return True if the output of the socket is busy. */ public boolean isOutboundBusy() { return outboundBusy; } /** * Indicates if the connection should be persisted across calls. * * @return True if the connection should be persisted across calls. */ public boolean isPersistent() { return persistent; } /** * Indicates if idempotent sequences of requests can be pipelined. * * @return True requests pipelining is enabled. */ public boolean isPipelining() { return pipelining; } /** * Indicates if it is a server-side connection. * * @return True if it is a server-side connection. */ public boolean isServerSide() { return getHelper().isServerSide(); } /** * Set the inbound busy state to false. */ public void onEndReached() { setInboundBusy(false); } /** * Set the inbound busy state to false and the connection state to * {@link ConnectionState#CLOSING}. */ public void onError() { setInboundBusy(false); setState(ConnectionState.CLOSING); } /** * Opens the connection. By default, set the state to * {@link ConnectionState#OPEN}. */ public void open() { try { setState(ConnectionState.OPEN); } catch (Exception ex) { getLogger().log(Level.FINE, "Unable to properly open socket", ex); } } /** * Reads the next message received via the inbound stream or channel. Note * that the optional entity is not fully read. * * @throws IOException */ protected abstract void readMessage() throws IOException; /** * Reads inbound messages from the socket. Only one message at a time if * pipelining isn't enabled. */ public void readMessages() { try { synchronized (this) { if (canRead()) { setInboundBusy(true); readMessage(); } } } catch (Throwable e) { if (ConnectionState.CLOSING != getState() && ConnectionState.CLOSED != getState()) { // Abnormal exception, close the connection and trace the event. // NB : may be due to a client that closes the connection. getLogger() .log(Level.FINE, "Error while reading a message. Closing the connection.", e.getMessage()); getLogger() .log(Level.FINE, "Error while reading a message. Closing the connection.", e); close(); } } // Immediately attempt to handle the next pending message, trying to // prevent a thread context switch. getHelper().handleNextInbound(); } /** * Indicates if the input of the socket is busy. * * @param inboundBusy * True if the input of the socket is busy. */ public void setInboundBusy(boolean inboundBusy) { this.inboundBusy = inboundBusy; } /** * Indicates if the output of the socket is busy. * * @param outboundBusy * True if the output of the socket is busy. */ public void setOutboundBusy(boolean outboundBusy) { this.outboundBusy = outboundBusy; } /** * Indicates if the connection should be persisted across calls. * * @param persistent * True if the connection should be persisted across calls. */ public void setPersistent(boolean persistent) { this.persistent = persistent; } /** * Indicates if idempotent sequences of requests can be pipelined. * * @param pipelining * True requests pipelining is enabled. */ public void setPipelining(boolean pipelining) { this.pipelining = pipelining; } /** * Sets the state of the connection. * * @param state * The state of the connection. */ public void setState(ConnectionState state) { this.state = state; } /** * Indicates if the entity should be chunked because its length is unknown. * * @param entity * The entity to analyze. * @return True if the entity should be chunked. */ protected boolean shouldBeChunked(Representation entity) { return (entity != null && entity.isAvailable()) && (entity.getSize() == Representation.UNKNOWN_SIZE); } /** * Write the given message on the socket. * * @param message * The message to write. */ protected abstract void writeMessage(Response message); /** * Writes the message and its headers. * * @param message * The message to write. * @throws IOException * if the Response could not be written to the network. */ protected void writeMessage(Response message, Series headers) throws IOException { if (message != null) { // Get the connector service to callback Representation entity = isClientSide() ? message.getRequest() .getEntity() : message.getEntity(); if (entity != null && !entity.isAvailable()) { entity = null; } ConnectorService connectorService = ConnectorHelper .getConnectorService(); if (connectorService != null) { connectorService.beforeSend(entity); } try { try { writeMessageHead(message, headers); } catch (IOException ioe) { getLogger() .log(Level.WARNING, "Exception while writing the message headers.", ioe); throw ioe; } if (entity != null) { boolean chunked = HeaderUtils.isChunkedEncoding(headers); OutputStream entityStream = null; WritableByteChannel entityChannel = null; try { // In order to workaround bug #6472250 // (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6472250), // it is very important to reuse that exact same // "entityStream" reference when manipulating the entity // stream, otherwise "insufficient data sent" exceptions // will occur in "fixedLengthMode" entityChannel = getOutboundEntityChannel(chunked); entityStream = getOutboundEntityStream(chunked); writeMessageBody(entity, entityChannel, entityStream); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Exception while writing the message body.", ioe); throw ioe; } try { if (entityStream != null) { entityStream.flush(); entityStream.close(); } } catch (IOException ioe) { // The stream was probably already closed by the // connector. Probably OK, low message priority. getLogger() .log(Level.FINE, "Exception while flushing and closing the entity stream.", ioe); } } } catch (IOException ioe) { throw ioe; } finally { if (entity != null) { entity.release(); } if (connectorService != null) { connectorService.afterSend(entity); } } } } /** * Effectively writes the message body. The entity to write is guaranteed to * be non null. Attempts to write the entity on the outbound channel or * outbound stream by default. * * @param entity * The representation to write as entity of the body. * @param entityChannel * The outbound entity channel or null if a stream is used. * @param entityStream * The outbound entity stream or null if a channel is used. * @throws IOException */ protected void writeMessageBody(Representation entity, WritableByteChannel entityChannel, OutputStream entityStream) throws IOException { if (entityChannel != null) { entity.write(entityChannel); } else if (entityStream != null) { entity.write(entityStream); entityStream.flush(); if (getHelper().isTracing()) { synchronized (System.out) { System.out.println("\n"); } } } } /** * Writes the message head to the given output stream. * * @param message * The source message. * @param headStream * The target stream. * @throws IOException */ protected void writeMessageHead(Response message, OutputStream headStream, Series headers) throws IOException { // Write the head line writeMessageHeadLine(message, headStream); // Write the headers for (Parameter header : headers) { HeaderUtils.writeHeaderLine(header, headStream); } // Write the end of the headers section headStream.write(13); // CR headStream.write(10); // LF headStream.flush(); } /** * Writes the message head. * * @param message * The message. * @param headers * The series of headers to write. * @throws IOException */ protected void writeMessageHead(Response message, Series headers) throws IOException { writeMessageHead(message, getOutboundStream(), headers); } /** * Writes the message head line to the given output stream. * * @param message * The source message. * @param headStream * The target stream. * @throws IOException */ protected abstract void writeMessageHeadLine(Response message, OutputStream headStream) throws IOException; /** * Writes outbound messages to the socket. Only one response at a time if * pipelining isn't enabled. */ public void writeMessages() { try { Response message = null; // We want to make sure that responses are written in order without // blocking other concurrent threads during the writing synchronized (this) { if (canWrite()) { message = getOutboundMessages().peek(); setOutboundBusy((message != null)); } } if (message != null) { writeMessage(message); // Try to close the connection immediately. if ((getState() == ConnectionState.CLOSING) && !isBusy()) { close(); } } } catch (Throwable e) { getLogger().log(Level.WARNING, "Error while writing an HTTP message: ", e.getMessage()); getLogger().log(Level.INFO, "Error while writing an HTTP message", e); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/connector/HttpServerHelper.java0000664000175000017500000000467011757206346031615 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.connector; import java.io.IOException; import java.net.Socket; import java.nio.channels.SocketChannel; import org.restlet.Server; import org.restlet.data.Protocol; /** * HTTP server helper based on NIO blocking sockets. * * @author Jerome Louvel */ public class HttpServerHelper extends BaseServerHelper { /** * Constructor. * * @param server * The server to help. */ public HttpServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTP); } @Override protected Connection createConnection(BaseHelper helper, Socket socket, SocketChannel socketChannel) throws IOException { return new ServerConnection(helper, socket, socketChannel); } @Override public synchronized void start() throws Exception { getLogger().info( "Starting the internal " + getProtocols().get(0).getName() + " server on port " + getHelped().getPort()); super.start(); } @Override public synchronized void stop() throws Exception { getLogger().info("Stopping the internal HTTP server"); super.stop(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/adapter/0000775000175000017500000000000011757206350025116 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/http/adapter/Adapter.java0000664000175000017500000000414411757206346027351 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.adapter; import java.util.logging.Logger; import org.restlet.Context; /** * Converter between high-level and low-level HTTP calls. * * @author Jerome Louvel */ public class Adapter { /** The context. */ private volatile Context context; /** * Constructor. * * @param context * The context to use. */ public Adapter(Context context) { this.context = context; } /** * Returns the context. * * @return The context. */ public Context getContext() { return this.context; } /** * Returns the logger. * * @return The logger. */ public Logger getLogger() { Logger result = (getContext() != null) ? getContext().getLogger() : null; return (result != null) ? result : Context.getCurrentLogger(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/adapter/package.html0000664000175000017500000000022411757206350027375 0ustar jamespagejamespage Adapters between low-level HTTP calls and high-level Restlet Request and Response objects.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java0000664000175000017500000002632111757206346030541 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.adapter; import java.io.IOException; import java.security.cert.Certificate; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.engine.http.HttpRequest; import org.restlet.engine.http.HttpResponse; import org.restlet.engine.http.ServerCall; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.representation.Representation; import org.restlet.util.Series; // [excludes gwt] /** * Converter of low-level HTTP server calls into high-level uniform calls. * * @author Jerome Louvel */ public class ServerAdapter extends Adapter { /** * Constructor. * * @param context * The client context. */ public ServerAdapter(Context context) { super(context); } /** * Adds the entity headers for the handled uniform call. * * @param response * The response returned. */ protected void addEntityHeaders(HttpResponse response) { Series responseHeaders = response.getHttpCall() .getResponseHeaders(); Representation entity = response.getEntity(); HeaderUtils.addEntityHeaders(entity, responseHeaders); } /** * Adds the response headers for the handled uniform call. * * @param response * The response returned. */ protected void addResponseHeaders(HttpResponse response) { try { // Add all the necessary headers HeaderUtils.addGeneralHeaders(response, response.getHttpCall() .getResponseHeaders()); HeaderUtils.addResponseHeaders(response, response.getHttpCall() .getResponseHeaders()); // Set the status code in the response if (response.getStatus() != null) { response.getHttpCall().setStatusCode( response.getStatus().getCode()); response.getHttpCall().setReasonPhrase( response.getStatus().getName()); } } catch (Exception e) { getLogger().log(Level.INFO, "Exception intercepted while adding the response headers", e); response.getHttpCall().setStatusCode( Status.SERVER_ERROR_INTERNAL.getCode()); response.getHttpCall().setReasonPhrase( Status.SERVER_ERROR_INTERNAL.getName()); } } /** * Commits the changes to a handled uniform call back into the original HTTP * call. The default implementation first invokes the "addResponseHeaders" * then asks the "htppCall" to send the response back to the client. * * @param response * The high-level response. */ public void commit(HttpResponse response) { try { if ((response.getRequest().getMethod() != null) && response.getRequest().getMethod().equals(Method.HEAD)) { addEntityHeaders(response); response.setEntity(null); } else if (Method.GET.equals(response.getRequest().getMethod()) && Status.SUCCESS_OK.equals(response.getStatus()) && (!response.isEntityAvailable())) { addEntityHeaders(response); getLogger() .warning( "A response with a 200 (Ok) status should have an entity. Make sure that resource \"" + response.getRequest() .getResourceRef() + "\" returns one or sets the status to 204 (No content)."); } else if (response.getStatus().equals(Status.SUCCESS_NO_CONTENT)) { addEntityHeaders(response); if (response.isEntityAvailable()) { getLogger() .fine( "Responses with a 204 (No content) status generally don't have an entity. Only adding entity headers for resource \"" + response.getRequest() .getResourceRef() + "\"."); response.setEntity(null); } } else if (response.getStatus() .equals(Status.SUCCESS_RESET_CONTENT)) { if (response.isEntityAvailable()) { getLogger() .warning( "Responses with a 205 (Reset content) status can't have an entity. Ignoring the entity for resource \"" + response.getRequest() .getResourceRef() + "\"."); response.setEntity(null); } } else if (response.getStatus().equals( Status.REDIRECTION_NOT_MODIFIED)) { if (response.getEntity() != null) { HeaderUtils.addNotModifiedEntityHeaders(response .getEntity(), response.getHttpCall() .getResponseHeaders()); response.setEntity(null); } } else if (response.getStatus().isInformational()) { if (response.isEntityAvailable()) { getLogger() .warning( "Responses with an informational (1xx) status can't have an entity. Ignoring the entity for resource \"" + response.getRequest() .getResourceRef() + "\"."); response.setEntity(null); } } else { addEntityHeaders(response); if (!response.isEntityAvailable()) { if ((response.getEntity() != null) && (response.getEntity().getSize() != 0)) { getLogger() .warning( "A response with an unavailable and potentially non empty entity was returned. Ignoring the entity for resource \"" + response.getRequest() .getResourceRef() + "\"."); } response.setEntity(null); } } // Add the response headers addResponseHeaders(response); // Send the response to the client response.getHttpCall().sendResponse(response); } catch (Throwable t) { if (response.getHttpCall().isConnectionBroken(t)) { getLogger() .log( Level.INFO, "The connection was broken. It was probably closed by the client.", t); } else { getLogger().log(Level.SEVERE, "An exception occured writing the response entity", t); response.getHttpCall().setStatusCode( Status.SERVER_ERROR_INTERNAL.getCode()); response.getHttpCall().setReasonPhrase( "An exception occured writing the response entity"); response.setEntity(null); try { response.getHttpCall().sendResponse(response); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to send error response", ioe); } } } finally { response.getHttpCall().complete(); if (response.getOnSent() != null) { response.getOnSent().handle(response.getRequest(), response); } } } /** * Converts a low-level HTTP call into a high-level uniform request. * * @param httpCall * The low-level HTTP call. * @return A new high-level uniform request. */ @SuppressWarnings("deprecation") public HttpRequest toRequest(ServerCall httpCall) { HttpRequest result = new HttpRequest(getContext(), httpCall); result.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, httpCall.getRequestHeaders()); if (httpCall.getVersion() != null) { result.getAttributes().put(HeaderConstants.ATTRIBUTE_VERSION, httpCall.getVersion()); } if (httpCall.isConfidential()) { final List clientCertificates = httpCall .getSslClientCertificates(); if (clientCertificates != null) { result.getAttributes().put( HeaderConstants.ATTRIBUTE_HTTPS_CLIENT_CERTIFICATES, clientCertificates); } final String cipherSuite = httpCall.getSslCipherSuite(); if (cipherSuite != null) { result.getAttributes().put( HeaderConstants.ATTRIBUTE_HTTPS_CIPHER_SUITE, cipherSuite); } final Integer keySize = httpCall.getSslKeySize(); if (keySize != null) { result.getAttributes().put( HeaderConstants.ATTRIBUTE_HTTPS_KEY_SIZE, keySize); } final String sslSessionId = httpCall.getSslSessionId(); if (sslSessionId != null) { result.getAttributes().put( HeaderConstants.ATTRIBUTE_HTTPS_SSL_SESSION_ID, sslSessionId); } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/adapter/ClientAdapter.java0000664000175000017500000001613411757206346030512 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.adapter; import java.io.IOException; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Uniform; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.engine.Edition; import org.restlet.engine.http.ClientCall; import org.restlet.engine.http.HttpClientHelper; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.util.Series; /** * Converter of high-level uniform calls into low-level HTTP client calls. * * @author Jerome Louvel */ public class ClientAdapter extends Adapter { /** * Constructor. * * @param context * The context to use. */ public ClientAdapter(Context context) { super(context); } /** * Commits the changes to a handled HTTP client call back into the original * uniform call. The default implementation first invokes the * "addResponseHeaders" then asks the "htppCall" to send the response back * to the client. * * @param httpCall * The original HTTP call. * @param request * The high-level request. * @param response * The high-level response. * @throws Exception */ public void commit(final ClientCall httpCall, Request request, Response response) throws Exception { if (httpCall != null) { // Check if the call is asynchronous if (request.getOnResponse() != null) { final Uniform userCallback = request.getOnResponse(); // Send the request to the client httpCall.sendRequest(request, response, new Uniform() { public void handle(Request request, Response response) { try { updateResponse(response, new Status(httpCall.getStatusCode(), null, httpCall.getReasonPhrase(), null), httpCall); userCallback.handle(request, response); } catch (Throwable t) { getLogger() .log(Level.WARNING, "Unexpected error or exception inside the user call back", t); // Unexpected exception occurred if ((response.getStatus() == null) || !response.getStatus().isError()) { response.setStatus( Status.CONNECTOR_ERROR_INTERNAL, t); userCallback.handle(request, response); } } } }); } else { if (Edition.CURRENT == Edition.GWT) { System.err .println("HTTP client calls must have a callback in the GWT edition"); } else { updateResponse(response, httpCall.sendRequest(request), httpCall); } } } } /** * Reads the response headers of a handled HTTP client call to update the * original uniform call. * * @param httpCall * The handled HTTP client call. * @param response * The high-level response to update. */ protected void readResponseHeaders(ClientCall httpCall, Response response) { try { Series responseHeaders = httpCall.getResponseHeaders(); // Put the response headers in the call's attributes map response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders); HeaderUtils.copyResponseTransportHeaders(responseHeaders, response); } catch (Exception e) { e.printStackTrace(); getLogger() .log(Level.FINE, "An error occured during the processing of the HTTP response.", e); response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, e); } } /** * Converts a low-level HTTP call into a high-level uniform call. * * @param client * The HTTP client that will handle the call. * @param request * The high-level request. * @return A new high-level uniform call. */ public ClientCall toSpecific(HttpClientHelper client, Request request) { // Create the low-level HTTP client call ClientCall result = client.create(request); // Add the headers if (result != null) { HeaderUtils.addGeneralHeaders(request, result.getRequestHeaders()); if (request.getEntity() != null) { HeaderUtils.addEntityHeaders(request.getEntity(), result.getRequestHeaders()); } // NOTE: This must stay at the end because the AWS challenge // scheme requires access to all HTTP headers HeaderUtils.addRequestHeaders(request, result.getRequestHeaders()); } return result; } /** * Updates the response with information from the lower-level HTTP client * call. * * @param response * The response to update. * @param status * The response status to apply. * @param httpCall * The source HTTP client call. * @throws IOException */ public void updateResponse(Response response, Status status, ClientCall httpCall) { // Send the request to the client response.setStatus(status); // Get the server address response.getServerInfo().setAddress(httpCall.getServerAddress()); response.getServerInfo().setPort(httpCall.getServerPort()); // Read the response headers readResponseHeaders(httpCall, response); // Set the entity response.setEntity(httpCall.getResponseEntity(response)); // Release the representation's content for some obvious cases if (response.getEntity() != null) { if (response.getEntity().getSize() == 0) { response.getEntity().release(); } else if (response.getRequest().getMethod().equals(Method.HEAD)) { response.getEntity().release(); } else if (response.getStatus().equals(Status.SUCCESS_NO_CONTENT)) { response.getEntity().release(); } else if (response.getStatus() .equals(Status.SUCCESS_RESET_CONTENT)) { response.getEntity().release(); response.setEntity(null); } else if (response.getStatus().equals( Status.REDIRECTION_NOT_MODIFIED)) { response.getEntity().release(); } else if (response.getStatus().isInformational()) { response.getEntity().release(); response.setEntity(null); } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/0000775000175000017500000000000011757206350024105 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/UnclosableOutputStream.java0000664000175000017500000000356311757206346031450 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; // [excludes gwt] /** * OutputStream decorator to trap close() calls so that the decorated stream * does not get closed. * * @author Kevin Conaway */ public class UnclosableOutputStream extends FilterOutputStream { /** * Constructor. * * @param source * The decorated source stream. */ public UnclosableOutputStream(OutputStream source) { super(source); } @Override public void close() throws IOException { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/InboundStream.java0000664000175000017500000000412311757206346027527 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import org.restlet.engine.io.IoUtils; // [excludes gwt] /** * Buffered input stream that prevent the underlying stream from being closed. * * @author Jerome Louvel */ public class InboundStream extends BufferedInputStream { /** * Constructor. * * @param source * The source input stream. */ public InboundStream(InputStream source) { super(source, IoUtils.BUFFER_SIZE); } /** * Constructor. * * @param source * The source input stream. * @param size * the buffer size. */ public InboundStream(InputStream source, int size) { super(source, size); } @Override public void close() throws IOException { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/OutboundStream.java0000664000175000017500000000414511757206350027727 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import org.restlet.engine.io.IoUtils; // [excludes gwt] /** * Buffered output stream that prevents the underlying stream from being closed. * * @author Jerome Louvel */ public class OutboundStream extends BufferedOutputStream { /** * Constructor. * * @param source * The decorated source stream. */ public OutboundStream(OutputStream source) { super(source, IoUtils.BUFFER_SIZE); } /** * Constructor. * * @param source * The decorated source stream. * @param size * the buffer size. */ public OutboundStream(OutputStream source, int size) { super(source, size); } @Override public void close() throws IOException { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/SizedInputStream.java0000664000175000017500000001055011757206346030230 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.IOException; import java.io.InputStream; // [excludes gwt] /** * Input stream based on a source stream that must only be partially read. * * @author Jerome Louvel */ public class SizedInputStream extends InputEntityStream { /** The total size that should be read from the source stream. */ private volatile long availableSize; /** The total size when the {@link #mark(int)} method was called. */ private volatile long markedAvailableSize; /** * Constructor. * * @param notifiable * The notifiable connection. * @param inboundStream * The inbound stream. * @param size * The total size that should be read from the source stream. */ public SizedInputStream(Notifiable notifiable, InputStream inboundStream, long size) { super(notifiable, inboundStream); this.availableSize = size; this.markedAvailableSize = -1; } @Override public int available() throws IOException { return Math.min((int) this.availableSize, getInboundStream() .available()); } @Override public void close() throws IOException { // Don't close it directly } @Override public synchronized void mark(int readlimit) { if (markSupported()) { this.markedAvailableSize = availableSize; } getInboundStream().mark(readlimit); } @Override public boolean markSupported() { return getInboundStream().markSupported(); } /** * Reads a byte from the underlying stream. * * @return The byte read, or -1 if the end of the stream has been reached. */ @Override public int read() throws IOException { int result = -1; if (this.availableSize > 0) { result = getInboundStream().read(); if (result != -1) { this.availableSize--; } else { onEndReached(); } } // The stream has been fully read. if (this.availableSize <= 0) { onEndReached(); } return result; } @Override public int read(byte b[], int off, int len) throws IOException { int result = -1; if (this.availableSize > 0) { result = getInboundStream().read(b, off, Math.min(len, (int) this.availableSize)); if (result > 0) { this.availableSize -= result; } else if (result == -1) { onEndReached(); } } if (this.availableSize <= 0) { onEndReached(); } return result; } @Override public synchronized void reset() throws IOException { if (markSupported()) { if (this.markedAvailableSize != -1) { this.availableSize = markedAvailableSize; this.markedAvailableSize = -1; } } getInboundStream().reset(); } @Override public long skip(long n) throws IOException { return getInboundStream().skip(n); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/UnclosableInputStream.java0000664000175000017500000000355711757206346031252 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; // [excludes gwt] /** * InputStream decorator to trap {@code close()} calls so that the underlying * stream is not closed. * * @author Kevin Conaway * */ public class UnclosableInputStream extends FilterInputStream { /** * Constructor. * * @param source * The source input stream. */ public UnclosableInputStream(InputStream source) { super(source); } @Override public void close() throws IOException { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/package.html0000664000175000017500000000013211757206350026362 0ustar jamespagejamespage Supports HTTP input and output.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/ReadableEntityChannel.java0000664000175000017500000001152411757206346031145 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; // [excludes gwt] /** * Readable byte channel based on a source socket channel that must only be * partially read. */ public class ReadableEntityChannel extends SelectableChannel implements ReadableByteChannel { /** The byte buffer remaining from previous read processing. */ private volatile ByteBuffer remainingBuffer; /** The source channel. */ private volatile SelectableChannel source; /** The total size that should be read from the source channel. */ private volatile long availableSize; /** * Constructor. * * @param remainingBuffer * The byte buffer remaining from previous read processing. * @param source * The source channel. * @param availableSize * The available size that can be read from the source channel. */ public ReadableEntityChannel(ByteBuffer remainingBuffer, SelectableChannel source, long availableSize) { this.remainingBuffer = remainingBuffer; this.source = source; this.availableSize = availableSize; } @Override public Object blockingLock() { return getSource().blockingLock(); } @Override public SelectableChannel configureBlocking(boolean block) throws IOException { return getSource().configureBlocking(block); } private SelectableChannel getSource() { return this.source; } @Override protected void implCloseChannel() throws IOException { } @Override public boolean isBlocking() { return getSource().isBlocking(); } @Override public boolean isRegistered() { return getSource().isRegistered(); } @Override public SelectionKey keyFor(Selector sel) { return getSource().keyFor(sel); } @Override public SelectorProvider provider() { return getSource().provider(); } /** * Reads some bytes and put them into the destination buffer. The bytes come * from the underlying channel. * * @param dst * The destination buffer. * @return The number of bytes read, or -1 if the end of the channel has * been reached. */ public int read(ByteBuffer dst) throws IOException { int result = -1; if (this.availableSize > 0) { if ((this.remainingBuffer != null) && (this.remainingBuffer.hasRemaining())) { // First make sure that the remaining buffer is empty result = Math.min(this.remainingBuffer.remaining(), dst.remaining()); byte[] src = new byte[result]; this.remainingBuffer.get(src); dst.put(src); } else { // Otherwise, read data from the source channel result = ((ReadableByteChannel) getSource()).read(dst); } if (result > 0) { this.availableSize -= result; } } return result; } @Override public SelectionKey register(Selector sel, int ops, Object att) throws ClosedChannelException { return getSource().register(sel, ops, att); } @Override public int validOps() { return getSource().validOps(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/ClosingInputStream.java0000664000175000017500000000450511757206346030553 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.IOException; import java.io.InputStream; /** * Input stream based on a source stream that must only be totally read before * closing. * * @author Jerome Louvel */ public class ClosingInputStream extends InputEntityStream { /** * Constructor. * * @param notifiable * The notifiable connection. * @param inboundStream * The inbound stream. */ public ClosingInputStream(Notifiable notifiable, InputStream inboundStream) { super(notifiable, inboundStream); } @Override public int read() throws IOException { int r = -1; try { r = getInboundStream().read(); if (r == -1) { onEndReached(); } } catch (Exception e) { onError(); } return r; } @Override public int read(byte[] b, int off, int len) throws IOException { int result = getInboundStream().read(b, off, len); if (result == -1) { onEndReached(); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/InputEntityStream.java0000664000175000017500000000563611757206346030437 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.InputStream; import org.restlet.engine.http.connector.Connection; import org.restlet.engine.http.connector.ConnectionState; /** * Input stream that synchronizes the state of a {@link Connection} instance and * an input stream. */ public abstract class InputEntityStream extends InputStream { /** The notifiable connection. */ private volatile Notifiable notifiable; /** The inbound stream. */ private InputStream inboundStream; /** * Constructor. * * @param notifiable * The notifiable connection. * @param inboundStream * The inbound stream. */ public InputEntityStream(Notifiable notifiable, InputStream inboundStream) { super(); this.notifiable = notifiable; this.inboundStream = inboundStream; } /** * Returns the inbound stream. * * @return The inbound stream. */ protected InputStream getInboundStream() { return this.inboundStream; } /** * To be called when the end of the stream is reached. By default, it * updates the state of the connection ( * {@link Connection#setInboundBusy(boolean)}) . */ protected void onEndReached() { if (notifiable != null) { notifiable.onEndReached(); } } /** * To be called when there is an error when handling the stream. By default * it calls {@link #onEndReached()} and set the state of the connection to * {@link ConnectionState#CLOSING} in order to release this stream. */ protected void onError() { if (notifiable != null) { notifiable.onError(); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/ChunkedInputStream.java0000664000175000017500000001704611757206346030542 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; /** * {@link InputStream} to wrap a source {@link InputStream} that has been * chunked. See section 3.6.1 of HTTP Protocol for more information on chunked * encoding. * * @author Kevin Conaway * @see HTTP/1.1 * Protocol */ public class ChunkedInputStream extends InputEntityStream { /** Size of the push back buffer. */ private static final int PUSHBBACK_BUFFER_SIZE = 2; /** Size of the current chunk. */ private volatile long chunkSize; /** Indicates if the end of the source stream has been reached. */ private volatile boolean endReached; /** Indicates if the chunked has been properly initialized. */ private volatile boolean initialized; /** Indicates the position inside the current chunk. */ private volatile long position; /** The source input stream to decode. */ private final PushbackInputStream source; /** * Constructor. * * @param notifiable * The notifiable connection. * @param inboundStream * The inbound stream. */ public ChunkedInputStream(Notifiable notifiable, InputStream inboundStream) { super(notifiable, inboundStream); this.source = new PushbackInputStream(inboundStream, PUSHBBACK_BUFFER_SIZE); this.initialized = false; this.endReached = false; this.position = 0; this.chunkSize = 0; } /** * Indicates if the source stream can be read and prepare it if necessary. * * @return True if the source stream can be read. * @throws IOException */ private boolean canRead() throws IOException { boolean result = false; initialize(); if (!this.endReached) { if (!chunkAvailable()) { initializeChunk(); } result = !this.endReached; } return result; } /** * Checks if the source stream will return a CR+LF sequence next, without * actually reading it. * * @throws IOException */ private void checkCRLF() throws IOException { final int cr = this.source.read(); final int lf = this.source.read(); if ((cr != '\r') || (lf != '\n')) { this.source.unread(lf); this.source.unread(cr); } } /** * Indicates if a chunk is available or false if a new one needs to be * initialized. * * @return True if a chunk is available or false if a new one needs to be * initialized. */ private boolean chunkAvailable() { return this.position < this.chunkSize; } /** * Closes this input stream but do not close the underlying stream. */ @Override public void close() throws IOException { super.close(); this.initialized = true; onEndReached(); } /** * Initializes the stream by reading and discarding a CRLF (if present). * * @throws IOException */ private void initialize() throws IOException { if (!this.initialized) { checkCRLF(); this.initialized = true; } } /** * Initialize the next chunk in the stream. * * @throws IOException */ private void initializeChunk() throws IOException { this.chunkSize = readChunkSize(); this.position = 0; if (this.chunkSize == 0) { onEndReached(); // Read the new line after the optional (unsupported) trailer checkCRLF(); } } @Override protected void onEndReached() { super.onEndReached(); this.endReached = true; } @Override public int read() throws IOException { int result = -1; if (canRead()) { result = this.source.read(); this.position++; if ((result == -1)) { onEndReached(); } } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { int result = -1; if (canRead()) { result = this.source.read(b, off, Math.min(len, (int) (this.chunkSize - this.position))); this.position += result; if (len - result > 0) { int nextResult = read(b, off + result, len - result); if (nextResult > 0) { result += nextResult; } } if (result == -1) { onEndReached(); } } return result; } /** * Reads the chunk size from the current line. * * @return The chunk size from the current line. * @throws IOException * If the chunk size could not be read or was invalid. */ private long readChunkSize() throws IOException { String line = readChunkSizeLine(); final int index = line.indexOf(';'); line = index == -1 ? line : line.substring(0, index); try { return Long.parseLong(line.trim(), 16); } catch (NumberFormatException ex) { throw new IOException("<" + line + "> is an invalid chunk size"); } } /** * Reads a line containing a chunk size. * * @return A line containing a chunk size. * @throws IOException */ private String readChunkSizeLine() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); checkCRLF(); for (;;) { final int b = this.source.read(); if (b == -1) { throw new IOException( "Invalid chunk size specified. End of stream reached"); } if (b == '\r') { final int lf = this.source.read(); if (lf == '\n') { break; } throw new IOException( "Invalid chunk size specified. Expected crlf, only saw cr"); } buffer.write(b); } return new String(buffer.toByteArray()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/Notifiable.java0000664000175000017500000000401611757206346027032 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; /** * Marker class for objects such as * {@link org.restlet.engine.http.connector.Connection} that can be notified of * stream events. * * @author Jerome Louvel */ public interface Notifiable { /** * To be called when the end of the stream is reached. By default, it * updates the state of the connection ( * {@link org.restlet.engine.http.connector.Connection#setInboundBusy(boolean)} * ) . */ public void onEndReached(); /** * To be called when there is an error when handling the stream. By default * it calls {@link #onEndReached()} and set the state of the connection to * {@link org.restlet.engine.http.connector.ConnectionState#CLOSING} in * order to release this stream. */ public void onError(); } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/ClosingRepresentation.java0000664000175000017500000000545511757206346031307 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.IOException; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLSocket; import org.restlet.representation.Representation; import org.restlet.util.WrapperRepresentation; /** * Wrapper representation to close the associated socket when the representation * is released. * * @author Jerome Louvel */ public class ClosingRepresentation extends WrapperRepresentation { /** The associated logger. */ private final Logger logger; /** The associated socket. */ private final Socket socket; /** * Constructor. * * @param wrappedRepresentation * The wrapped representation. * @param socket * The associated socket. * @param logger * The associated logger. */ public ClosingRepresentation(Representation wrappedRepresentation, Socket socket, Logger logger) { super(wrappedRepresentation); this.socket = socket; this.logger = logger; } /** * Closes the socket if necessary. */ @Override public void release() { try { if (!this.socket.isClosed()) { if (!(this.socket instanceof SSLSocket)) { this.socket.shutdownOutput(); } this.socket.close(); } } catch (IOException ex) { this.logger.log(Level.WARNING, "An error occured closing the client socket", ex); } super.release(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/io/ChunkedOutputStream.java0000664000175000017500000001163411757206346030740 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.io; import java.io.IOException; import java.io.OutputStream; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.util.StringUtils; /** * OutputStream to write data in the HTTP chunked encoding format to a * destination OutputStream. See section 3.6.1 of HTTP Protocol for more * information on chunked encoding. * * @author Kevin Conaway * @see HTTP/1.1 * Protocol */ public class ChunkedOutputStream extends OutputStream { /** Default size of a chunk. */ private static final int DEFAULT_CHUNK_SIZE = 2048; /** The byte buffer. */ private final byte[] buffer; /** The number of bytes written. */ private volatile int bytesWritten; /** Indicate if the stream is closed. */ private volatile boolean closed; /** The destination output stream. */ private final OutputStream destination; /** * Convenience constructor to use a default chunk size size of 2048. * * @param destination * @see #ChunkedOutputStream(OutputStream, int) */ public ChunkedOutputStream(OutputStream destination) { this(destination, DEFAULT_CHUNK_SIZE); } /** * @param destination * Outputstream to write chunked data to * @param chunkSize * Chunk size */ public ChunkedOutputStream(OutputStream destination, int chunkSize) { this.destination = destination; this.buffer = new byte[chunkSize]; this.bytesWritten = 0; this.closed = false; } /** * @return True if the current chunk is full. */ private boolean chunkFull() { return this.bytesWritten == this.buffer.length; } /** * Closes this output stream for writing but does not close the wrapped * stream. */ @Override public void close() throws IOException { if (!this.closed) { writeChunk(); writeFinalChunk(); super.close(); this.closed = true; this.destination.flush(); } } /** * Writes the current chunk and flushes the wrapped stream. */ @Override public void flush() throws IOException { writeChunk(); this.destination.flush(); } /** * Resets the internal buffer. */ private void reset() { this.bytesWritten = 0; } @Override public void write(int b) throws IOException { if (chunkFull()) { writeChunk(); } this.buffer[this.bytesWritten++] = (byte) b; } /** * Write a chunk, starting with its size in hexadecimal, followed by CRLF * and the actual content. * * @throws IOException */ private void writeChunk() throws IOException { if (this.bytesWritten > 0) { // Write the current position in hexadecimal format followed by CRLF this.destination.write(StringUtils.getAsciiBytes(Integer .toHexString(this.bytesWritten))); HeaderUtils.writeCRLF(this.destination); // Write the chunk content this.destination.write(this.buffer, 0, this.bytesWritten); HeaderUtils.writeCRLF(this.destination); // Reset the position reset(); } } /** * Write the closing chunk: A zero followed by two CRLF. * * @throws IOException */ private void writeFinalChunk() throws IOException { this.destination.write((byte) '0'); HeaderUtils.writeCRLF(this.destination); HeaderUtils.writeCRLF(this.destination); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java0000664000175000017500000001403511757206350027612 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Server; import org.restlet.engine.Engine; import org.restlet.engine.ServerHelper; import org.restlet.engine.http.adapter.ServerAdapter; /** * Base HTTP server connector. Here is the list of parameters that are * supported. They should be set in the Server's context before it is started: * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    useForwardedForHeaderbooleanfalseLookup the "X-Forwarded-For" header supported by popular proxies and * caches and uses it to populate the Request.getClientAddresses() method * result. This information is only safe for intermediary components within your * local network. Other addresses could easily be changed by setting a fake * header and should not be trusted for serious security checks.
    adapterStringorg.restlet.engine.http.adapter.ServerAdapterClass name of the adapter of low-level HTTP calls into high level * requests and responses.
    * * @author Jerome Louvel */ public class HttpServerHelper extends ServerHelper { /** The adapter from HTTP calls to uniform calls. */ private volatile ServerAdapter adapter; /** * Default constructor. Note that many methods assume that a non-null server * is set to work properly. You can use the setHelped(Server) method for * this purpose or better rely on the other constructor. */ public HttpServerHelper() { this(null); } /** * Constructor. * * @param server * The server to help. */ public HttpServerHelper(Server server) { super(server); this.adapter = null; } /** * Returns the adapter from HTTP calls to uniform calls. * * @return the adapter from HTTP calls to uniform calls. */ public ServerAdapter getAdapter() { if (this.adapter == null) { try { final String adapterClass = getHelpedParameters() .getFirstValue("adapter", "org.restlet.engine.http.adapter.ServerAdapter"); this.adapter = (ServerAdapter) Engine.loadClass(adapterClass) .getConstructor(Context.class) .newInstance(getContext()); } catch (IllegalArgumentException e) { getLogger().log(Level.SEVERE, "Unable to create the HTTP server adapter", e); } catch (SecurityException e) { getLogger().log(Level.SEVERE, "Unable to create the HTTP server adapter", e); } catch (InstantiationException e) { getLogger().log(Level.SEVERE, "Unable to create the HTTP server adapter", e); } catch (IllegalAccessException e) { getLogger().log(Level.SEVERE, "Unable to create the HTTP server adapter", e); } catch (InvocationTargetException e) { getLogger().log(Level.SEVERE, "Unable to create the HTTP server adapter", e); } catch (NoSuchMethodException e) { getLogger().log(Level.SEVERE, "Unable to create the HTTP server adapter", e); } catch (ClassNotFoundException e) { getLogger().log(Level.SEVERE, "Unable to create the HTTP server adapter", e); } } return this.adapter; } /** * Handles the connector call. The default behavior is to create an REST * call and delegate it to the attached Restlet. * * @param httpCall * The HTTP server call. */ public void handle(ServerCall httpCall) { try { HttpRequest request = getAdapter().toRequest(httpCall); HttpResponse response = new HttpResponse(httpCall, request); handle(request, response); getAdapter().commit(response); } catch (Exception e) { getLogger().log(Level.WARNING, "Error while handling an HTTP server call: ", e.getMessage()); getLogger().log(Level.INFO, "Error while handling an HTTP server call", e); } finally { Engine.clearThreadLocalVariables(); } } /** * Sets the adapter from HTTP calls to uniform calls. * * @param adapter * The converter to set. */ public void setAdapter(ServerAdapter adapter) { this.adapter = adapter; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/HttpProtocolHelper.java0000664000175000017500000000355511757206346030157 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import org.restlet.data.Method; import org.restlet.engine.ProtocolHelper; /** * Protocol helper for the HTTP protocol. * * @author Thierry Boileau * */ public class HttpProtocolHelper extends ProtocolHelper { @Override public void registerMethods() { Method.register(Method.ALL); Method.register(Method.CONNECT); Method.register(Method.DELETE); Method.register(Method.GET); Method.register(Method.HEAD); Method.register(Method.OPTIONS); Method.register(Method.POST); Method.register(Method.PUT); Method.register(Method.TRACE); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/0000775000175000017500000000000011757206350024726 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/PreferenceWriter.java0000664000175000017500000000735711757206350031060 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.restlet.data.Parameter; import org.restlet.data.Preference; /** * Preference header writer. * * @author Jerome Louvel */ public class PreferenceWriter extends HeaderWriter> { /** * Indicates if the quality value is valid. * * @param quality * The quality value. * @return True if the quality value is valid. */ public static boolean isValidQuality(float quality) { return (quality >= 0F) && (quality <= 1F); } /** * Writes a list of preferences with a comma separator. * * @param prefs * The list of preferences. * @return The formatted list of preferences. * @throws IOException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static String write(List prefs) { return new PreferenceWriter().append(prefs).toString(); } @Override public PreferenceWriter append(Preference pref) { append(pref.getMetadata().getName()); if (pref.getQuality() < 1F) { append(";q="); appendQuality(pref.getQuality()); } if (pref.getParameters() != null) { Parameter param; for (Iterator iter = pref.getParameters().iterator(); iter .hasNext();) { param = iter.next(); if (param.getName() != null) { append(';').append(param.getName()); if ((param.getValue() != null) && (param.getValue().length() > 0)) { append('=').append(param.getValue()); } } } } return this; } /** * Formats a quality value.
    * If the quality is invalid, an IllegalArgumentException is thrown. * * @param quality * The quality value as a float. * @return This writer. */ public PreferenceWriter appendQuality(float quality) { if (!isValidQuality(quality)) { throw new IllegalArgumentException( "Invalid quality value detected. Value must be between 0 and 1."); } java.text.NumberFormat formatter = java.text.NumberFormat .getNumberInstance(java.util.Locale.US); formatter.setMaximumFractionDigits(2); append(formatter.format(quality)); return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/CacheDirectiveReader.java0000664000175000017500000000453211757206346031567 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Collection; import org.restlet.data.CacheDirective; import org.restlet.data.Parameter; /** * Cache directive header reader. * * @author Jerome Louvel */ public class CacheDirectiveReader extends HeaderReader { /** * Adds values to the given collection. * * @param header * The header to read. * @param collection * The collection to update. */ public static void addValues(Parameter header, Collection collection) { new CacheDirectiveReader(header.getValue()).addValues(collection); } /** * Constructor. * * @param header * The header to read. */ public CacheDirectiveReader(String header) { super(header); } @Override protected Parameter createParameter(String name, String value) { return new CacheDirective(name, value); } @Override public CacheDirective readValue() throws IOException { return (CacheDirective) readParameter(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/RecipientInfoWriter.java0000664000175000017500000000473111757206346031536 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.RecipientInfo; /** * Recipient info header writer. * * @author Jerome Louvel */ public class RecipientInfoWriter extends HeaderWriter { /** * Creates a via header from the given recipients info. * * @param recipientsInfo * The recipients info. * @return Returns the Via header. */ public static String write(List recipientsInfo) { return new RecipientInfoWriter().append(recipientsInfo).toString(); } @Override public RecipientInfoWriter append(RecipientInfo recipientInfo) { if (recipientInfo.getProtocol() != null) { appendToken(recipientInfo.getProtocol().getName()); append('/'); appendToken(recipientInfo.getProtocol().getVersion()); appendSpace(); if (recipientInfo.getName() != null) { append(recipientInfo.getName()); if (recipientInfo.getComment() != null) { appendSpace(); appendComment(recipientInfo.getComment()); } } else { throw new IllegalArgumentException( "The name (host or pseudonym) of a recipient can't be null"); } } else { throw new IllegalArgumentException( "The protocol of a recipient can't be null"); } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/HeaderReader.java0000664000175000017500000004710211757206346030115 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import static org.restlet.engine.http.header.HeaderUtils.isCarriageReturn; import static org.restlet.engine.http.header.HeaderUtils.isComma; import static org.restlet.engine.http.header.HeaderUtils.isCommentText; import static org.restlet.engine.http.header.HeaderUtils.isDoubleQuote; import static org.restlet.engine.http.header.HeaderUtils.isLineFeed; import static org.restlet.engine.http.header.HeaderUtils.isLinearWhiteSpace; import static org.restlet.engine.http.header.HeaderUtils.isQuoteCharacter; import static org.restlet.engine.http.header.HeaderUtils.isQuotedText; import static org.restlet.engine.http.header.HeaderUtils.isSemiColon; import static org.restlet.engine.http.header.HeaderUtils.isSpace; import static org.restlet.engine.http.header.HeaderUtils.isTokenChar; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.Encoding; import org.restlet.data.Parameter; import org.restlet.engine.util.DateUtils; /** * HTTP-style header reader. * * @param * The header value target type. There can be multiple values for a * single header. * @author Jerome Louvel */ public class HeaderReader { /** * Parses a date string. * * @param date * The date string to parse. * @param cookie * Indicates if the date is in the cookie format. * @return The parsed date. */ public static Date readDate(String date, boolean cookie) { if (cookie) { return DateUtils.parse(date, DateUtils.FORMAT_RFC_1036); } return DateUtils.parse(date, DateUtils.FORMAT_RFC_1123); } /** * Read a header. Return null if the last header was already read. * * @param header * The header line to parse. * @return The header read or null. * @throws IOException */ public static Parameter readHeader(CharSequence header) throws IOException { Parameter result = null; if (header.length() > 0) { // Detect the end of headers int start = 0; int index = 0; int next = header.charAt(index++); if (isCarriageReturn(next)) { next = header.charAt(index++); if (!isLineFeed(next)) { throw new IOException( "Invalid end of headers. Line feed missing after the carriage return."); } } else { result = new Parameter(); // Parse the header name while ((index < header.length()) && (next != ':')) { next = header.charAt(index++); } if (index == header.length()) { throw new IOException( "Unable to parse the header name. End of line reached too early."); } result.setName(header.subSequence(start, index - 1).toString()); next = header.charAt(index++); while (isSpace(next)) { // Skip any separator space between colon and header value next = header.charAt(index++); } start = index - 1; // Parse the header value result.setValue(header.subSequence(start, header.length()) .toString()); } } return result; } /** * Read a header. Return null if the last header was already read. * * @param is * The message input stream. * @param sb * The string builder to reuse. * @return The header read or null. * @throws IOException */ public static Parameter readHeader(InputStream is, StringBuilder sb) throws IOException { Parameter result = null; // Detect the end of headers int next = is.read(); if (isCarriageReturn(next)) { next = is.read(); if (!isLineFeed(next)) { throw new IOException( "Invalid end of headers. Line feed missing after the carriage return."); } } else { result = new Parameter(); // Parse the header name while ((next != -1) && (next != ':')) { sb.append((char) next); next = is.read(); } if (next == -1) { throw new IOException( "Unable to parse the header name. End of stream reached too early."); } result.setName(sb.toString()); sb.delete(0, sb.length()); next = is.read(); while (isSpace(next)) { // Skip any separator space between colon and header value next = is.read(); } // Parse the header value while ((next != -1) && (!isCarriageReturn(next))) { sb.append((char) next); next = is.read(); } if (next == -1) { throw new IOException( "Unable to parse the header value. End of stream reached too early."); } next = is.read(); if (isLineFeed(next)) { result.setValue(sb.toString()); sb.delete(0, sb.length()); } else { throw new IOException( "Unable to parse the HTTP header value. The carriage return must be followed by a line feed."); } } return result; } /** The header to read. */ private final String header; /** The current read index (or -1 if not reading anymore). */ private volatile int index; /** The current mark. */ private volatile int mark; /** * Constructor. * * @param header * The header to read. */ public HeaderReader(String header) { this.header = header; this.index = ((header == null) || (header.length() == 0)) ? -1 : 0; this.mark = index; } /** * Adds values to the given list. * * @param values * The list of values to update. */ public void addValues(Collection values) { try { // Skip leading spaces skipSpaces(); do { // Read the first value V nextValue = readValue(); if (canAdd(nextValue, values)) { // Add the value to the list values.add(nextValue); } // Attempt to skip the value separator skipValueSeparator(); } while (peek() != -1); } catch (IOException ioe) { Context.getCurrentLogger().log(Level.INFO, "Unable to read a header", ioe); } } /** * Indicates if the value can be added the the list. Useful to prevent the * addition of {@link Encoding#IDENTITY} constants for example. By default * it returns true for non null values. * * @param value * The value to add. * * @param values * The target collection. * @return True if the value can be added. */ protected boolean canAdd(V value, Collection values) { return value != null && !values.contains(value); } /** * Creates a new parameter with a null value. Can be overridden. * * @param name * The parameter name. * @return The new parameter. */ protected final Parameter createParameter(String name) { return createParameter(name, null); } /** * Creates a new parameter. Can be overridden. * * @param name * The parameter name. * @param value * The parameter value or null. * @return The new parameter. */ protected Parameter createParameter(String name, String value) { return new Parameter(name, value); } /** * Marks the current position in this reader. A subsequent call to the * reset method repositions this reader at the last marked * position. */ public void mark() { mark = index; } /** * Reads the next character. * * @return The next character. */ public int peek() { int result = -1; if (this.index != -1) { result = this.header.charAt(this.index); } return result; } /** * Reads the next character. * * @return The next character. */ public int read() { int result = -1; if (this.index >= 0) { result = this.header.charAt(this.index++); if (this.index >= this.header.length()) { this.index = -1; } } return result; } /** * Reads the next comment. The first character must be a parenthesis. * * @return The next comment. * @throws IOException */ public String readComment() throws IOException { String result = null; int next = read(); // First character must be a parenthesis if (next == '(') { StringBuilder buffer = new StringBuilder(); while (result == null) { next = read(); if (isCommentText(next)) { buffer.append((char) next); } else if (isQuoteCharacter(next)) { // Start of a quoted pair (escape sequence) buffer.append((char) read()); } else if (next == '(') { // Nested comment buffer.append('(').append(readComment()).append(')'); } else if (next == ')') { // End of comment result = buffer.toString(); } else if (next == -1) { throw new IOException( "Unexpected end of comment. Please check your value"); } else { throw new IOException("Invalid character \"" + next + "\" detected in comment. Please check your value"); } } } else { throw new IOException("A comment must start with a parenthesis"); } return result; } /** * Reads the next digits. * * @return The next digits. */ public String readDigits() { StringBuilder sb = new StringBuilder(); int next = read(); while (isTokenChar(next)) { sb.append((char) next); next = read(); } // Unread the last character (separator or end marker) unread(); return sb.toString(); } /** * Reads the next pair as a parameter. * * @return The next pair as a parameter. * @throws IOException */ public Parameter readParameter() throws IOException { Parameter result = null; String name = readToken(); int nextChar = read(); if (name.length() > 0) { if (nextChar == '=') { // The parameter has a value result = createParameter(name, readParameterValue()); } else { // The parameter has not value unread(); result = createParameter(name); } } else { throw new IOException( "Parameter or extension has no name. Please check your value"); } return result; } /** * Reads a parameter value which is either a token or a quoted string. * * @return A parameter value. * @throws IOException */ public String readParameterValue() throws IOException { String result = null; // Discard any leading space skipSpaces(); // Detect if quoted string or token available int nextChar = peek(); if (isDoubleQuote(nextChar)) { result = readQuotedString(); } else if (isTokenChar(nextChar)) { result = readToken(); } return result; } /** * Reads the next quoted string. The first character must be a double quote. * * @return The next quoted string. * @throws IOException */ public String readQuotedString() throws IOException { String result = null; int next = read(); // First character must be a double quote if (isDoubleQuote(next)) { StringBuilder buffer = new StringBuilder(); while (result == null) { next = read(); if (isQuotedText(next)) { buffer.append((char) next); } else if (isQuoteCharacter(next)) { // Start of a quoted pair (escape sequence) buffer.append((char) read()); } else if (isDoubleQuote(next)) { // End of quoted string result = buffer.toString(); } else if (next == -1) { throw new IOException( "Unexpected end of quoted string. Please check your value"); } else { throw new IOException( "Invalid character \"" + next + "\" detected in quoted string. Please check your value"); } } } else { throw new IOException( "A quoted string must start with a double quote"); } return result; } /** * Read the next text until a space separator is reached. * * @return The next text. */ public String readRawText() { // Read value until end or space StringBuilder sb = null; int next = read(); while ((next != -1) && !isSpace(next) && !isComma(next)) { if (sb == null) { sb = new StringBuilder(); } sb.append((char) next); next = read(); } // Unread the separator if (isSpace(next) || isComma(next)) { unread(); } return (sb == null) ? null : sb.toString(); } /** * Read the next header value of a multi-value header. It skips leading and * trailing spaces. * * @see HTTP * parsing rule * * @return The next header value or null. */ public String readRawValue() { // Skip leading spaces skipSpaces(); // Read value until end or comma StringBuilder sb = null; int next = read(); while ((next != -1) && !isComma(next)) { if (sb == null) { sb = new StringBuilder(); } sb.append((char) next); next = read(); } // Remove trailing spaces if (sb != null) { for (int i = sb.length() - 1; (i >= 0) && isLinearWhiteSpace(sb.charAt(i)); i--) { sb.deleteCharAt(i); } } // Unread the separator if (isComma(next)) { unread(); } return (sb == null) ? null : sb.toString(); } /** * Reads the next token. * * @return The next token. */ public String readToken() { StringBuilder sb = new StringBuilder(); int next = read(); while (isTokenChar(next)) { sb.append((char) next); next = read(); } // Unread the last character (separator or end marker) unread(); return sb.toString(); } /** * Read the next value. There can be multiple values for a single header. * * @return The next value. */ public V readValue() throws IOException { return null; } /** * Returns a new list with all values added. * * @return A new list with all values added. */ public List readValues() { List result = new CopyOnWriteArrayList(); addValues(result); return result; } /** * Repositions this stream to the position at the time the mark * method was last called on this input stream. */ public void reset() { index = mark; } /** * Skips the next parameter separator (semi-colon) including leading and * trailing spaces. * * @return True if a separator was effectively skipped. */ public boolean skipParameterSeparator() { boolean result = false; // Skip leading spaces skipSpaces(); // Check if next character is a parameter separator if (isSemiColon(read())) { result = true; // Skip trailing spaces skipSpaces(); } else { // Probably reached the end of the header unread(); } return result; } /** * Skips the next spaces. * * @return True if spaces were skipped. */ public boolean skipSpaces() { boolean result = false; int next = peek(); while (isLinearWhiteSpace(next) && (next != -1)) { result = result || isLinearWhiteSpace(next); read(); next = peek(); } return result; } /** * Skips the next value separator (comma) including leading and trailing * spaces. * * @return True if a separator was effectively skipped. */ public boolean skipValueSeparator() { boolean result = false; // Skip leading spaces skipSpaces(); // Check if next character is a value separator if (isComma(read())) { result = true; // Skip trailing spaces skipSpaces(); } else { // Probably reached the end of the header unread(); } return result; } /** * Unreads the last character. */ public void unread() { if (this.index > 0) { this.index--; } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/MethodWriter.java0000664000175000017500000000355211757206346030220 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.Set; import org.restlet.data.Method; /** * Method header writer. * * @author Jerome Louvel */ public class MethodWriter extends HeaderWriter { /** * Writes a set of methods with a comma separator. * * @param methods * The set of methods. * @return The formatted set of methods. */ public static String write(Set methods) { return new MethodWriter().append(methods).toString(); } @Override public MethodWriter append(Method method) { return (MethodWriter) appendToken(method.getName()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/TagWriter.java0000664000175000017500000000373011757206346027511 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.Tag; /** * Tag header writer. * * @author Jerome Louvel */ public class TagWriter extends HeaderWriter { /** * Writes a list of tags. * * @param tags * The tags to write. * @return This writer. */ public static String write(List tags) { return new TagWriter().append(tags).toString(); } /** * Writes a tag. * * @param tag * The tag to write. * @return This writer. */ public static String write(Tag tag) { return tag.format(); } @Override public HeaderWriter append(Tag tag) { return append(write(tag)); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/EncodingWriter.java0000664000175000017500000000353111757206346030523 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.Encoding; /** * Encoding header writer. * * @author Jerome Louvel */ public class EncodingWriter extends MetadataWriter { /** * Writes a list of encodings. * * @param encodings * The encodings to write. * @return This writer. */ public static String write(List encodings) { return new EncodingWriter().append(encodings).toString(); } @Override protected boolean canWrite(Encoding encoding) { return !encoding.equals(Encoding.IDENTITY); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/HeaderUtils.java0000664000175000017500000014326111757206350030011 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Message; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.AuthenticationInfo; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.CookieSetting; import org.restlet.data.Digest; import org.restlet.data.Disposition; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.data.Tag; import org.restlet.engine.Engine; import org.restlet.engine.util.DateUtils; import org.restlet.engine.util.StringUtils; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * HTTP-style header utilities. * * @author Jerome Louvel */ public class HeaderUtils { /** * Adds the entity headers based on the {@link Representation} to the * {@link Series}. * * @param entity * The source entity {@link Representation}. * @param headers * The target headers {@link Series}. */ public static void addEntityHeaders(Representation entity, Series headers) { if (entity == null || !entity.isAvailable()) { addHeader(HeaderConstants.HEADER_CONTENT_LENGTH, "0", headers); } else if (entity.getAvailableSize() != Representation.UNKNOWN_SIZE) { addHeader(HeaderConstants.HEADER_CONTENT_LENGTH, Long.toString(entity.getAvailableSize()), headers); } if (entity != null) { addHeader(HeaderConstants.HEADER_CONTENT_ENCODING, EncodingWriter.write(entity.getEncodings()), headers); addHeader(HeaderConstants.HEADER_CONTENT_LANGUAGE, LanguageWriter.write(entity.getLanguages()), headers); if (entity.getLocationRef() != null) { addHeader(HeaderConstants.HEADER_CONTENT_LOCATION, entity .getLocationRef().getTargetRef().toString(), headers); } if (entity.getDigest() != null && Digest.ALGORITHM_MD5.equals(entity.getDigest() .getAlgorithm())) { addHeader( HeaderConstants.HEADER_CONTENT_MD5, new String(org.restlet.engine.util.Base64.encode(entity .getDigest().getValue(), false)), headers); } if (entity.getRange() != null) { addHeader(HeaderConstants.HEADER_CONTENT_RANGE, RangeWriter.write(entity.getRange(), entity.getSize()), headers); } if (entity.getMediaType() != null) { String contentType = entity.getMediaType().toString(); // Specify the character set parameter if required if ((entity.getMediaType().getParameters() .getFirstValue("charset") == null) && (entity.getCharacterSet() != null)) { contentType = contentType + "; charset=" + entity.getCharacterSet().getName(); } addHeader(HeaderConstants.HEADER_CONTENT_TYPE, contentType, headers); } if (entity.getExpirationDate() != null) { addHeader(HeaderConstants.HEADER_EXPIRES, DateWriter.write(entity.getExpirationDate()), headers); } if (entity.getModificationDate() != null) { addHeader(HeaderConstants.HEADER_LAST_MODIFIED, DateWriter.write(entity.getModificationDate()), headers); } if (entity.getTag() != null) { addHeader(HeaderConstants.HEADER_ETAG, TagWriter.write(entity.getTag()), headers); } if (entity.getDisposition() != null && !Disposition.TYPE_NONE.equals(entity.getDisposition() .getType())) { addHeader(HeaderConstants.HEADER_CONTENT_DISPOSITION, DispositionWriter.write(entity.getDisposition()), headers); } } } /** * Adds extension headers if they are non-standard headers. * * @param existingHeaders * The headers to update. * @param additionalHeaders * The headers to add. */ public static void addExtensionHeaders(Series existingHeaders, Series additionalHeaders) { if (additionalHeaders != null) { for (Parameter param : additionalHeaders) { if (param.getName().equalsIgnoreCase( HeaderConstants.HEADER_ACCEPT) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_ACCEPT_CHARSET) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_ACCEPT_ENCODING) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_ACCEPT_LANGUAGE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_ACCEPT_RANGES) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_AGE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_ALLOW) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_AUTHENTICATION_INFO) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_AUTHORIZATION) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CACHE_CONTROL) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONNECTION) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_DISPOSITION) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_ENCODING) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LANGUAGE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LENGTH) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LOCATION) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_MD5) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_RANGE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_TYPE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_COOKIE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_DATE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_ETAG) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_EXPECT) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_EXPIRES) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_FROM) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_HOST) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_MATCH) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_MODIFIED_SINCE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_NONE_MATCH) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_RANGE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_IF_UNMODIFIED_SINCE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_LAST_MODIFIED) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_LOCATION) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_MAX_FORWARDS) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_PROXY_AUTHENTICATE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_PROXY_AUTHORIZATION) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_RANGE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_REFERRER) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_RETRY_AFTER) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_SERVER) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_SET_COOKIE) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_SET_COOKIE2) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_USER_AGENT) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_VARY) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_VIA) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_WARNING) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_WWW_AUTHENTICATE)) { // Standard headers that can't be overridden Context.getCurrentLogger() .warning( "Addition of the standard header \"" + param.getName() + "\" is not allowed. Please use the equivalent property in the Restlet API."); } else if (param.getName().equalsIgnoreCase( HeaderConstants.HEADER_PRAGMA) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_TRAILER) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_TRANSFER_ENCODING) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_TRANSFER_EXTENSION) || param.getName().equalsIgnoreCase( HeaderConstants.HEADER_UPGRADE)) { // Standard headers that shouldn't be overridden Context.getCurrentLogger() .info("Addition of the standard header \"" + param.getName() + "\" is discouraged as a future version of the Restlet API will directly support it."); existingHeaders.add(param); } else { existingHeaders.add(param); } } } } /** * Adds the general headers from the {@link Message} to the {@link Series}. * * @param message * The source {@link Message}. * @param headers * The target headers {@link Series}. */ public static void addGeneralHeaders(Message message, Series headers) { addHeader(HeaderConstants.HEADER_CACHE_CONTROL, CacheDirectiveWriter.write(message.getCacheDirectives()), headers); if (message.getDate() == null) { message.setDate(new Date()); } addHeader(HeaderConstants.HEADER_DATE, DateWriter.write(message.getDate()), headers); addHeader(HeaderConstants.HEADER_VIA, RecipientInfoWriter.write(message.getRecipientsInfo()), headers); addHeader(HeaderConstants.HEADER_WARNING, WarningWriter.write(message.getWarnings()), headers); } /** * Adds a header to the given list. Check for exceptions and logs them. * * @param headerName * The header name. * @param headerValue * The header value. * @param headers * The headers list. */ public static void addHeader(String headerName, String headerValue, Series headers) { if ((headerName != null) && (headerValue != null) && (headerValue.length() > 0)) { try { headers.add(headerName, headerValue); } catch (Throwable t) { Context.getCurrentLogger().log(Level.WARNING, "Unable to format the " + headerName + " header", t); } } } /** * Adds the entity headers based on the {@link Representation} to the * {@link Series} when a 304 (Not Modified) status is returned. * * @param entity * The source entity {@link Representation}. * @param headers * The target headers {@link Series}. */ public static void addNotModifiedEntityHeaders(Representation entity, Series headers) { if (entity != null) { if (entity.getTag() != null) { HeaderUtils.addHeader(HeaderConstants.HEADER_ETAG, TagWriter.write(entity.getTag()), headers); } if (entity.getLocationRef() != null) { HeaderUtils.addHeader(HeaderConstants.HEADER_CONTENT_LOCATION, entity.getLocationRef().getTargetRef().toString(), headers); } } } /** * Adds the headers based on the {@link Request} to the given {@link Series} * . * * @param request * The {@link Request} to copy the headers from. * @param headers * The {@link Series} to copy the headers to. */ @SuppressWarnings("unchecked") public static void addRequestHeaders(Request request, Series headers) { ClientInfo clientInfo = request.getClientInfo(); if (!clientInfo.getAcceptedMediaTypes().isEmpty()) { addHeader(HeaderConstants.HEADER_ACCEPT, PreferenceWriter.write(clientInfo.getAcceptedMediaTypes()), headers); } else { addHeader(HeaderConstants.HEADER_ACCEPT, MediaType.ALL.getName(), headers); } if (!clientInfo.getAcceptedCharacterSets().isEmpty()) { addHeader(HeaderConstants.HEADER_ACCEPT_CHARSET, PreferenceWriter.write(clientInfo .getAcceptedCharacterSets()), headers); } if (!clientInfo.getAcceptedEncodings().isEmpty()) { addHeader(HeaderConstants.HEADER_ACCEPT_ENCODING, PreferenceWriter.write(clientInfo.getAcceptedEncodings()), headers); } if (!clientInfo.getAcceptedLanguages().isEmpty()) { addHeader(HeaderConstants.HEADER_ACCEPT_LANGUAGE, PreferenceWriter.write(clientInfo.getAcceptedLanguages()), headers); } if (!clientInfo.getExpectations().isEmpty()) { addHeader(HeaderConstants.HEADER_EXPECT, ExpectationWriter.write(clientInfo.getExpectations()), headers); } if (clientInfo.getFrom() != null) { addHeader(HeaderConstants.HEADER_FROM, request.getClientInfo() .getFrom(), headers); } // Manually add the host name and port when it is potentially // different from the one specified in the target resource reference. Reference hostRef = (request.getResourceRef().getBaseRef() != null) ? request .getResourceRef().getBaseRef() : request.getResourceRef(); if (hostRef.getHostDomain() != null) { String host = hostRef.getHostDomain(); int hostRefPortValue = hostRef.getHostPort(); if ((hostRefPortValue != -1) && (hostRefPortValue != request.getProtocol() .getDefaultPort())) { host = host + ':' + hostRefPortValue; } addHeader(HeaderConstants.HEADER_HOST, host, headers); } Conditions conditions = request.getConditions(); addHeader(HeaderConstants.HEADER_IF_MATCH, TagWriter.write(conditions.getMatch()), headers); addHeader(HeaderConstants.HEADER_IF_NONE_MATCH, TagWriter.write(conditions.getNoneMatch()), headers); if (conditions.getModifiedSince() != null) { addHeader(HeaderConstants.HEADER_IF_MODIFIED_SINCE, DateWriter.write(conditions.getModifiedSince()), headers); } if (conditions.getRangeTag() != null && conditions.getRangeDate() != null) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to format the HTTP If-Range header due to the presence of both entity tag and modification date."); } else if (conditions.getRangeTag() != null) { addHeader(HeaderConstants.HEADER_IF_RANGE, TagWriter.write(conditions.getRangeTag()), headers); } else if (conditions.getRangeDate() != null) { addHeader(HeaderConstants.HEADER_IF_RANGE, DateWriter.write(conditions.getRangeDate()), headers); } if (conditions.getUnmodifiedSince() != null) { addHeader(HeaderConstants.HEADER_IF_UNMODIFIED_SINCE, DateWriter.write(conditions.getUnmodifiedSince()), headers); } if (request.getMaxForwards() > -1) { addHeader(HeaderConstants.HEADER_MAX_FORWARDS, Integer.toString(request.getMaxForwards()), headers); } if (!request.getRanges().isEmpty()) { addHeader(HeaderConstants.HEADER_RANGE, RangeWriter.write(request.getRanges()), headers); } if (request.getReferrerRef() != null) { addHeader(HeaderConstants.HEADER_REFERRER, request.getReferrerRef() .toString(), headers); } if (request.getClientInfo().getAgent() != null) { addHeader(HeaderConstants.HEADER_USER_AGENT, request .getClientInfo().getAgent(), headers); } else { addHeader(HeaderConstants.HEADER_USER_AGENT, Engine.VERSION_HEADER, headers); } if (clientInfo.getExpectations().size() > 0) { addHeader(HeaderConstants.HEADER_ACCEPT_ENCODING, PreferenceWriter.write(clientInfo.getAcceptedEncodings()), headers); } // ---------------------------------- // 3) Add supported extension headers // ---------------------------------- if (request.getCookies().size() > 0) { addHeader(HeaderConstants.HEADER_COOKIE, CookieWriter.write(request.getCookies()), headers); } // ------------------------------------- // 4) Add user-defined extension headers // ------------------------------------- Series additionalHeaders = (Series) request .getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); addExtensionHeaders(headers, additionalHeaders); // --------------------------------------- // 5) Add authorization headers at the end // --------------------------------------- // Add the security headers. NOTE: This must stay at the end because // the AWS challenge scheme requires access to all HTTP headers ChallengeResponse challengeResponse = request.getChallengeResponse(); if (challengeResponse != null) { addHeader( HeaderConstants.HEADER_AUTHORIZATION, org.restlet.engine.security.AuthenticatorUtils .formatResponse(challengeResponse, request, headers), headers); } ChallengeResponse proxyChallengeResponse = request .getProxyChallengeResponse(); if (proxyChallengeResponse != null) { addHeader(HeaderConstants.HEADER_PROXY_AUTHORIZATION, org.restlet.engine.security.AuthenticatorUtils .formatResponse(proxyChallengeResponse, request, headers), headers); } } /** * Adds the headers based on the {@link Response} to the given * {@link Series}. * * @param response * The {@link Response} to copy the headers from. * @param headers * The {@link Series} to copy the headers to. */ @SuppressWarnings("unchecked") public static void addResponseHeaders(Response response, Series headers) { if (response.getServerInfo().isAcceptingRanges()) { addHeader(HeaderConstants.HEADER_ACCEPT_RANGES, "bytes", headers); } if (response.getAge() > 0) { addHeader(HeaderConstants.HEADER_AGE, Integer.toString(response.getAge()), headers); } if (response.getStatus().equals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED) || Method.OPTIONS.equals(response.getRequest().getMethod())) { addHeader(HeaderConstants.HEADER_ALLOW, MethodWriter.write(response.getAllowedMethods()), headers); } if (response.getLocationRef() != null) { // The location header must contain an absolute URI. addHeader(HeaderConstants.HEADER_LOCATION, response .getLocationRef().getTargetRef().toString(), headers); } if (response.getProxyChallengeRequests() != null) { for (ChallengeRequest challengeRequest : response .getProxyChallengeRequests()) { addHeader(HeaderConstants.HEADER_PROXY_AUTHENTICATE, org.restlet.engine.security.AuthenticatorUtils .formatRequest(challengeRequest, response, headers), headers); } } if (response.getRetryAfter() != null) { addHeader(HeaderConstants.HEADER_RETRY_AFTER, DateWriter.write(response.getRetryAfter()), headers); } if ((response.getServerInfo() != null) && (response.getServerInfo().getAgent() != null)) { addHeader(HeaderConstants.HEADER_SERVER, response.getServerInfo() .getAgent(), headers); } else { addHeader(HeaderConstants.HEADER_SERVER, Engine.VERSION_HEADER, headers); } // Send the Vary header only to none-MSIE user agents as MSIE seems // to support partially and badly this header (cf issue 261). if (!((response.getRequest().getClientInfo().getAgent() != null) && response .getRequest().getClientInfo().getAgent().contains("MSIE"))) { // Add the Vary header if content negotiation was used addHeader(HeaderConstants.HEADER_VARY, DimensionWriter.write(response.getDimensions()), headers); } // Set the security data if (response.getChallengeRequests() != null) { for (ChallengeRequest challengeRequest : response .getChallengeRequests()) { addHeader(HeaderConstants.HEADER_WWW_AUTHENTICATE, org.restlet.engine.security.AuthenticatorUtils .formatRequest(challengeRequest, response, headers), headers); } } // ---------------------------------- // 3) Add supported extension headers // ---------------------------------- // Add the Authentication-Info header if (response.getAuthenticationInfo() != null) { addHeader(HeaderConstants.HEADER_AUTHENTICATION_INFO, org.restlet.engine.security.AuthenticatorUtils .formatAuthenticationInfo(response .getAuthenticationInfo()), headers); } // Cookies settings should be written in a single header, but Web // browsers does not seem to support it. for (CookieSetting cookieSetting : response.getCookieSettings()) { addHeader(HeaderConstants.HEADER_SET_COOKIE, CookieSettingWriter.write(cookieSetting), headers); } // ------------------------------------- // 4) Add user-defined extension headers // ------------------------------------- Series additionalHeaders = (Series) response .getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); addExtensionHeaders(headers, additionalHeaders); } /** * Extracts entity headers and updates a given representation or create an * empty one when at least one entity header is present. * * @param headers * The headers to copy. * @param representation * The representation to update or null. * @return a representation updated with the given entity headers. * @throws NumberFormatException * @see HeaderUtils#copyResponseTransportHeaders(Series, Response) */ public static Representation extractEntityHeaders( Iterable headers, Representation representation) throws NumberFormatException { Representation result = (representation == null) ? new EmptyRepresentation() : representation; boolean entityHeaderFound = false; if (headers != null) { for (Parameter header : headers) { if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_TYPE)) { ContentType contentType = new ContentType(header.getValue()); result.setMediaType(contentType.getMediaType()); if ((result.getCharacterSet() == null) || (contentType.getCharacterSet() != null)) { result.setCharacterSet(contentType.getCharacterSet()); } entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LENGTH)) { entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_EXPIRES)) { result.setExpirationDate(HeaderReader.readDate( header.getValue(), false)); entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_ENCODING)) { new EncodingReader(header.getValue()).addValues(result .getEncodings()); entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LANGUAGE)) { new LanguageReader(header.getValue()).addValues(result .getLanguages()); entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_LAST_MODIFIED)) { result.setModificationDate(HeaderReader.readDate( header.getValue(), false)); entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_ETAG)) { result.setTag(Tag.parse(header.getValue())); entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LOCATION)) { result.setLocationRef(header.getValue()); entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_DISPOSITION)) { try { result.setDisposition(new DispositionReader(header .getValue()).readValue()); entityHeaderFound = true; } catch (IOException ioe) { Context.getCurrentLogger().log( Level.WARNING, "Error during Content-Disposition header parsing. Header: " + header.getValue(), ioe); } } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_RANGE)) { org.restlet.engine.http.header.RangeReader.update( header.getValue(), result); entityHeaderFound = true; } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_MD5)) { result.setDigest(new org.restlet.data.Digest( org.restlet.data.Digest.ALGORITHM_MD5, org.restlet.engine.util.Base64.decode(header .getValue()))); entityHeaderFound = true; } } } // If no representation was initially expected and no entity header // is found, then do not return any representation if ((representation == null) && !entityHeaderFound) { result = null; } return result; } /** * Copies headers into a response. * * @param headers * The headers to copy. * @param response * The response to update. */ public static void copyResponseTransportHeaders(Series headers, Response response) { if (headers != null) { for (Parameter header : headers) { if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_LOCATION)) { response.setLocationRef(header.getValue()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_AGE)) { try { response.setAge(Integer.parseInt(header.getValue())); } catch (NumberFormatException nfe) { Context.getCurrentLogger().log( Level.WARNING, "Error during Age header parsing. Header: " + header.getValue(), nfe); } } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_DATE)) { Date date = DateUtils.parse(header.getValue()); if (date == null) { date = new Date(); } response.setDate(date); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_RETRY_AFTER)) { Date retryAfter = DateUtils.parse(header.getValue()); if (retryAfter == null) { // The date might be expressed as a number of seconds try { int retryAfterSecs = Integer.parseInt(header .getValue()); java.util.Calendar calendar = java.util.Calendar .getInstance(); calendar.add(java.util.Calendar.SECOND, retryAfterSecs); retryAfter = calendar.getTime(); } catch (NumberFormatException nfe) { Context.getCurrentLogger().log( Level.WARNING, "Error during Retry-After header parsing. Header: " + header.getValue(), nfe); } } response.setRetryAfter(retryAfter); } else if ((header.getName() .equalsIgnoreCase(HeaderConstants.HEADER_SET_COOKIE)) || (header.getName() .equalsIgnoreCase(HeaderConstants.HEADER_SET_COOKIE2))) { try { CookieSettingReader cr = new CookieSettingReader( header.getValue()); response.getCookieSettings().add(cr.readValue()); } catch (Exception e) { Context.getCurrentLogger().log( Level.WARNING, "Error during cookie setting parsing. Header: " + header.getValue(), e); } } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_WWW_AUTHENTICATE)) { List crs = org.restlet.engine.security.AuthenticatorUtils .parseRequest(response, header.getValue(), headers); response.getChallengeRequests().addAll(crs); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_PROXY_AUTHENTICATE)) { List crs = org.restlet.engine.security.AuthenticatorUtils .parseRequest(response, header.getValue(), headers); response.getProxyChallengeRequests().addAll(crs); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_AUTHENTICATION_INFO)) { AuthenticationInfo authenticationInfo = org.restlet.engine.security.AuthenticatorUtils .parseAuthenticationInfo(header.getValue()); response.setAuthenticationInfo(authenticationInfo); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_SERVER)) { response.getServerInfo().setAgent(header.getValue()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_ALLOW)) { MethodReader .addValues(header, response.getAllowedMethods()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_VARY)) { DimensionReader.addValues(header, response.getDimensions()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_VIA)) { RecipientInfoReader.addValues(header, response.getRecipientsInfo()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_WARNING)) { WarningReader.addValues(header, response.getWarnings()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CACHE_CONTROL)) { CacheDirectiveReader.addValues(header, response.getCacheDirectives()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_ACCEPT_RANGES)) { TokenReader tr = new TokenReader(header.getValue()); response.getServerInfo().setAcceptingRanges( tr.readValues().contains("bytes")); } } } } /** * Returns the content length of the request entity if know, * {@link Representation#UNKNOWN_SIZE} otherwise. * * @return The request content length. */ public static long getContentLength(Series headers) { long contentLength = Representation.UNKNOWN_SIZE; if (headers != null) { // Extract the content length header for (Parameter header : headers) { if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LENGTH)) { try { contentLength = Long.parseLong(header.getValue()); } catch (NumberFormatException e) { contentLength = Representation.UNKNOWN_SIZE; } } } } return contentLength; } /** * Indicates if the given character is alphabetical (a-z or A-Z). * * @param character * The character to test. * @return True if the given character is alphabetical (a-z or A-Z). */ public static boolean isAlpha(int character) { return isUpperCase(character) || isLowerCase(character); } /** * Indicates if the given character is in ASCII range. * * @param character * The character to test. * @return True if the given character is in ASCII range. */ public static boolean isAsciiChar(int character) { return (character >= 0) && (character <= 127); } /** * Indicates if the given character is a carriage return. * * @param character * The character to test. * @return True if the given character is a carriage return. */ public static boolean isCarriageReturn(int character) { return (character == 13); } /** * Indicates if the entity is chunked. * * @return True if the entity is chunked. */ public static boolean isChunkedEncoding(Series headers) { boolean result = false; if (headers != null) { final String header = headers.getFirstValue( HeaderConstants.HEADER_TRANSFER_ENCODING, true); result = "chunked".equalsIgnoreCase(header); } return result; } /** * Indicates if the given character is a comma, the character used as header * value separator. * * @param character * The character to test. * @return True if the given character is a comma. */ public static boolean isComma(int character) { return (character == ','); } /** * Indicates if the given character is a comment text. It means * {@link #isText(int)} returns true and the character is not '(' or ')'. * * @param character * The character to test. * @return True if the given character is a quoted text. */ public static boolean isCommentText(int character) { return isText(character) && (character != '(') && (character != ')'); } /** * Indicates if the connection must be closed. * * @param headers * The headers to test. * @return True if the connection must be closed. */ public static boolean isConnectionClose(Series headers) { boolean result = false; if (headers != null) { String header = headers.getFirstValue( HeaderConstants.HEADER_CONNECTION, true); result = "close".equalsIgnoreCase(header); } return result; } /** * Indicates if the given character is a control character. * * @param character * The character to test. * @return True if the given character is a control character. */ public static boolean isControlChar(int character) { return ((character >= 0) && (character <= 31)) || (character == 127); } /** * Indicates if the given character is a digit (0-9). * * @param character * The character to test. * @return True if the given character is a digit (0-9). */ public static boolean isDigit(int character) { return (character >= '0') && (character <= '9'); } /** * Indicates if the given character is a double quote. * * @param character * The character to test. * @return True if the given character is a double quote. */ public static boolean isDoubleQuote(int character) { return (character == 34); } /** * Indicates if the given character is an horizontal tab. * * @param character * The character to test. * @return True if the given character is an horizontal tab. */ public static boolean isHorizontalTab(int character) { return (character == 9); } /** * Indicates if the given character is in ISO Latin 1 (8859-1) range. Note * that this range is a superset of ASCII and a subrange of Unicode (UTF-8). * * @param character * The character to test. * @return True if the given character is in ISO Latin 1 range. */ public static boolean isLatin1Char(int character) { return (character >= 0) && (character <= 255); } /** * Indicates if the given character is a value separator. * * @param character * The character to test. * @return True if the given character is a value separator. */ public static boolean isLinearWhiteSpace(int character) { return (isCarriageReturn(character) || isSpace(character) || isLineFeed(character) || HeaderUtils .isHorizontalTab(character)); } /** * Indicates if the given character is a line feed. * * @param character * The character to test. * @return True if the given character is a line feed. */ public static boolean isLineFeed(int character) { return (character == 10); } /** * Indicates if the given character is lower case (a-z). * * @param character * The character to test. * @return True if the given character is lower case (a-z). */ public static boolean isLowerCase(int character) { return (character >= 'a') && (character <= 'z'); } /** * Indicates if the given character marks the start of a quoted pair. * * @param character * The character to test. * @return True if the given character marks the start of a quoted pair. */ public static boolean isQuoteCharacter(int character) { return (character == '\\'); } /** * Indicates if the given character is a quoted text. It means * {@link #isText(int)} returns true and {@link #isDoubleQuote(int)} returns * false. * * @param character * The character to test. * @return True if the given character is a quoted text. */ public static boolean isQuotedText(int character) { return isText(character) && !isDoubleQuote(character); } /** * Indicates if the given character is a semicolon, the character used as * header parameter separator. * * @param character * The character to test. * @return True if the given character is a semicolon. */ public static boolean isSemiColon(int character) { return (character == ';'); } /** * Indicates if the given character is a separator. * * @param character * The character to test. * @return True if the given character is a separator. */ public static boolean isSeparator(int character) { switch (character) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } /** * Indicates if the given character is a space. * * @param character * The character to test. * @return True if the given character is a space. */ public static boolean isSpace(int character) { return (character == 32); } /** * Indicates if the given character is textual (ISO Latin 1 and not a * control character). * * @param character * The character to test. * @return True if the given character is textual. */ public static boolean isText(int character) { return isLatin1Char(character) && !isControlChar(character); } /** * Indicates if the token is valid.
    * Only contains valid token characters. * * @param token * The token to check * @return True if the token is valid. */ public static boolean isToken(CharSequence token) { for (int i = 0; i < token.length(); i++) { if (!isTokenChar(token.charAt(i))) { return false; } } return true; } /** * Indicates if the given character is a token character (text and not a * separator). * * @param character * The character to test. * @return True if the given character is a token character (text and not a * separator). */ public static boolean isTokenChar(int character) { return isAsciiChar(character) && !isSeparator(character); } /** * Indicates if the given character is upper case (A-Z). * * @param character * The character to test. * @return True if the given character is upper case (A-Z). */ public static boolean isUpperCase(int character) { return (character >= 'A') && (character <= 'Z'); } /** * Writes a new line. * * @param os * The output stream. * @throws IOException */ public static void writeCRLF(OutputStream os) throws IOException { os.write(13); // CR os.write(10); // LF } /** * Writes a header line. * * @param header * The header to write. * @param os * The output stream. * @throws IOException */ public static void writeHeaderLine(Parameter header, OutputStream os) throws IOException { os.write(StringUtils.getAsciiBytes(header.getName())); os.write(':'); os.write(' '); if (header.getValue() != null) { os.write(StringUtils.getLatin1Bytes(header.getValue())); } os.write(13); // CR os.write(10); // LF } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private HeaderUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ContentTypeReader.java0000664000175000017500000002544211757206346031204 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.util.Series; /** * Content type header reader. * * @author Jerome Louvel */ public class ContentTypeReader extends HeaderReader { /** * Constructor. * * @param header * The header to read. */ public ContentTypeReader(String header) { super(header); } /** * Creates a content type. * * @param mediaType * The media type name. * @param parameters * The parameters parsed. * @return The content type. */ private ContentType createContentType(StringBuilder mediaType, Series parameters) { // Attempt to extract the character set CharacterSet characterSet = null; if (parameters != null) { String charSet = parameters.getFirstValue("charset"); if (charSet != null) { parameters.removeAll("charset"); characterSet = new CharacterSet(charSet); } return new ContentType(new MediaType(mediaType.toString(), parameters), characterSet); } return new ContentType(new MediaType(mediaType.toString()), null); } @Override public ContentType readValue() throws IOException { ContentType result = null; boolean readingMediaType = true; boolean readingParamName = false; boolean readingParamValue = false; StringBuilder mediaTypeBuffer = new StringBuilder(); StringBuilder paramNameBuffer = null; StringBuilder paramValueBuffer = null; Series parameters = null; String nextValue = readRawValue(); int nextIndex = 0; if (nextValue != null) { int nextChar = nextValue.charAt(nextIndex++); while (result == null) { if (readingMediaType) { if (nextChar == -1) { if (mediaTypeBuffer.length() > 0) { // End of metadata section // No parameters detected result = createContentType(mediaTypeBuffer, null); paramNameBuffer = new StringBuilder(); } else { // Ignore empty metadata name } } else if (nextChar == ';') { if (mediaTypeBuffer.length() > 0) { // End of mediaType section // Parameters detected readingMediaType = false; readingParamName = true; paramNameBuffer = new StringBuilder(); parameters = new Form(); } else { throw new IOException( "Empty mediaType name detected."); } } else if (HeaderUtils.isSpace(nextChar)) { // Ignore spaces } else if (HeaderUtils.isText(nextChar)) { mediaTypeBuffer.append((char) nextChar); } else { throw new IOException( "The " + (char) nextChar + " character isn't allowed in a media type name."); } } else if (readingParamName) { if (nextChar == '=') { if (paramNameBuffer.length() > 0) { // End of parameter name section readingParamName = false; readingParamValue = true; paramValueBuffer = new StringBuilder(); } else { throw new IOException( "Empty parameter name detected."); } } else if (nextChar == -1) { if (paramNameBuffer.length() > 0) { // End of parameters section parameters.add(Parameter.create(paramNameBuffer, null)); result = createContentType(mediaTypeBuffer, parameters); } else if (paramNameBuffer.length() == 0) { result = createContentType(mediaTypeBuffer, parameters); } else { throw new IOException( "Empty parameter name detected."); } } else if (nextChar == ';') { // End of parameter parameters.add(Parameter.create(paramNameBuffer, null)); paramNameBuffer = new StringBuilder(); readingParamName = true; readingParamValue = false; } else if (HeaderUtils.isSpace(nextChar) && (paramNameBuffer.length() == 0)) { // Ignore white spaces } else if (HeaderUtils.isTokenChar(nextChar)) { paramNameBuffer.append((char) nextChar); } else { throw new IOException( "The \"" + (char) nextChar + "\" character isn't allowed in a media type parameter name."); } } else if (readingParamValue) { if (nextChar == -1) { if (paramValueBuffer.length() > 0) { // End of parameters section parameters.add(Parameter.create(paramNameBuffer, paramValueBuffer)); result = createContentType(mediaTypeBuffer, parameters); } else { throw new IOException( "Empty parameter value detected"); } } else if (nextChar == ';') { // End of parameter parameters.add(Parameter.create(paramNameBuffer, paramValueBuffer)); paramNameBuffer = new StringBuilder(); readingParamName = true; readingParamValue = false; } else if ((nextChar == '"') && (paramValueBuffer.length() == 0)) { // Parse the quoted string boolean done = false; boolean quotedPair = false; while ((!done) && (nextChar != -1)) { nextChar = (nextIndex < nextValue.length()) ? nextValue .charAt(nextIndex++) : -1; if (quotedPair) { // End of quoted pair (escape sequence) if (HeaderUtils.isText(nextChar)) { paramValueBuffer.append((char) nextChar); quotedPair = false; } else { throw new IOException( "Invalid character \"" + (char) nextChar + "\" detected in quoted string. Please check your value"); } } else if (HeaderUtils.isDoubleQuote(nextChar)) { // End of quoted string done = true; } else if (nextChar == '\\') { // Begin of quoted pair (escape sequence) quotedPair = true; } else if (HeaderUtils.isText(nextChar)) { paramValueBuffer.append((char) nextChar); } else { throw new IOException( "Invalid character \"" + (char) nextChar + "\" detected in quoted string. Please check your value"); } } } else if (HeaderUtils.isTokenChar(nextChar)) { paramValueBuffer.append((char) nextChar); } else { throw new IOException( "The \"" + (char) nextChar + "\" character isn't allowed in a media type parameter value."); } } nextChar = (nextIndex < nextValue.length()) ? nextValue .charAt(nextIndex++) : -1; } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ExpectationReader.java0000664000175000017500000000500411757206346031203 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import org.restlet.data.ClientInfo; import org.restlet.data.Expectation; import org.restlet.data.Parameter; /** * Expectation header reader. * * @author Jerome Louvel */ public class ExpectationReader extends HeaderReader { /** * Adds values to the given collection. * * @param header * The header to read. * @param clientInfo * The client info to update. */ public static void addValues(String header, ClientInfo clientInfo) { if (header != null) { new ExpectationReader(header).addValues(clientInfo .getExpectations()); } } /** * Constructor. * * @param header * The header to read. */ public ExpectationReader(String header) { super(header); } @Override protected Parameter createParameter(String name, String value) { return new Expectation(name, value); } @Override public Expectation readValue() throws IOException { Expectation result = (Expectation) readParameter(); while (skipParameterSeparator()) { result.getParameters().add(readParameter()); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/EncodingReader.java0000664000175000017500000000365311757206346030456 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Collection; import org.restlet.data.Encoding; /** * Encoding header reader. * * @author Jerome Louvel */ public class EncodingReader extends HeaderReader { /** * Constructor. * * @param header * The header to read. */ public EncodingReader(String header) { super(header); } @Override protected boolean canAdd(Encoding value, Collection values) { return value != null && !Encoding.IDENTITY.equals(value); } @Override public Encoding readValue() throws IOException { return Encoding.valueOf(readToken()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ChallengeRequestReader.java0000664000175000017500000001157711757206346032167 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import static org.restlet.engine.http.header.HeaderUtils.isSpace; import java.io.IOException; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeScheme; import org.restlet.data.Parameter; /** * Challenge request header reader. * * @author Thierry Boileau */ public class ChallengeRequestReader extends HeaderReader { public static void main(String[] args) throws Exception { String str = "Basic realm=\"Control Panel\""; ChallengeRequestReader r = new ChallengeRequestReader(str); ChallengeRequest c = r.readValue(); System.out.println(c.getScheme()); System.out.println(c.getRawValue()); str = "Digest realm=\"Control Panel\", domain=\"/controlPanel\", nonce=\"15bb54af506016d4414a025d4c84e34c\", algorithm=MD5, qop=\"auth,auth-int\""; r = new ChallengeRequestReader(str); c = r.readValue(); System.out.println(c.getScheme()); System.out.println(c.getRawValue()); str = "Negotiate"; r = new ChallengeRequestReader(str); c = r.readValue(); System.out.println(c.getScheme()); System.out.println(c.getRawValue()); str = "Basic realm=\"Control Panel\",Digest realm=\"Control Panel\", domain=\"/controlPanel\", nonce=\"15bb54af506016d4414a025d4c84e34c\", algorithm=MD5, qop=\"auth,auth-int\""; r = new ChallengeRequestReader(str); System.out.println("list"); for (ChallengeRequest challengeRequest : r.readValues()) { System.out.println(challengeRequest.getScheme()); System.out.println(challengeRequest.getRawValue()); } } /** * Constructor. * * @param header * The header to read. */ public ChallengeRequestReader(String header) { super(header); } @Override public ChallengeRequest readValue() throws IOException { ChallengeRequest result = null; // The challenge is that this header is a comma separated lst of // challenges, and that each challenges is also a comma separated list, // but of parameters. skipSpaces(); if (peek() != -1) { String scheme = readToken(); result = new ChallengeRequest(new ChallengeScheme("HTTP_" + scheme, scheme)); skipSpaces(); // Header writer that will reconstruct the raw value of a challenge. HeaderWriter w = new HeaderWriter() { @Override public HeaderWriter append(Parameter value) { appendExtension(value); return this; } }; boolean stop = false; while (peek() != -1 && !stop) { boolean sepSkipped = skipValueSeparator(); // Record the start of the segment mark(); // Read a token and the next character. readToken(); int nextChar = read(); reset(); if (isSpace(nextChar)) { // A new scheme has been discovered. stop = true; } else { // The next segment is considered as a parameter if (sepSkipped) { // Add the skipped value separator. w.appendValueSeparator(); } // Append the parameter w.append(readParameter()); } } result.setRawValue(w.toString()); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/HeaderWriter.java0000664000175000017500000002055111757206346030166 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.StringWriter; import java.util.Collection; import org.restlet.data.CharacterSet; import org.restlet.data.Encoding; import org.restlet.data.Parameter; import org.restlet.data.Reference; /** * HTTP-style header writer. * * @param * The value type. * @author Jerome Louvel */ public abstract class HeaderWriter extends StringWriter { @Override public HeaderWriter append(char c) { super.append(c); return this; } /** * Appends an array of characters. * * @param cs * The array of characters. * @return This writer. */ public HeaderWriter append(char[] cs) { if (cs != null) { for (char c : cs) { append(c); } } return this; } @Override public HeaderWriter append(CharSequence csq) { super.append(csq); return this; } /** * Appends a collection of values. * * @param values * The collection of values to append. * @return This writer. */ public HeaderWriter append(Collection values) { if ((values != null) && !values.isEmpty()) { boolean first = true; for (V value : values) { if (canWrite(value)) { if (first) { first = false; } else { appendValueSeparator(); } append(value); } } } return this; } /** * Appends an integer. * * @param i * The value to append. * @return This writer. */ public HeaderWriter append(int i) { return append(Integer.toString(i)); } /** * Appends a long. * * @param l * The value to append. * @return This writer. */ public HeaderWriter append(long l) { return append(Long.toString(l)); } /** * Appends a value. * * @param value * The value. * @return This writer. */ public abstract HeaderWriter append(V value); /** * Appends a string as an HTTP comment, surrounded by parenthesis and with * quoted pairs if needed. * * @param content * The comment to write. * @return This writer. */ public HeaderWriter appendComment(String content) { append('('); char c; for (int i = 0; i < content.length(); i++) { c = content.charAt(i); if (HeaderUtils.isCommentText(c)) { append(c); } else { appendQuotedPair(c); } } return append(')'); } /** * Formats and appends a parameter as an extension. If the value is not a * token, then it is quoted. * * @param extension * The parameter to format as an extension. * @return This writer. */ public HeaderWriter appendExtension(Parameter extension) { if (extension != null) { return appendExtension(extension.getName(), extension.getValue()); } else { return this; } } /** * Appends an extension. If the value is not a token, then it is quoted. * * @param name * The extension name. * @param value * The extension value. * @return This writer. */ public HeaderWriter appendExtension(String name, String value) { if ((name != null) && (name.length() > 0)) { append(name); if ((value != null) && (value.length() > 0)) { append("="); if (HeaderUtils.isToken(value)) { append(value); } else { appendQuotedString(value); } } } return this; } /** * Appends a semicolon as a parameter separator. * * @return This writer. */ public HeaderWriter appendParameterSeparator() { return append(";"); } /** * Appends a product description. * * @param name * The product name token. * @param version * The product version token. * @return This writer. */ public HeaderWriter appendProduct(String name, String version) { appendToken(name); if (version != null) { append('/').appendToken(version); } return this; } /** * Appends a quoted character, prefixing it with a backslash. * * @param character * The character to quote. * @return This writer. */ public HeaderWriter appendQuotedPair(char character) { return append('\\').append(character); } /** * Appends a quoted string. * * @param content * The string to quote and write. * @return This writer. */ public HeaderWriter appendQuotedString(String content) { if ((content != null) && (content.length() > 0)) { append('"'); char c; for (int i = 0; i < content.length(); i++) { c = content.charAt(i); if (HeaderUtils.isQuotedText(c)) { append(c); } else { appendQuotedPair(c); } } append('"'); } return this; } /** * Appends a space character. * * @return This writer. */ public HeaderWriter appendSpace() { return append(' '); } /** * Appends a token. * * @param token * The token to write. * @return This writer. */ public HeaderWriter appendToken(String token) { if (HeaderUtils.isToken(token)) { return append(token); } else { throw new IllegalArgumentException( "Unexpected character found in token: " + token); } } /** * Formats and appends a source string as an URI encoded string. * * @param source * The source string to format. * @param characterSet * The supported character encoding. * @return This writer. */ public HeaderWriter appendUriEncoded(CharSequence source, CharacterSet characterSet) { return append(Reference.encode(source.toString(), characterSet)); } /** * Appends a comma as a value separator. * * @return This writer. */ public HeaderWriter appendValueSeparator() { return append(", "); } /** * Indicates if the value can be written to the header. Useful to prevent * the writing of {@link Encoding#IDENTITY} constants for example. By * default it returns true for non null values. * * @param value * The value to add. * @return True if the value can be added. */ protected boolean canWrite(V value) { return (value != null); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/RangeReader.java0000664000175000017500000001040711757206346027757 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.ArrayList; import java.util.List; import org.restlet.data.Range; import org.restlet.representation.Representation; /** * Range header reader. * * @author Jerome Louvel */ public class RangeReader { /** * Parse the Content-Range header value and update the given representation. * * @param value * Content-range header. * @param representation * Representation to update. */ public static void update(String value, Representation representation) { String prefix = "bytes "; if (value != null && value.startsWith(prefix)) { value = value.substring(prefix.length()); int index = value.indexOf("-"); int index1 = value.indexOf("/"); if (index != -1) { long startIndex = (index == 0) ? Range.INDEX_LAST : Long .parseLong(value.substring(0, index)); long endIndex = Long.parseLong(value.substring(index + 1, index1)); representation.setRange(new Range(startIndex, endIndex - startIndex + 1)); } String strLength = value.substring(index1 + 1, value.length()); if (!("*".equals(strLength))) { representation.setSize(Long.parseLong(strLength)); } } } /** * Parse the Range header and returns the list of corresponding Range * objects. * * @param rangeHeader * The Range header value. * @return The list of corresponding Range objects. */ public static List read(String rangeHeader) { List result = new ArrayList(); String prefix = "bytes="; if (rangeHeader != null && rangeHeader.startsWith(prefix)) { rangeHeader = rangeHeader.substring(prefix.length()); String[] array = rangeHeader.split(","); for (int i = 0; i < array.length; i++) { String value = array[i].trim(); long index = 0; long length = 0; if (value.startsWith("-")) { index = Range.INDEX_LAST; length = Long.parseLong(value.substring(1)); } else if (value.endsWith("-")) { index = Long.parseLong(value.substring(0, value.length() - 1)); length = Range.SIZE_MAX; } else { String[] tab = value.split("-"); if (tab.length == 2) { index = Long.parseLong(tab[0]); length = Long.parseLong(tab[1]) - index + 1; } } result.add(new Range(index, length)); } } return result; } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private RangeReader() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/CacheDirectiveWriter.java0000664000175000017500000000372511757206346031644 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.CacheDirective; /** * Cache directive header writer. * * @author Thierry Boileau */ public class CacheDirectiveWriter extends HeaderWriter { /** * Writes a list of cache directives with a comma separator. * * @param directives * The list of cache directives. * @return The formatted list of cache directives. */ public static String write(List directives) { return new CacheDirectiveWriter().append(directives).toString(); } @Override public CacheDirectiveWriter append(CacheDirective directive) { appendExtension(directive); return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ProductReader.java0000664000175000017500000001312211757206346030340 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.ArrayList; import java.util.List; import org.restlet.data.Product; /** * User agent header reader. * * @author Thierry Boileau */ public class ProductReader { /** * Parses the given user agent String to a list of Product instances. * * @param userAgent * @return the List of Product objects parsed from the String * @throws IllegalArgumentException * Thrown if the String can not be parsed as a list of Product * instances. */ public static List read(String userAgent) throws IllegalArgumentException { final List result = new ArrayList(); if (userAgent != null) { String token = null; String version = null; String comment = null; final char[] tab = userAgent.trim().toCharArray(); StringBuilder tokenBuilder = new StringBuilder(); StringBuilder versionBuilder = null; StringBuilder commentBuilder = null; int index = 0; boolean insideToken = true; boolean insideVersion = false; boolean insideComment = false; for (index = 0; index < tab.length; index++) { final char c = tab[index]; if (insideToken) { if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == ' ')) { tokenBuilder.append(c); } else { token = tokenBuilder.toString().trim(); insideToken = false; if (c == '/') { insideVersion = true; versionBuilder = new StringBuilder(); } else if (c == '(') { insideComment = true; commentBuilder = new StringBuilder(); } } } else { if (insideVersion) { if (c != ' ') { versionBuilder.append(c); } else { insideVersion = false; version = versionBuilder.toString(); } } else { if (c == '(') { insideComment = true; commentBuilder = new StringBuilder(); } else { if (insideComment) { if (c == ')') { insideComment = false; comment = commentBuilder.toString(); result.add(new Product(token, version, comment)); insideToken = true; tokenBuilder = new StringBuilder(); } else { commentBuilder.append(c); } } else { result.add(new Product(token, version, null)); insideToken = true; tokenBuilder = new StringBuilder(); tokenBuilder.append(c); } } } } } if (insideComment) { comment = commentBuilder.toString(); result.add(new Product(token, version, comment)); } else { if (insideVersion) { version = versionBuilder.toString(); result.add(new Product(token, version, null)); } else { if (insideToken && (tokenBuilder.length() > 0)) { token = tokenBuilder.toString(); result.add(new Product(token, null, null)); } } } } return result; } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private ProductReader() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/package.html0000664000175000017500000000014711757206350027211 0ustar jamespagejamespage Supports HTTP header parsing and formatting.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/MetadataWriter.java0000664000175000017500000000307111757206346030514 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import org.restlet.data.Metadata; /** * Metadata header writer. * * @author Jerome Louvel */ public class MetadataWriter extends HeaderWriter { @Override public MetadataWriter append(M metadata) { return (MetadataWriter) append(metadata.getName()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/DimensionWriter.java0000664000175000017500000000715211757206346030725 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.Collection; import org.restlet.data.Dimension; /** * Dimension header writer. * * @author Thierry Boileau */ public class DimensionWriter extends HeaderWriter { /** * Creates a vary header from the given dimensions. * * @param dimensions * The dimensions to copy to the response. * @return Returns the Vary header or null, if dimensions is null or empty. */ public static String write(Collection dimensions) { return new DimensionWriter().append(dimensions).toString(); } /** * Appends a collection of dimensions as a header. * * @param dimensions * The dimensions to format. * @return This writer. */ public DimensionWriter append(Collection dimensions) { if ((dimensions != null) && !dimensions.isEmpty()) { if (dimensions.contains(Dimension.CLIENT_ADDRESS) || dimensions.contains(Dimension.TIME) || dimensions.contains(Dimension.UNSPECIFIED)) { // From an HTTP point of view the representations can // vary in unspecified ways append("*"); } else { boolean first = true; for (Dimension dimension : dimensions) { if (first) { first = false; } else { append(", "); } append(dimension); } } } return this; } @Override public HeaderWriter append(Dimension dimension) { if (dimension == Dimension.CHARACTER_SET) { append(HeaderConstants.HEADER_ACCEPT_CHARSET); } else if (dimension == Dimension.CLIENT_AGENT) { append(HeaderConstants.HEADER_USER_AGENT); } else if (dimension == Dimension.ENCODING) { append(HeaderConstants.HEADER_ACCEPT_ENCODING); } else if (dimension == Dimension.LANGUAGE) { append(HeaderConstants.HEADER_ACCEPT_LANGUAGE); } else if (dimension == Dimension.MEDIA_TYPE) { append(HeaderConstants.HEADER_ACCEPT); } else if (dimension == Dimension.AUTHORIZATION) { append(HeaderConstants.HEADER_AUTHORIZATION); } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/PreferenceReader.java0000664000175000017500000004117511757206346031007 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Iterator; import static org.restlet.engine.http.header.HeaderUtils.*; import org.restlet.data.CharacterSet; import org.restlet.data.ClientInfo; import org.restlet.data.Encoding; import org.restlet.data.Form; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Parameter; import org.restlet.data.Preference; import org.restlet.util.Series; /** * Preference header reader. Works for character sets, encodings, languages or * media types. * * @author Jerome Louvel */ public class PreferenceReader extends HeaderReader> { public static final int TYPE_CHARACTER_SET = 1; public static final int TYPE_ENCODING = 2; public static final int TYPE_LANGUAGE = 3; public static final int TYPE_MEDIA_TYPE = 4; /** * Parses character set preferences from a header. * * @param acceptCharsetHeader * The header to parse. * @param clientInfo * The client info to update. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void addCharacterSets(String acceptCharsetHeader, ClientInfo clientInfo) { if (acceptCharsetHeader != null) { // Implementation according to // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2 if (acceptCharsetHeader.length() == 0) { clientInfo.getAcceptedCharacterSets().add( new Preference(CharacterSet.ISO_8859_1)); } else { PreferenceReader pr = new PreferenceReader( PreferenceReader.TYPE_CHARACTER_SET, acceptCharsetHeader); pr.addValues(clientInfo.getAcceptedCharacterSets()); } } else { clientInfo.getAcceptedCharacterSets().add( new Preference(CharacterSet.ALL)); } } /** * Parses encoding preferences from a header. * * @param acceptEncodingHeader * The header to parse. * @param clientInfo * The client info to update. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void addEncodings(String acceptEncodingHeader, ClientInfo clientInfo) { if (acceptEncodingHeader != null) { PreferenceReader pr = new PreferenceReader( PreferenceReader.TYPE_ENCODING, acceptEncodingHeader); pr.addValues(clientInfo.getAcceptedEncodings()); } else { clientInfo.getAcceptedEncodings().add( new Preference(Encoding.IDENTITY)); } } /** * Adds language preferences from a header. * * @param acceptLanguageHeader * The header to parse. * @param clientInfo * The client info to update. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void addLanguages(String acceptLanguageHeader, ClientInfo clientInfo) { if (acceptLanguageHeader != null) { PreferenceReader pr = new PreferenceReader( PreferenceReader.TYPE_LANGUAGE, acceptLanguageHeader); pr.addValues(clientInfo.getAcceptedLanguages()); } else { clientInfo.getAcceptedLanguages().add(new Preference(Language.ALL)); } } /** * Parses media type preferences from a header. * * @param acceptMediaTypeHeader * The header to parse. * @param clientInfo * The client info to update. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void addMediaTypes(String acceptMediaTypeHeader, ClientInfo clientInfo) { if (acceptMediaTypeHeader != null) { PreferenceReader pr = new PreferenceReader( PreferenceReader.TYPE_MEDIA_TYPE, acceptMediaTypeHeader); pr.addValues(clientInfo.getAcceptedMediaTypes()); } else { clientInfo.getAcceptedMediaTypes().add( new Preference(MediaType.ALL)); } } /** * Parses a quality value.
    * If the quality is invalid, an IllegalArgumentException is thrown. * * @param quality * The quality value as a string. * @return The parsed quality value as a float. */ public static float readQuality(String quality) { try { float result = Float.valueOf(quality); if (PreferenceWriter.isValidQuality(result)) { return result; } throw new IllegalArgumentException( "Invalid quality value detected. Value must be between 0 and 1."); } catch (NumberFormatException nfe) { throw new IllegalArgumentException( "Invalid quality value detected. Value must be between 0 and 1."); } } /** The type of metadata read. */ private volatile int type; /** * Constructor. * * @param type * The type of metadata read. * @param header * The header to read. */ public PreferenceReader(int type, String header) { super(header); this.type = type; } /** * Creates a new preference. * * @param metadata * The metadata name. * @param parameters * The parameters list. * @return The new preference. */ @SuppressWarnings("unchecked") protected Preference createPreference(CharSequence metadata, Series parameters) { Preference result; if (parameters == null) { result = new Preference(); switch (this.type) { case TYPE_CHARACTER_SET: result.setMetadata((T) CharacterSet.valueOf(metadata.toString())); break; case TYPE_ENCODING: result.setMetadata((T) Encoding.valueOf(metadata.toString())); break; case TYPE_LANGUAGE: result.setMetadata((T) Language.valueOf(metadata.toString())); break; case TYPE_MEDIA_TYPE: result.setMetadata((T) MediaType.valueOf(metadata.toString())); break; } } else { final Series mediaParams = extractMediaParams(parameters); final float quality = extractQuality(parameters); result = new Preference(null, quality, parameters); switch (this.type) { case TYPE_CHARACTER_SET: result.setMetadata((T) new CharacterSet(metadata.toString())); break; case TYPE_ENCODING: result.setMetadata((T) new Encoding(metadata.toString())); break; case TYPE_LANGUAGE: result.setMetadata((T) new Language(metadata.toString())); break; case TYPE_MEDIA_TYPE: result.setMetadata((T) new MediaType(metadata.toString(), mediaParams)); break; } } return result; } /** * Extract the media parameters. Only leave as the quality parameter if * found. Modifies the parameters list. * * @param parameters * All the preference parameters. * @return The media parameters. */ protected Series extractMediaParams(Series parameters) { Series result = null; boolean qualityFound = false; Parameter param = null; if (parameters != null) { result = new Form(); for (final Iterator iter = parameters.iterator(); !qualityFound && iter.hasNext();) { param = iter.next(); if (param.getName().equals("q")) { qualityFound = true; } else { iter.remove(); result.add(param); } } } return result; } /** * Extract the quality value. If the value is not found, 1 is returned. * * @param parameters * The preference parameters. * @return The quality value. */ protected float extractQuality(Series parameters) { float result = 1F; boolean found = false; if (parameters != null) { Parameter param = null; for (final Iterator iter = parameters.iterator(); !found && iter.hasNext();) { param = iter.next(); if (param.getName().equals("q")) { result = readQuality(param.getValue()); found = true; // Remove the quality parameter as we will directly store it // in the Preference object iter.remove(); } } } return result; } /** * Read the next preference. * * @return The next preference. */ public Preference readValue() throws IOException { Preference result = null; boolean readingMetadata = true; boolean readingParamName = false; boolean readingParamValue = false; StringBuilder metadataBuffer = new StringBuilder(); StringBuilder paramNameBuffer = null; StringBuilder paramValueBuffer = null; Series parameters = null; int next = 0; while (result == null) { next = read(); if (readingMetadata) { if ((next == -1) || isComma(next)) { if (metadataBuffer.length() > 0) { // End of metadata section // No parameters detected result = createPreference(metadataBuffer, null); } else { // Ignore empty metadata name break; } } else if (next == ';') { if (metadataBuffer.length() > 0) { // End of metadata section // Parameters detected readingMetadata = false; readingParamName = true; paramNameBuffer = new StringBuilder(); parameters = new Form(); } else { throw new IOException("Empty metadata name detected."); } } else if (isSpace(next)) { // Ignore spaces } else if (isText(next)) { metadataBuffer.append((char) next); } else { throw new IOException("Unexpected character \"" + (char) next + "\" detected."); } } else if (readingParamName) { if (next == '=') { if (paramNameBuffer.length() > 0) { // End of parameter name section readingParamName = false; readingParamValue = true; paramValueBuffer = new StringBuilder(); } else { throw new IOException("Empty parameter name detected."); } } else if ((next == -1) || isComma(next)) { if (paramNameBuffer.length() > 0) { // End of parameters section parameters.add(Parameter.create(paramNameBuffer, null)); result = createPreference(metadataBuffer, parameters); } else { throw new IOException("Empty parameter name detected."); } } else if (next == ';') { // End of parameter parameters.add(Parameter.create(paramNameBuffer, null)); paramNameBuffer = new StringBuilder(); readingParamName = true; readingParamValue = false; } else if (isSpace(next) && (paramNameBuffer.length() == 0)) { // Ignore white spaces } else if (isTokenChar(next)) { paramNameBuffer.append((char) next); } else { throw new IOException("Unexpected character \"" + (char) next + "\" detected."); } } else if (readingParamValue) { if ((next == -1) || isComma(next) || isSpace(next)) { if (paramValueBuffer.length() > 0) { // End of parameters section parameters.add(Parameter.create(paramNameBuffer, paramValueBuffer)); result = createPreference(metadataBuffer, parameters); } else { throw new IOException("Empty parameter value detected"); } } else if (next == ';') { // End of parameter parameters.add(Parameter.create(paramNameBuffer, paramValueBuffer)); paramNameBuffer = new StringBuilder(); readingParamName = true; readingParamValue = false; } else if ((next == '"') && (paramValueBuffer.length() == 0)) { // Parse the quoted string boolean done = false; boolean quotedPair = false; while ((!done) && (next != -1)) { next = read(); if (quotedPair) { // End of quoted pair (escape sequence) if (isText(next)) { paramValueBuffer.append((char) next); quotedPair = false; } else { throw new IOException( "Invalid character detected in quoted string. Please check your value"); } } else if (isDoubleQuote(next)) { // End of quoted string done = true; } else if (next == '\\') { // Begin of quoted pair (escape sequence) quotedPair = true; } else if (isText(next)) { paramValueBuffer.append((char) next); } else { throw new IOException( "Invalid character detected in quoted string. Please check your value"); } } } else if (isTokenChar(next)) { paramValueBuffer.append((char) next); } else { throw new IOException("Unexpected character \"" + (char) next + "\" detected."); } } } if (isComma(next)) { // Unread character which isn't part of the value unread(); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ProductWriter.java0000664000175000017500000000507211757206346030417 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.Iterator; import java.util.List; import org.restlet.data.Product; /** * User agent header writer. * * @author Thierry Boileau */ public class ProductWriter { /** * Formats the given List of Products to a String. * * @param products * The list of products to format. * @return the List of Products as String. */ public static String write(List products) { StringBuilder builder = new StringBuilder(); for (Iterator iterator = products.iterator(); iterator .hasNext();) { Product product = iterator.next(); if ((product.getName() == null) || (product.getName().length() == 0)) { throw new IllegalArgumentException( "Product name cannot be null."); } builder.append(product.getName()); if (product.getVersion() != null) { builder.append("/").append(product.getVersion()); } if (product.getComment() != null) { builder.append(" (").append(product.getComment()).append(")"); } if (iterator.hasNext()) { builder.append(" "); } } return builder.toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/TokenReader.java0000664000175000017500000000325111757206346030002 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; /** * Token header reader. * * @author Jerome Louvel */ public class TokenReader extends HeaderReader { /** * Constructor. * * @param header * The header to read. */ public TokenReader(String header) { super(header); } @Override public String readValue() throws IOException { return readToken(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/RecipientInfoReader.java0000664000175000017500000000553011757206346031462 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Collection; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.RecipientInfo; /** * Recipient info header reader. * * @author Jerome Louvel */ public class RecipientInfoReader extends HeaderReader { /** * Adds values to the given collection. * * @param header * The header to read. * @param collection * The collection to update. */ public static void addValues(Parameter header, Collection collection) { new RecipientInfoReader(header.getValue()).addValues(collection); } /** * Constructor. * * @param header * The header to read. */ public RecipientInfoReader(String header) { super(header); } @Override public RecipientInfo readValue() throws IOException { RecipientInfo result = new RecipientInfo(); String protocolToken = readToken(); if (peek() == '/') { read(); result.setProtocol(new Protocol(protocolToken, protocolToken, null, -1, readToken())); } else { result.setProtocol(new Protocol("HTTP", "HTTP", null, -1, protocolToken)); } // Move to the next text if (skipSpaces()) { result.setName(readRawText()); // Move to the next text if (skipSpaces()) { result.setComment(readComment()); } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/RangeWriter.java0000664000175000017500000001123411757206346030030 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.Range; import org.restlet.representation.Representation; /** * Range header writer. * * @author Jerome Louvel */ public class RangeWriter extends HeaderWriter { /** * Format {@code ranges} as a Range header value * * @param ranges * List of ranges to format * @return {@code ranges} formatted or null if the list is null or empty. */ public static String write(List ranges) { return new RangeWriter().append(ranges).toString(); } /** * Format {@code range} as a Content-Range header value * * @param range * Range to format * @param size * Total size of the entity * @return {@code range} formatted */ public static String write(Range range, long size) { StringBuilder b = new StringBuilder("bytes "); if (range.getIndex() >= Range.INDEX_FIRST) { b.append(range.getIndex()); b.append("-"); if (range.getSize() != Range.SIZE_MAX) { b.append(range.getIndex() + range.getSize() - 1); } else { if (size != Representation.UNKNOWN_SIZE) { b.append(size - 1); } else { throw new IllegalArgumentException( "The entity has an unknown size, can't determine the last byte position."); } } } else if (range.getIndex() == Range.INDEX_LAST) { if (range.getSize() != Range.SIZE_MAX) { if (size != Representation.UNKNOWN_SIZE) { b.append(size - range.getSize()); b.append("-"); b.append(size - 1); } else { throw new IllegalArgumentException( "The entity has an unknown size, can't determine the last byte position."); } } else { // This is not a valid range. throw new IllegalArgumentException( "The range provides no index and no size, it is invalid."); } } if (size != Representation.UNKNOWN_SIZE) { b.append("/").append(size); } else { b.append("/*"); } return b.toString(); } /** * Format {@code ranges} as a Range header value * * @param ranges * List of ranges to format * @return This writer. */ public RangeWriter append(List ranges) { if (ranges == null || ranges.isEmpty()) { return this; } append("bytes="); for (int i = 0; i < ranges.size(); i++) { if (i > 0) { append(", "); } append(ranges.get(i)); } return this; } @Override public HeaderWriter append(Range range) { if (range.getIndex() >= Range.INDEX_FIRST) { append(range.getIndex()); append("-"); if (range.getSize() != Range.SIZE_MAX) { append(range.getIndex() + range.getSize() - 1); } } else if (range.getIndex() == Range.INDEX_LAST) { append("-"); if (range.getSize() != Range.SIZE_MAX) { append(range.getSize()); } } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/CookieWriter.java0000664000175000017500000001216411757206346030210 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.Iterator; import java.util.List; import java.util.Map; import org.restlet.data.Cookie; /** * Cookie header writer. * * @author Jerome Louvel */ public class CookieWriter extends HeaderWriter { /** * Gets the cookies whose name is a key in the given map. If a matching * cookie is found, its value is put in the map. * * @param source * The source list of cookies. * @param destination * The cookies map controlling the reading. */ public static void getCookies(List source, Map destination) { Cookie cookie; for (final Iterator iter = source.iterator(); iter.hasNext();) { cookie = iter.next(); if (destination.containsKey(cookie.getName())) { destination.put(cookie.getName(), cookie); } } } /** * Writes a cookie. * * @param cookie * The cookie to format. * @return The formatted cookie. * @throws IllegalArgumentException * If the Cookie contains illegal values. */ public static String write(Cookie cookie) throws IllegalArgumentException { return new CookieWriter().append(cookie).toString(); } /** * Writes a cookie. * * @param cookies * The cookies to format. * @return The formatted cookie. */ public static String write(List cookies) { return new CookieWriter().append(cookies).toString(); } @Override public CookieWriter append(Cookie cookie) throws IllegalArgumentException { String name = cookie.getName(); String value = cookie.getValue(); int version = cookie.getVersion(); if ((name == null) || (name.length() == 0)) { throw new IllegalArgumentException( "Can't write cookie. Invalid name detected"); } appendValue(name, 0).append('='); // Append the value if ((value != null) && (value.length() > 0)) { appendValue(value, version); } if (version > 0) { // Append the path String path = cookie.getPath(); if ((path != null) && (path.length() > 0)) { append("; $Path="); appendQuotedString(path); } // Append the domain String domain = cookie.getDomain(); if ((domain != null) && (domain.length() > 0)) { append("; $Domain="); appendQuotedString(domain); } } return this; } /** * Appends a list of cookies as an HTTP header. * * @param cookies * The list of cookies to format. * @return This writer. */ public CookieWriter append(List cookies) { if ((cookies != null) && !cookies.isEmpty()) { Cookie cookie; for (int i = 0; i < cookies.size(); i++) { cookie = cookies.get(i); if (i == 0) { if (cookie.getVersion() > 0) { append("$Version=\"").append(cookie.getVersion()) .append("\"; "); } } else { append("; "); } append(cookie); } } return this; } /** * Appends a source string as an HTTP comment. * * @param value * The source string to format. * @param version * The cookie version. * @return This writer. */ public CookieWriter appendValue(String value, int version) { if (version == 0) { append(value.toString()); } else { appendQuotedString(value); } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/WarningWriter.java0000664000175000017500000000536111757206346030405 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.Warning; import org.restlet.engine.util.DateUtils; /** * Warning header writer. * * @author Thierry Boileau */ public class WarningWriter extends HeaderWriter { /** * Writes a warning. * * @param warnings * The list of warnings to format. * @return The formatted warning. */ public static String write(List warnings) { return new WarningWriter().append(warnings).toString(); } @Override public WarningWriter append(Warning warning) { String agent = warning.getAgent(); String text = warning.getText(); if (warning.getStatus() == null) { throw new IllegalArgumentException( "Can't write warning. Invalid status code detected"); } if ((agent == null) || (agent.length() == 0)) { throw new IllegalArgumentException( "Can't write warning. Invalid agent detected"); } if ((text == null) || (text.length() == 0)) { throw new IllegalArgumentException( "Can't write warning. Invalid text detected"); } append(Integer.toString(warning.getStatus().getCode())); append(" "); append(agent); append(" "); appendQuotedString(text); if (warning.getDate() != null) { appendQuotedString(DateUtils.format(warning.getDate())); } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/HeaderConstants.java0000664000175000017500000001537611757206346030677 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; /** * Constants related to the HTTP protocol. * * @author Jerome Louvel */ public final class HeaderConstants { // -------------------- // --- Expectations --- // -------------------- public static final String EXPECT_CONTINUE = "100-continue"; // ------------------------ // --- Cache directives --- // ------------------------ public static final String CACHE_NO_CACHE = "no-cache"; public static final String CACHE_NO_STORE = "no-store"; public static final String CACHE_MAX_AGE = "max-age"; public static final String CACHE_MAX_STALE = "max-stale"; public static final String CACHE_MIN_FRESH = "min-fresh"; public static final String CACHE_NO_TRANSFORM = "no-transform"; public static final String CACHE_ONLY_IF_CACHED = "only-if-cached"; public static final String CACHE_PUBLIC = "public"; public static final String CACHE_PRIVATE = "private"; public static final String CACHE_MUST_REVALIDATE = "must-revalidate"; public static final String CACHE_PROXY_MUST_REVALIDATE = "proxy-revalidate"; public static final String CACHE_SHARED_MAX_AGE = "s-maxage"; // --------------------- // --- Header names --- // --------------------- public static final String HEADER_ACCEPT = "Accept"; public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language"; public static final String HEADER_ACCEPT_RANGES = "Accept-Ranges"; public static final String HEADER_AGE = "Age"; public static final String HEADER_ALLOW = "Allow"; public static final String HEADER_AUTHENTICATION_INFO = "Authentication-Info"; public static final String HEADER_AUTHORIZATION = "Authorization"; public static final String HEADER_CACHE_CONTROL = "Cache-Control"; public static final String HEADER_CONNECTION = "Connection"; public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; public static final String HEADER_CONTENT_LANGUAGE = "Content-Language"; public static final String HEADER_CONTENT_LENGTH = "Content-Length"; public static final String HEADER_CONTENT_LOCATION = "Content-Location"; public static final String HEADER_CONTENT_MD5 = "Content-MD5"; public static final String HEADER_CONTENT_RANGE = "Content-Range"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_COOKIE = "Cookie"; public static final String HEADER_DATE = "Date"; public static final String HEADER_ETAG = "ETag"; public static final String HEADER_EXPECT = "Expect"; public static final String HEADER_EXPIRES = "Expires"; public static final String HEADER_FROM = "From"; public static final String HEADER_HOST = "Host"; public static final String HEADER_IF_MATCH = "If-Match"; public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since"; public static final String HEADER_IF_NONE_MATCH = "If-None-Match"; public static final String HEADER_IF_RANGE = "If-Range"; public static final String HEADER_IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; public static final String HEADER_LAST_MODIFIED = "Last-Modified"; public static final String HEADER_LOCATION = "Location"; public static final String HEADER_MAX_FORWARDS = "Max-Forwards"; public static final String HEADER_PRAGMA = "Pragma"; public static final String HEADER_PROXY_AUTHENTICATE = "Proxy-Authenticate"; public static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization"; public static final String HEADER_RANGE = "Range"; public static final String HEADER_REFERRER = "Referer"; public static final String HEADER_RETRY_AFTER = "Retry-After"; public static final String HEADER_SERVER = "Server"; public static final String HEADER_SET_COOKIE = "Set-Cookie"; public static final String HEADER_SET_COOKIE2 = "Set-Cookie2"; public static final String HEADER_SLUG = "Slug"; public static final String HEADER_TRAILER = "Trailer"; public static final String HEADER_TRANSFER_ENCODING = "Transfer-Encoding"; public static final String HEADER_TRANSFER_EXTENSION = "TE"; public static final String HEADER_UPGRADE = "Upgrade"; public static final String HEADER_USER_AGENT = "User-Agent"; public static final String HEADER_VARY = "Vary"; public static final String HEADER_VIA = "Via"; public static final String HEADER_WARNING = "Warning"; public static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate"; public static final String HEADER_X_FORWARDED_FOR = "X-Forwarded-For"; public static final String HEADER_X_HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override"; // ------------------------- // --- Attribute names --- // ------------------------- public static final String ATTRIBUTE_HEADERS = "org.restlet.http.headers"; @Deprecated public static final String ATTRIBUTE_VERSION = "org.restlet.http.version"; public static final String ATTRIBUTE_HTTPS_CLIENT_CERTIFICATES = "org.restlet.https.clientCertificates"; public static final String ATTRIBUTE_HTTPS_CIPHER_SUITE = "org.restlet.https.cipherSuite"; public static final String ATTRIBUTE_HTTPS_KEY_SIZE = "org.restlet.https.keySize"; public static final String ATTRIBUTE_HTTPS_SSL_SESSION_ID = "org.restlet.https.sslSessionId"; } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ContentType.java0000664000175000017500000000712111757206346030053 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; /** * Association of a media type and a character set. * * @author Jerome Louvel */ public class ContentType { /** * Parses the given content type header and returns the media type. * * @param contentType * The content type header to parse. * @return The media type. */ public static MediaType readMediaType(String contentType) { return new ContentType(contentType).getMediaType(); } /** * Parses the given content type header and returns the character set. * * @param contentType * The content type header to parse. * @return The character set. */ public static CharacterSet readCharacterSet(String contentType) { return new ContentType(contentType).getCharacterSet(); } /** * The content character set. */ private volatile CharacterSet characterSet; /** * The content media type. */ private volatile MediaType mediaType; /** * Constructor. * * @param mediaType * The media type. * @param characterSet * The character set. */ public ContentType(MediaType mediaType, CharacterSet characterSet) { this.mediaType = mediaType; this.characterSet = characterSet; } /** * Constructor. * * @param headerValue * The "Content-type" header to parse. */ public ContentType(String headerValue) { try { ContentTypeReader ctr = new ContentTypeReader(headerValue); ContentType ct = ctr.readValue(); if (ct != null) { this.mediaType = ct.getMediaType(); this.characterSet = ct.getCharacterSet(); } } catch (IOException ioe) { throw new IllegalArgumentException( "The Content Type could not be read.", ioe); } } /** * Returns the character set. * * @return The character set. */ public CharacterSet getCharacterSet() { return this.characterSet; } /** * Returns the media type. * * @return The media type. */ public MediaType getMediaType() { return this.mediaType; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/DispositionWriter.java0000664000175000017500000000464111757206346031304 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import org.restlet.data.Disposition; import org.restlet.data.Parameter; /** * Disposition header writer. * * @author Thierry Boileau */ public class DispositionWriter extends HeaderWriter { /** * Formats a disposition. * * @param disposition * The disposition to format. * @return The formatted disposition. */ public static String write(Disposition disposition) { return new DispositionWriter().append(disposition).toString(); } @Override public DispositionWriter append(Disposition disposition) { if (Disposition.TYPE_NONE.equals(disposition.getType()) || disposition.getType() == null) { return this; } append(disposition.getType()); for (Parameter parameter : disposition.getParameters()) { append("; "); append(parameter.getName()); append("="); if (HeaderUtils.isToken(parameter.getValue())) { append(parameter.getValue()); } else { appendQuotedString(parameter.getValue()); } } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/DimensionReader.java0000664000175000017500000000635511757206346030657 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Collection; import org.restlet.data.Dimension; import org.restlet.data.Parameter; /** * Dimension header reader. * * @author Jerome Louvel */ public class DimensionReader extends HeaderReader { /** * Adds values to the given collection. * * @param header * The header to read. * @param collection * The collection to update. */ public static void addValues(Parameter header, Collection collection) { new DimensionReader(header.getValue()).addValues(collection); } /** * Constructor. * * @param header * The header to read. */ public DimensionReader(String header) { super(header); } @Override public Dimension readValue() throws IOException { Dimension result = null; String value = readRawValue(); if (value != null) { if (value.equalsIgnoreCase(HeaderConstants.HEADER_ACCEPT)) { result = Dimension.MEDIA_TYPE; } else if (value .equalsIgnoreCase(HeaderConstants.HEADER_ACCEPT_CHARSET)) { result = Dimension.CHARACTER_SET; } else if (value .equalsIgnoreCase(HeaderConstants.HEADER_ACCEPT_ENCODING)) { result = Dimension.ENCODING; } else if (value .equalsIgnoreCase(HeaderConstants.HEADER_ACCEPT_LANGUAGE)) { result = Dimension.LANGUAGE; } else if (value .equalsIgnoreCase(HeaderConstants.HEADER_AUTHORIZATION)) { result = Dimension.AUTHORIZATION; } else if (value .equalsIgnoreCase(HeaderConstants.HEADER_USER_AGENT)) { result = Dimension.CLIENT_AGENT; } else if (value.equals("*")) { result = Dimension.UNSPECIFIED; } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ExpectationWriter.java0000664000175000017500000000451611757206346031264 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.Expectation; import org.restlet.data.Parameter; /** * Expectation header writer. * * @author Jerome Louvel */ public class ExpectationWriter extends HeaderWriter { /** * Writes a list of expectations with a comma separator. * * @param expectations * The list of expectations. * @return The formatted list of expectations. */ public static String write(List expectations) { return new ExpectationWriter().append(expectations).toString(); } @Override public ExpectationWriter append(Expectation expectation) { if ((expectation.getName() != null) && (expectation.getName().length() > 0)) { appendExtension(expectation); if (!expectation.getParameters().isEmpty()) { for (Parameter param : expectation.getParameters()) { appendParameterSeparator(); appendExtension(param); } } } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/LanguageWriter.java0000664000175000017500000000333511757206346030522 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.List; import org.restlet.data.Language; /** * Language header writer. * * @author Jerome Louvel */ public class LanguageWriter extends MetadataWriter { /** * Writes a list of languages. * * @param languages * The languages to write. * @return This writer. */ public static String write(List languages) { return new LanguageWriter().append(languages).toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/DispositionReader.java0000664000175000017500000000454711757206346031237 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import org.restlet.data.Disposition; import org.restlet.data.Parameter; /** * Disposition header reader. * * @author Thierry Boileau */ public class DispositionReader extends HeaderReader { /** * Constructor. * * @param header * The header to read. */ public DispositionReader(String header) { super(header); } @Override public Disposition readValue() throws IOException { Disposition result = null; String type = readToken(); if (type.length() > 0) { result = new Disposition(); result.setType(type); if (skipParameterSeparator()) { Parameter param = readParameter(); while (param != null) { result.getParameters().add(param); if (skipParameterSeparator()) { param = readParameter(); } else { param = null; } } } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/MethodReader.java0000664000175000017500000000417711757206346030152 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Collection; import org.restlet.data.Method; import org.restlet.data.Parameter; /** * Method header reader. * * @author Jerome Louvel */ public class MethodReader extends HeaderReader { /** * Adds values to the given collection. * * @param header * The header to read. * @param collection * The collection to update. */ public static void addValues(Parameter header, Collection collection) { new MethodReader(header.getValue()).addValues(collection); } /** * Constructor. * * @param header * The header to read. */ public MethodReader(String header) { super(header); } @Override public Method readValue() throws IOException { return Method.valueOf(readToken()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/CookieReader.java0000664000175000017500000001655111757206346030142 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import org.restlet.data.Cookie; import org.restlet.data.Parameter; /** * Cookie header reader. * * @author Jerome Louvel */ public class CookieReader extends HeaderReader { private static final String NAME_DOMAIN = "$Domain"; private static final String NAME_PATH = "$Path"; private static final String NAME_VERSION = "$Version"; /** * Parses the given String to a Cookie * * @param cookie * @return the Cookie parsed from the String * @throws IllegalArgumentException * Thrown if the String can not be parsed as Cookie. */ public static Cookie read(String cookie) throws IllegalArgumentException { CookieReader cr = new CookieReader(cookie); try { return cr.readValue(); } catch (IOException e) { throw new IllegalArgumentException("Could not read the cookie", e); } } /** The global cookie specification version. */ private volatile int globalVersion; /** * Constructor. * * @param header * The header to read. */ public CookieReader(String header) { super(header); this.globalVersion = -1; } /** * Reads the next pair as a parameter. * * @param readAttribute * True, if the intention is to read only cookie attribute. * @return The next pair as a parameter. * @throws IOException */ private Parameter readPair(boolean readAttribute) throws IOException { Parameter result = null; boolean readingName = true; boolean readingValue = false; StringBuilder nameBuffer = new StringBuilder(); StringBuilder valueBuffer = new StringBuilder(); int nextChar = 0; while ((result == null) && (nextChar != -1)) { nextChar = read(); if (readingName) { if ((HeaderUtils.isSpace(nextChar)) && (nameBuffer.length() == 0)) { // Skip spaces } else if ((nextChar == -1) || (nextChar == ';') || (nextChar == ',')) { if (nameBuffer.length() > 0) { // End of pair with no value result = Parameter.create(nameBuffer, null); } else if (nextChar == -1) { // Do nothing return null preference } else { throw new IOException( "Empty cookie name detected. Please check your cookies"); } } else if (nextChar == '=') { readingName = false; readingValue = true; } else if (HeaderUtils.isTokenChar(nextChar) || (this.globalVersion < 1)) { if (readAttribute && nextChar != '$' && (nameBuffer.length() == 0)) { unread(); nextChar = -1; } else { nameBuffer.append((char) nextChar); } } else { throw new IOException( "Separator and control characters are not allowed within a token. Please check your cookie header"); } } else if (readingValue) { if ((HeaderUtils.isSpace(nextChar)) && (valueBuffer.length() == 0)) { // Skip spaces } else if ((nextChar == -1) || (nextChar == ';')) { // End of pair result = Parameter.create(nameBuffer, valueBuffer); } else if ((nextChar == '"') && (valueBuffer.length() == 0)) { // Step back unread(); valueBuffer.append(readQuotedString()); } else if (HeaderUtils.isTokenChar(nextChar) || (this.globalVersion < 1)) { valueBuffer.append((char) nextChar); } else { throw new IOException( "Separator and control characters are not allowed within a token. Please check your cookie header"); } } } return result; } @Override public Cookie readValue() throws IOException { Cookie result = null; Parameter pair = readPair(false); if (this.globalVersion == -1) { // Cookies version not yet detected if (pair.getName().equalsIgnoreCase(NAME_VERSION)) { if (pair.getValue() != null) { this.globalVersion = Integer.parseInt(pair.getValue()); } else { throw new IOException( "Empty cookies version attribute detected. Please check your cookie header"); } } else { // Set the default version for old Netscape cookies this.globalVersion = 0; } } while ((pair != null) && (pair.getName().charAt(0) == '$')) { // Unexpected special attribute // Silently ignore it as it may have been introduced by new // specifications pair = readPair(false); } if (pair != null) { // Set the cookie name and value result = new Cookie(this.globalVersion, pair.getName(), pair .getValue()); pair = readPair(true); } while ((pair != null) && (pair.getName().charAt(0) == '$')) { if (pair.getName().equalsIgnoreCase(NAME_PATH)) { result.setPath(pair.getValue()); } else if (pair.getName().equalsIgnoreCase(NAME_DOMAIN)) { result.setDomain(pair.getValue()); } else { // Unexpected special attribute // Silently ignore it as it may have been introduced by new // specifications } pair = readPair(true); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/CookieSettingReader.java0000664000175000017500000002411611757206346031474 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Date; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CookieSetting; import org.restlet.data.Parameter; import org.restlet.engine.util.DateUtils; /** * Cookie setting header reader. * * @author Jerome Louvel */ public class CookieSettingReader extends HeaderReader { private static final String NAME_SET_ACCESS_RESTRICTED = "httpOnly"; private static final String NAME_SET_COMMENT = "comment"; private static final String NAME_SET_COMMENT_URL = "commentURL"; private static final String NAME_SET_DISCARD = "discard"; private static final String NAME_SET_DOMAIN = "domain"; private static final String NAME_SET_EXPIRES = "expires"; private static final String NAME_SET_MAX_AGE = "max-age"; private static final String NAME_SET_PATH = "path"; private static final String NAME_SET_PORT = "port"; private static final String NAME_SET_SECURE = "secure"; private static final String NAME_SET_VERSION = "version"; /** * Parses the given String to a CookieSetting * * @param cookieSetting * @return the CookieSetting parsed from the String * @throws IllegalArgumentException * Thrown if the String can not be parsed as CookieSetting. */ public static CookieSetting read(String cookieSetting) throws IllegalArgumentException { CookieSettingReader cr = new CookieSettingReader(cookieSetting); try { return cr.readValue(); } catch (IOException e) { throw new IllegalArgumentException( "Could not read the cookie setting", e); } } /** The cached pair. Used by the readPair() method. */ private volatile Parameter cachedPair; /** The global cookie specification version. */ private volatile int globalVersion; /** * Constructor. * * @param header * The header to read. */ public CookieSettingReader(String header) { super(header); this.cachedPair = null; this.globalVersion = -1; } /** * Reads the next pair as a parameter. * * @return The next pair as a parameter. * @throws IOException */ private Parameter readPair() throws IOException { Parameter result = null; if (this.cachedPair != null) { result = this.cachedPair; this.cachedPair = null; } else { boolean readingName = true; boolean readingValue = false; StringBuilder nameBuffer = new StringBuilder(); StringBuilder valueBuffer = new StringBuilder(); int nextChar = 0; while ((result == null) && (nextChar != -1)) { nextChar = read(); if (readingName) { if ((HeaderUtils.isSpace(nextChar)) && (nameBuffer.length() == 0)) { // Skip spaces } else if ((nextChar == -1) || (nextChar == ';') || (nextChar == ',')) { if (nameBuffer.length() > 0) { // End of pair with no value result = Parameter.create(nameBuffer, null); } else if (nextChar == -1) { // Do nothing return null preference } else { throw new IOException( "Empty cookie name detected. Please check your cookies"); } } else if (nextChar == '=') { readingName = false; readingValue = true; } else if (HeaderUtils.isTokenChar(nextChar) || (this.globalVersion < 1)) { nameBuffer.append((char) nextChar); } else { throw new IOException( "Separator and control characters are not allowed within a token. Please check your cookie header"); } } else if (readingValue) { if ((HeaderUtils.isSpace(nextChar)) && (valueBuffer.length() == 0)) { // Skip spaces } else if ((nextChar == -1) || (nextChar == ';')) { // End of pair result = Parameter.create(nameBuffer, valueBuffer); } else if ((nextChar == '"') && (valueBuffer.length() == 0)) { // Step back unread(); valueBuffer.append(readQuotedString()); } else if (HeaderUtils.isTokenChar(nextChar) || (this.globalVersion < 1)) { valueBuffer.append((char) nextChar); } else { throw new IOException( "Separator and control characters are not allowed within a token. Please check your cookie header"); } } } } return result; } @Override public CookieSetting readValue() throws IOException { CookieSetting result = null; Parameter pair = readPair(); while ((pair != null) && (pair.getName().charAt(0) == '$')) { // Unexpected special attribute // Silently ignore it as it may have been introduced by new // specifications pair = readPair(); } if (pair != null) { // Set the cookie name and value result = new CookieSetting(pair.getName(), pair.getValue()); pair = readPair(); } while (pair != null) { if (pair.getName().equalsIgnoreCase(NAME_SET_PATH)) { result.setPath(pair.getValue()); } else if (pair.getName().equalsIgnoreCase(NAME_SET_DOMAIN)) { result.setDomain(pair.getValue()); } else if (pair.getName().equalsIgnoreCase(NAME_SET_COMMENT)) { result.setComment(pair.getValue()); } else if (pair.getName().equalsIgnoreCase(NAME_SET_COMMENT_URL)) { // No yet supported } else if (pair.getName().equalsIgnoreCase(NAME_SET_DISCARD)) { result.setMaxAge(-1); } else if (pair.getName().equalsIgnoreCase(NAME_SET_EXPIRES)) { final Date current = new Date(System.currentTimeMillis()); Date expires = DateUtils.parse(pair.getValue(), DateUtils.FORMAT_RFC_1036); if (expires == null) { expires = DateUtils.parse(pair.getValue(), DateUtils.FORMAT_RFC_1123); } if (expires == null) { expires = DateUtils.parse(pair.getValue(), DateUtils.FORMAT_ASC_TIME); } if (expires != null) { if (DateUtils.after(current, expires)) { result.setMaxAge((int) ((expires.getTime() - current .getTime()) / 1000)); } else { result.setMaxAge(0); } } else { // Ignore the expires header Context.getCurrentLogger().log( Level.WARNING, "Ignoring cookie setting expiration date. Unable to parse the date: " + pair.getValue()); } } else if (pair.getName().equalsIgnoreCase(NAME_SET_MAX_AGE)) { result.setMaxAge(Integer.valueOf(pair.getValue())); } else if (pair.getName().equalsIgnoreCase(NAME_SET_PORT)) { // No yet supported } else if (pair.getName().equalsIgnoreCase(NAME_SET_SECURE)) { if ((pair.getValue() == null) || (pair.getValue().length() == 0)) { result.setSecure(true); } } else if (pair.getName().equalsIgnoreCase( NAME_SET_ACCESS_RESTRICTED)) { if ((pair.getValue() == null) || (pair.getValue().length() == 0)) { result.setAccessRestricted(true); } } else if (pair.getName().equalsIgnoreCase(NAME_SET_VERSION)) { result.setVersion(Integer.valueOf(pair.getValue())); } else { // Unexpected special attribute // Silently ignore it as it may have been introduced by new // specifications } pair = readPair(); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/DateWriter.java0000664000175000017500000000411211757206346027646 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.Date; import org.restlet.engine.util.DateUtils; /** * Date header writer. * * @author Jerome Louvel */ public class DateWriter { /** * Writes a date header. * * @param date * The date to write. * @return The formatted date. */ public static String write(Date date) { return write(date, false); } /** * Writes a date header. * * @param date * The date to write. * @param cookie * Indicates if the date should be in the cookie format. * @return The formatted date. */ public static String write(Date date, boolean cookie) { if (cookie) { return DateUtils.format(date, DateUtils.FORMAT_RFC_1036.get(0)); } return DateUtils.format(date); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/WarningReader.java0000664000175000017500000000563611757206346030340 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import java.util.Collection; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.data.Warning; import org.restlet.engine.util.DateUtils; /** * Warning header reader. * * @author Thierry Boileau */ public class WarningReader extends HeaderReader { /** * Adds values to the given collection. * * @param header * The header to read. * @param collection * The collection to update. */ public static void addValues(Parameter header, Collection collection) { new WarningReader(header.getValue()).addValues(collection); } /** * Constructor. * * @param header * The header to read. */ public WarningReader(String header) { super(header); } @Override public Warning readValue() throws IOException { Warning result = new Warning(); String code = readToken(); skipSpaces(); String agent = readRawText(); skipSpaces(); String text = readQuotedString(); // The date is not mandatory skipSpaces(); String date = null; if (peek() != -1) { date = readQuotedString(); } if ((code == null) || (agent == null) || (text == null)) { throw new IOException("Warning header malformed."); } result.setStatus(Status.valueOf(Integer.parseInt(code))); result.setAgent(agent); result.setText(text); if (date != null) { result.setDate(DateUtils.parse(date)); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/CookieSettingWriter.java0000664000175000017500000001273511757206346031552 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.util.Date; import java.util.List; import org.restlet.data.CookieSetting; import org.restlet.engine.util.DateUtils; /** * Cookie setting header writer. * * @author Jerome Louvel */ public class CookieSettingWriter extends HeaderWriter { /** * Writes a cookie setting. * * @param cookieSetting * The cookie setting to format. * @return The formatted cookie setting. */ public static String write(CookieSetting cookieSetting) { return new CookieSettingWriter().append(cookieSetting).toString(); } /** * Writes a list of cookie settings. * * @param cookieSettings * The cookie settings to write. * @return The formatted cookie setting. */ public static String write(List cookieSettings) { return new CookieSettingWriter().append(cookieSettings).toString(); } @Override public CookieSettingWriter append(CookieSetting cookieSetting) throws IllegalArgumentException { String name = cookieSetting.getName(); String value = cookieSetting.getValue(); int version = cookieSetting.getVersion(); if ((name == null) || (name.length() == 0)) { throw new IllegalArgumentException( "Can't write cookie. Invalid name detected"); } append(name).append('='); // Append the value if ((value != null) && (value.length() > 0)) { appendValue(value, version); } // Append the version if (version > 0) { append("; Version="); appendValue(Integer.toString(version), version); } // Append the path String path = cookieSetting.getPath(); if ((path != null) && (path.length() > 0)) { append("; Path="); if (version == 0) { append(path); } else { appendQuotedString(path); } } // Append the expiration date int maxAge = cookieSetting.getMaxAge(); if (maxAge >= 0) { if (version == 0) { long currentTime = System.currentTimeMillis(); long maxTime = (maxAge * 1000L); long expiresTime = currentTime + maxTime; Date expires = new Date(expiresTime); append("; Expires="); appendValue(DateUtils.format(expires, DateUtils.FORMAT_RFC_1036 .get(0)), version); } else { append("; Max-Age="); appendValue(Integer.toString(cookieSetting.getMaxAge()), version); } } else if ((maxAge == -1) && (version > 0)) { // Discard the cookie at the end of the user's session (RFC // 2965) append("; Discard"); } else { // NetScape cookies automatically expire at the end of the // user's session } // Append the domain String domain = cookieSetting.getDomain(); if ((domain != null) && (domain.length() > 0)) { append("; Domain="); appendValue(domain.toLowerCase(), version); } // Append the secure flag if (cookieSetting.isSecure()) { append("; Secure"); } // Append the secure flag if (cookieSetting.isAccessRestricted()) { append("; HttpOnly"); } // Append the comment if (version > 0) { String comment = cookieSetting.getComment(); if ((comment != null) && (comment.length() > 0)) { append("; Comment="); appendValue(comment, version); } } return this; } /** * Appends a source string as an HTTP comment. * * @param value * The source string to format. * @param version * The cookie version. * @return This writer. */ public CookieSettingWriter appendValue(String value, int version) { if (version == 0) { append(value.toString()); } else { appendQuotedString(value); } return this; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ChallengeWriter.java0000664000175000017500000001221411757206346030655 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import org.restlet.data.ChallengeRequest; import org.restlet.data.Parameter; /** * Authentication challenge header writer. * * @author Jerome Louvel */ public class ChallengeWriter extends HeaderWriter { /** Indicates if the first challenge parameter is written. */ private volatile boolean firstChallengeParameter; /** * Constructor. */ public ChallengeWriter() { this.firstChallengeParameter = true; } @Override public HeaderWriter append(ChallengeRequest value) { return this; } /** * Appends a new challenge parameter, prefixed with a comma. The value is * separated from the name by an '=' character. * * @param parameter * The parameter. * @return This writer. */ public ChallengeWriter appendChallengeParameter(Parameter parameter) { return appendChallengeParameter(parameter.getName(), parameter .getValue()); } /** * Appends a new parameter, prefixed with a comma. * * @param name * The parameter name. * @return The current builder. */ public ChallengeWriter appendChallengeParameter(String name) { appendChallengeParameterSeparator(); appendToken(name); return this; } /** * Appends a new parameter, prefixed with a comma. The value is separated * from the name by an '=' character. * * @param name * The parameter name. * @param value * The parameter value. * @return This writer. */ public ChallengeWriter appendChallengeParameter(String name, String value) { appendChallengeParameterSeparator(); if (name != null) { appendToken(name); } if (value != null) { append('='); appendToken(value); } return this; } /** * Appends a comma as a separator if the first parameter has already been * written. * * @return This writer. */ public ChallengeWriter appendChallengeParameterSeparator() { if (isFirstChallengeParameter()) { setFirstChallengeParameter(false); } else { append(", "); } return this; } /** * Appends a new parameter, prefixed with a comma. The value is separated * from the name by an '=' character. * * @param parameter * The parameter. * @return This writer. */ public ChallengeWriter appendQuotedChallengeParameter(Parameter parameter) { return appendQuotedChallengeParameter(parameter.getName(), parameter .getValue()); } /** * Appends a new parameter, prefixed with a comma. The value is quoted and * separated from the name by an '=' character. * * @param name * The parameter name. * @param value * The parameter value to quote. * @return This writer. */ public ChallengeWriter appendQuotedChallengeParameter(String name, String value) { appendChallengeParameterSeparator(); if (name != null) { appendToken(name); } if (value != null) { append('='); appendQuotedString(value); } return this; } /** * Indicates if the first comma-separated value is written. * * @return True if the first comma-separated value is written. */ public boolean isFirstChallengeParameter() { return firstChallengeParameter; } /** * Indicates if the first comma-separated value is written. * * @param firstValue * True if the first comma-separated value is written. */ public void setFirstChallengeParameter(boolean firstValue) { this.firstChallengeParameter = firstValue; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/LanguageReader.java0000664000175000017500000000335611757206346030453 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import org.restlet.data.Language; /** * Language header reader. * * @author Jerome Louvel */ public class LanguageReader extends HeaderReader { /** * Constructor. * * @param header * The header to read. */ public LanguageReader(String header) { super(header); } @Override public Language readValue() throws IOException { return Language.valueOf(readRawValue()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/header/ParameterReader.java0000664000175000017500000000334311757206346030644 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.header; import java.io.IOException; import org.restlet.data.Parameter; /** * Parameter header reader. * * @author Jerome Louvel */ public class ParameterReader extends HeaderReader { /** * Constructor. * * @param header * The header to read. */ public ParameterReader(String header) { super(header); } @Override public Parameter readValue() throws IOException { return readParameter(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/security/0000775000175000017500000000000011757206350025345 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/http/security/package.html0000664000175000017500000000012211757206350027621 0ustar jamespagejamespage Supports HTTP security.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/http/security/HttpBasicHelper.java0000664000175000017500000001452311757206346031243 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http.security; import java.io.CharArrayWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Parameter; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.security.AuthenticatorHelper; import org.restlet.engine.util.Base64; import org.restlet.util.Series; /** * Implements the HTTP BASIC authentication. * * @author Jerome Louvel */ public class HttpBasicHelper extends AuthenticatorHelper { /** * Constructor. */ public HttpBasicHelper() { super(ChallengeScheme.HTTP_BASIC, true, true); } @Override public void formatRawRequest(ChallengeWriter cw, ChallengeRequest challenge, Response response, Series httpHeaders) throws IOException { if (challenge.getRealm() != null) { cw.appendQuotedChallengeParameter("realm", challenge.getRealm()); } } @Override public void formatRawResponse(ChallengeWriter cw, ChallengeResponse challenge, Request request, Series httpHeaders) { try { if (challenge == null) { throw new RuntimeException( "No challenge provided, unable to encode credentials"); } else { CharArrayWriter credentials = new CharArrayWriter(); credentials.write(challenge.getIdentifier()); credentials.write(":"); credentials.write(challenge.getSecret()); cw.append(Base64.encode(credentials.toCharArray(), "ISO-8859-1", false)); } } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Unsupported encoding, unable to encode credentials"); } catch (IOException e) { throw new RuntimeException( "Unexpected exception, unable to encode credentials", e); } } @Override public void parseRequest(ChallengeRequest challenge, Response response, Series httpHeaders) { if (challenge.getRawValue() != null) { HeaderReader hr = new HeaderReader( challenge.getRawValue()); try { Parameter param = hr.readParameter(); while (param != null) { try { if ("realm".equals(param.getName())) { challenge.setRealm(param.getValue()); } else { challenge.getParameters().add(param); } if (hr.skipValueSeparator()) { param = hr.readParameter(); } else { param = null; } } catch (Exception e) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to parse the challenge request header parameter", e); } } } catch (Exception e) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to parse the challenge request header parameter", e); } } } @Override public void parseResponse(ChallengeResponse challenge, Request request, Series httpHeaders) { try { byte[] credentialsEncoded = Base64.decode(challenge.getRawValue()); if (credentialsEncoded == null) { getLogger() .info("Cannot decode credentials: " + challenge.getRawValue()); } String credentials = new String(credentialsEncoded, "ISO-8859-1"); int separator = credentials.indexOf(':'); if (separator == -1) { // Log the blocking getLogger().info( "Invalid credentials given by client with IP: " + ((request != null) ? request.getClientInfo() .getAddress() : "?")); } else { challenge.setIdentifier(credentials.substring(0, separator)); challenge.setSecret(credentials.substring(separator + 1)); } } catch (UnsupportedEncodingException e) { getLogger().log(Level.INFO, "Unsupported HTTP Basic encoding error", e); } catch (IllegalArgumentException e) { getLogger().log(Level.INFO, "Unable to decode the HTTP Basic credential", e); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/http/ServerCall.java0000664000175000017500000005053311757206346026416 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.http; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.security.cert.Certificate; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Response; import org.restlet.Server; import org.restlet.data.Digest; import org.restlet.data.Parameter; import org.restlet.engine.ConnectorHelper; import org.restlet.engine.http.header.ContentType; import org.restlet.engine.http.header.DispositionReader; import org.restlet.engine.http.header.EncodingReader; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.HeaderReader; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.http.header.LanguageReader; import org.restlet.engine.http.header.RangeReader; import org.restlet.engine.io.BioUtils; import org.restlet.engine.security.SslUtils; import org.restlet.engine.util.Base64; import org.restlet.engine.util.StringUtils; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.ReadableRepresentation; import org.restlet.representation.Representation; import org.restlet.service.ConnectorService; /** * Abstract HTTP server connector call. * * @author Jerome Louvel */ public abstract class ServerCall extends Call { /** Indicates if the "host" header was already parsed. */ private volatile boolean hostParsed; /** * Constructor. * * @param server * The parent server connector. */ public ServerCall(Server server) { this(server.getAddress(), server.getPort()); } /** * Constructor. * * @param serverAddress * The server IP address. * @param serverPort * The server port. */ public ServerCall(String serverAddress, int serverPort) { setServerAddress(serverAddress); setServerPort(serverPort); this.hostParsed = false; } /** * Ask the connector to abort the related network connection, for example * immediately closing the socket. * * @return True if the request was aborted. */ public abstract boolean abort(); /** * Complete the response */ public void complete() { } /** * Returns the content length of the request entity if know, * {@link Representation#UNKNOWN_SIZE} otherwise. * * @return The request content length. */ protected long getContentLength() { return HeaderUtils.getContentLength(getRequestHeaders()); } /** * Returns the host domain name. * * @return The host domain name. */ @Override public String getHostDomain() { if (!this.hostParsed) { parseHost(); } return super.getHostDomain(); } /** * Returns the host port. * * @return The host port. */ @Override public int getHostPort() { if (!this.hostParsed) { parseHost(); } return super.getHostPort(); } /** * Returns the request entity if available. * * @return The request entity if available. */ public Representation getRequestEntity() { Representation result = null; long contentLength = getContentLength(); boolean chunkedEncoding = HeaderUtils .isChunkedEncoding(getRequestHeaders()); // In some cases there is an entity without a content-length header boolean connectionClosed = HeaderUtils .isConnectionClose(getRequestHeaders()); // Create the representation if ((contentLength != Representation.UNKNOWN_SIZE && contentLength != 0) || chunkedEncoding || connectionClosed) { // Create the result representation InputStream requestStream = getRequestEntityStream(contentLength); ReadableByteChannel requestChannel = getRequestEntityChannel(contentLength); if ((requestStream != null) && connectionClosed) { // We need to detect if there is really an entity or not as only // the end of connection can let us know at this point PushbackInputStream pbi = new PushbackInputStream(requestStream); try { int next = pbi.read(); if (next != -1) { pbi.unread(next); requestStream = pbi; } else { requestStream = null; } } catch (IOException e) { getLogger().fine("Unable to read request entity"); } } if (requestStream != null) { result = new InputRepresentation(requestStream, null, contentLength); } else if (requestChannel != null) { result = new ReadableRepresentation(requestChannel, null, contentLength); } else { result = new EmptyRepresentation(); } result.setSize(contentLength); } else { result = new EmptyRepresentation(); } // Extract some interesting header values for (Parameter header : getRequestHeaders()) { if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_ENCODING)) { new EncodingReader(header.getValue()).addValues(result .getEncodings()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_LANGUAGE)) { new LanguageReader(header.getValue()).addValues(result .getLanguages()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_TYPE)) { ContentType contentType = new ContentType(header.getValue()); result.setMediaType(contentType.getMediaType()); result.setCharacterSet(contentType.getCharacterSet()); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_RANGE)) { RangeReader.update(header.getValue(), result); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_MD5)) { result.setDigest(new Digest(Digest.ALGORITHM_MD5, Base64 .decode(header.getValue()))); } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_DISPOSITION)) { try { result.setDisposition(new DispositionReader(header .getValue()).readValue()); } catch (IOException ioe) { Context.getCurrentLogger().log( Level.WARNING, "Error during Content-Disposition header parsing. Header: " + header.getValue(), ioe); } } } return result; } /** * Returns the request entity channel if it exists. * * @param size * The expected entity size or -1 if unknown. * * @return The request entity channel if it exists. */ public abstract ReadableByteChannel getRequestEntityChannel(long size); /** * Returns the request entity stream if it exists. * * @param size * The expected entity size or -1 if unknown. * * @return The request entity stream if it exists. */ public abstract InputStream getRequestEntityStream(long size); /** * Returns the request head channel if it exists. * * @return The request head channel if it exists. */ public abstract ReadableByteChannel getRequestHeadChannel(); /** * Returns the request head stream if it exists. * * @return The request head stream if it exists. */ public abstract InputStream getRequestHeadStream(); /** * Returns the response channel if it exists. * * @return The response channel if it exists. */ public abstract WritableByteChannel getResponseEntityChannel(); /** * Returns the response entity stream if it exists. * * @return The response entity stream if it exists. */ public abstract OutputStream getResponseEntityStream(); /** * Returns the SSL Cipher Suite, if available and accessible. * * @return The SSL Cipher Suite, if available and accessible. */ public String getSslCipherSuite() { return null; } /** * Returns the chain of client certificates, if available and accessible. * * @return The chain of client certificates, if available and accessible. */ public List getSslClientCertificates() { return null; } /** * Returns the SSL key size, if available and accessible. * * @return The SSL key size, if available and accessible. */ public Integer getSslKeySize() { Integer keySize = null; String sslCipherSuite = getSslCipherSuite(); if (sslCipherSuite != null) { keySize = SslUtils.extractKeySize(sslCipherSuite); } return keySize; } /** * Returns the SSL session ID, in hexadecimal encoding, if available and * accessible. * * @return The SSL session ID, in hexadecimal encoding, if available and * accessible. */ public String getSslSessionId() { byte[] byteArray = getSslSessionIdBytes(); if (byteArray != null) { return BioUtils.toHexString(byteArray); } else { return null; } } /** * Returns the SSL session ID, as a byte array, if available and accessible * in that format (to be used by getSslSessionId). * * @return The SSL session ID, as a byte array, if available and accessible * in that format. */ protected byte[] getSslSessionIdBytes() { return null; } @Override protected boolean isClientKeepAlive() { return !HeaderUtils.isConnectionClose(getRequestHeaders()); } @Override protected boolean isServerKeepAlive() { return true; } /** * Parses the "host" header to set the server host and port properties. */ private void parseHost() { String host = getRequestHeaders().getFirstValue( HeaderConstants.HEADER_HOST, true); if (host != null) { int colonIndex = host.indexOf(':'); if (colonIndex != -1) { super.setHostDomain(host.substring(0, colonIndex)); super.setHostPort(Integer.valueOf(host .substring(colonIndex + 1))); } else { super.setHostDomain(host); super.setHostPort(getProtocol().getDefaultPort()); } } else { getLogger().info( "Couldn't find the mandatory \"Host\" HTTP header."); } this.hostParsed = true; } /** * Reads the HTTP request head (request line and headers). * * @throws IOException */ protected void readRequestHead(InputStream headStream) throws IOException { StringBuilder sb = new StringBuilder(); // Parse the request method int next = headStream.read(); while ((next != -1) && !HeaderUtils.isSpace(next)) { sb.append((char) next); next = headStream.read(); } if (next == -1) { throw new IOException( "Unable to parse the request method. End of stream reached too early."); } setMethod(sb.toString()); sb.delete(0, sb.length()); // Parse the request URI next = headStream.read(); while ((next != -1) && !HeaderUtils.isSpace(next)) { sb.append((char) next); next = headStream.read(); } if (next == -1) { throw new IOException( "Unable to parse the request URI. End of stream reached too early."); } setRequestUri(sb.toString()); sb.delete(0, sb.length()); // Parse the HTTP version next = headStream.read(); while ((next != -1) && !HeaderUtils.isCarriageReturn(next)) { sb.append((char) next); next = headStream.read(); } if (next == -1) { throw new IOException( "Unable to parse the HTTP version. End of stream reached too early."); } next = headStream.read(); if (HeaderUtils.isLineFeed(next)) { setVersion(sb.toString()); sb.delete(0, sb.length()); // Parse the headers Parameter header = HeaderReader.readHeader(headStream, sb); while (header != null) { getRequestHeaders().add(header); header = HeaderReader.readHeader(headStream, sb); } } else { throw new IOException( "Unable to parse the HTTP version. The carriage return must be followed by a line feed."); } } /** * Sends the response back to the client. Commits the status, headers and * optional entity and send them over the network. The default * implementation only writes the response entity on the response stream or * channel. Subclasses will probably also copy the response headers and * status. * * @param response * The high-level response. * @throws IOException * if the Response could not be written to the network. */ public void sendResponse(Response response) throws IOException { if (response != null) { // Get the connector service to callback Representation responseEntity = response.getEntity(); ConnectorService connectorService = ConnectorHelper .getConnectorService(); if (connectorService != null) { connectorService.beforeSend(responseEntity); } try { writeResponseHead(response); if (responseEntity != null) { WritableByteChannel responseEntityChannel = getResponseEntityChannel(); OutputStream responseEntityStream = getResponseEntityStream(); writeResponseBody(responseEntity, responseEntityChannel, responseEntityStream); if (responseEntityStream != null) { try { responseEntityStream.flush(); responseEntityStream.close(); } catch (IOException ioe) { // The stream was probably already closed by the // connector. Probably OK, low message priority. getLogger() .log(Level.FINE, "Exception while flushing and closing the entity stream.", ioe); } } } } finally { if (responseEntity != null) { responseEntity.release(); } if (connectorService != null) { connectorService.afterSend(responseEntity); } } } } /** * Indicates if the response should be chunked because its length is * unknown. * * @param response * The response to analyze. * @return True if the response should be chunked. */ public boolean shouldResponseBeChunked(Response response) { return (response.getEntity() != null) && (response.getEntity().getSize() == Representation.UNKNOWN_SIZE); } /** * Effectively writes the response body. The entity to write is guaranteed * to be non null. Attempts to write the entity on the response channel or * response stream by default. * * @param entity * The representation to write as entity of the body. * @param responseEntityChannel * The response entity channel or null if a stream is used. * @param responseEntityStream * The response entity stream or null if a channel is used. * @throws IOException */ protected void writeResponseBody(Representation entity, WritableByteChannel responseEntityChannel, OutputStream responseEntityStream) throws IOException { // Send the entity to the client if (responseEntityChannel != null) { entity.write(responseEntityChannel); } else if (responseEntityStream != null) { entity.write(responseEntityStream); responseEntityStream.flush(); } } /** * Writes the response status line and headers. Does nothing by default. * * @param response * The response. * @throws IOException */ protected void writeResponseHead(Response response) throws IOException { // Do nothing by default } /** * Writes the response head to the given output stream. * * @param response * The response. * @param headStream * The output stream to write to. * @throws IOException */ protected void writeResponseHead(Response response, OutputStream headStream) throws IOException { // Write the status line String version = (getVersion() == null) ? "1.1" : getVersion(); headStream.write(StringUtils.getAsciiBytes(version)); headStream.write(' '); headStream.write(StringUtils.getAsciiBytes(Integer .toString(getStatusCode()))); headStream.write(' '); if (getReasonPhrase() != null) { headStream.write(StringUtils.getLatin1Bytes(getReasonPhrase())); } else { headStream.write(StringUtils .getAsciiBytes(("Status " + getStatusCode()))); } headStream.write(13); // CR headStream.write(10); // LF // We don't support persistent connections yet getResponseHeaders().set(HeaderConstants.HEADER_CONNECTION, "close", true); // Check if 'Transfer-Encoding' header should be set if (shouldResponseBeChunked(response)) { getResponseHeaders().add(HeaderConstants.HEADER_TRANSFER_ENCODING, "chunked"); } // Write the response headers for (Parameter header : getResponseHeaders()) { HeaderUtils.writeHeaderLine(header, headStream); } // Write the end of the headers section headStream.write(13); // CR headStream.write(10); // LF headStream.flush(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/internal/0000775000175000017500000000000011757206346024340 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/internal/Activator.java0000664000175000017500000001333711757206346027146 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.internal; import java.net.URL; import java.util.List; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.restlet.Client; import org.restlet.Server; import org.restlet.engine.Engine; /** * OSGi activator. It registers the NRE into the Restlet API and also introspect * the bundles to find connector or authentication helpers. * * @author Jerome Louvel */ public class Activator implements BundleActivator { /** * Registers the helpers for a given bundle. * * @param bundle * The bundle to inspect. * @param helpers * The helpers list to update. * @param constructorClass * The class to use as constructor parameter. * @param descriptorPath * The descriptor file path. */ private void registerHelper(Bundle bundle, List helpers, Class constructorClass, String descriptorPath) { // Discover server helpers URL configUrl = bundle.getEntry(descriptorPath); if (configUrl == null) { configUrl = bundle.getEntry("/src/" + descriptorPath); } if (configUrl != null) { registerHelper(bundle, helpers, constructorClass, configUrl); } } /** * Registers the helpers for a given bundle. * * @param bundle * The bundle to inspect. * @param helpers * The helpers list to update. * @param constructorClass * The class to use as constructor parameter. * @param descriptorUrl * The descriptor URL to inspect. */ private void registerHelper(final Bundle bundle, List helpers, Class constructorClass, URL descriptorUrl) { Engine.getInstance().registerHelpers(new ClassLoader() { @Override public Class loadClass(String name) throws ClassNotFoundException { return bundle.loadClass(name); } }, descriptorUrl, helpers, constructorClass); } /** * Registers the helpers for a given bundle. * * @param bundle * The bundle to inspect. */ private void registerHelpers(Bundle bundle) { // Register server helpers registerHelper(bundle, Engine.getInstance().getRegisteredServers(), Server.class, Engine.DESCRIPTOR_SERVER_PATH); // Register client helpers registerHelper(bundle, Engine.getInstance().getRegisteredClients(), Client.class, Engine.DESCRIPTOR_CLIENT_PATH); // Register authentication helpers registerHelper(bundle, Engine.getInstance() .getRegisteredAuthenticators(), null, Engine.DESCRIPTOR_AUTHENTICATOR_PATH); // Register converter helpers registerHelper(bundle, Engine.getInstance().getRegisteredConverters(), null, Engine.DESCRIPTOR_CONVERTER_PATH); } /** * Starts the OSGi bundle by registering the engine with the bundle of the * Restlet API. * * @param context * The bundle context. */ public void start(BundleContext context) throws Exception { org.restlet.engine.Engine.setInstance(new Engine(false)); // Discover helpers in installed bundles and start // the bundle if necessary for (final Bundle bundle : context.getBundles()) { registerHelpers(bundle); } // Listen to installed bundles context.addBundleListener(new BundleListener() { public void bundleChanged(BundleEvent event) { switch (event.getType()) { case BundleEvent.INSTALLED: registerHelpers(event.getBundle()); break; case BundleEvent.UNINSTALLED: break; } } }); Engine.getInstance().registerDefaultConnectors(); Engine.getInstance().registerDefaultAuthentications(); Engine.getInstance().registerDefaultConverters(); } /** * Stops the OSGi bundle by unregistering the engine with the bundle of the * Restlet API. * * @param context * The bundle context. */ public void stop(BundleContext context) throws Exception { org.restlet.engine.Engine.setInstance(null); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/RestletHelper.java0000664000175000017500000001240611757206346026154 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.service.MetadataService; import org.restlet.util.Series; /** * Delegate used by API classes to get support from the implementation classes. * Note that this is an SPI class that is not intended for public usage. * * @author Jerome Louvel */ public abstract class RestletHelper extends Helper { /** * The map of attributes exchanged between the API and the Engine via this * helper. */ private final Map attributes; /** * The helped Restlet. */ private volatile T helped; /** * Constructor. * * @param helped * The helped Restlet. */ public RestletHelper(T helped) { this.attributes = new ConcurrentHashMap(); this.helped = helped; } /** * Returns the map of attributes exchanged between the API and the Engine * via this helper. * * @return The map of attributes. */ public Map getAttributes() { return this.attributes; } /** * Returns the helped Restlet context. * * @return The helped Restlet context. */ public Context getContext() { return getHelped().getContext(); } /** * Returns the helped Restlet. * * @return The helped Restlet. */ public T getHelped() { return this.helped; } /** * Returns the helped Restlet parameters. * * @return The helped Restlet parameters. */ public Series getHelpedParameters() { Series result = null; if ((getHelped() != null) && (getHelped().getContext() != null)) { result = getHelped().getContext().getParameters(); } else { result = new Form(); } return result; } /** * Returns the helped Restlet logger. * * @return The helped Restlet logger. */ public Logger getLogger() { if (getHelped() != null && getHelped().getContext() != null) { return getHelped().getContext().getLogger(); } return Context.getCurrentLogger(); } /** * Returns the metadata service. If the parent application doesn't exist, a * new instance is created. * * @return The metadata service. */ public MetadataService getMetadataService() { MetadataService result = null; if (getHelped() != null) { org.restlet.Application application = getHelped().getApplication(); if (application != null) { result = application.getMetadataService(); } } if (result == null) { result = new MetadataService(); } return result; } /** * Handles a call. * * @param request * The request to handle. * @param response * The response to update. */ public void handle(Request request, Response response) { // Associate the response to the current thread Response.setCurrent(response); // Associate the context to the current thread if (getContext() != null) { Context.setCurrent(getContext()); } } /** * Sets the helped Restlet. * * @param helpedRestlet * The helped Restlet. */ public void setHelped(T helpedRestlet) { this.helped = helpedRestlet; } /** Start callback. */ public abstract void start() throws Exception; /** Stop callback. */ public abstract void stop() throws Exception; /** * Update callback with less impact than a {@link #stop()} followed by a * {@link #start()}. */ public abstract void update() throws Exception; } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/0000775000175000017500000000000011757206350023300 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/log/AccessLogFormatter.java0000664000175000017500000000317111757206346027701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * Log record formatter which simply outputs the message on a new line. Useful * for Web-style logs. * * @author Jerome Louvel */ public class AccessLogFormatter extends Formatter { @Override public String format(LogRecord logRecord) { return logRecord.getMessage() + '\n'; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/TraceHandler.java0000664000175000017500000000456411757206346026515 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * Special handler that logs in the console all log message sent through the log * manager. For each log record, it displays the source logger name and the * actual message. * * This is particularly useful for debugging. * * @author Jerome Louvel */ public class TraceHandler extends Handler { /** * Registers the handler with the root logger. Removes any default handler * like the default console handler. */ public static void register() { Logger rootLogger = Logger.getLogger(""); for (Handler handler : rootLogger.getHandlers()) { rootLogger.removeHandler(handler); } rootLogger.addHandler(new TraceHandler()); } @Override public void close() throws SecurityException { } @Override public void flush() { } @Override public void publish(LogRecord record) { System.out.println("[" + record.getLevel().getLocalizedName() + "][" + record.getLoggerName() + "] " + record.getMessage()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/IdentClient.java0000664000175000017500000001234011757206346026352 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.Socket; import java.util.StringTokenizer; import java.util.logging.Level; import org.restlet.Context; import org.restlet.engine.io.IoUtils; import org.restlet.engine.util.StringUtils; /** * Simple IDENT client. Follow the RFC 1413. * * @author Jerome Louvel */ public class IdentClient { /** The timeout while attempting to connect to the Ident server. */ private static final int CONNECT_TIMEOUT = 100; /** The timeout while communicating with the Ident server. */ private static final int SO_TIMEOUT = 500; /** The remote host type. */ private volatile String hostType; /** The user identifier. */ private volatile String userIdentifier; /** * Constructor. * * @param clientAddress * The client IP address. * @param clientPort * The client port (remote). * @param serverPort * The server port (local). */ public IdentClient(String clientAddress, int clientPort, int serverPort) { Socket socket = null; if ((clientAddress != null) && (clientPort != -1) && (serverPort != -1)) { BufferedReader in = null; try { // Compose the IDENT request final StringBuilder sb = new StringBuilder(); sb.append(clientPort).append(" , ").append(serverPort).append( "\r\n"); final String request = sb.toString(); // Send the request to the remote server socket = new Socket(); socket.setSoTimeout(SO_TIMEOUT); socket.connect(new InetSocketAddress(clientAddress, 113), CONNECT_TIMEOUT); socket.getOutputStream().write( StringUtils.getAsciiBytes(request)); // Read the response in = new BufferedReader(new InputStreamReader(socket .getInputStream()), IoUtils.getBufferSize()); final String response = in.readLine(); // Parse the response if (response != null) { final StringTokenizer st = new StringTokenizer(response, ":"); if (st.countTokens() >= 3) { // Skip the first token st.nextToken(); // Get the command final String command = st.nextToken().trim(); if (command.equalsIgnoreCase("USERID") && (st.countTokens() >= 2)) { // Get the host type this.hostType = st.nextToken().trim(); // Get the remaining text as a user identifier this.userIdentifier = st.nextToken("").substring(1); } } } } catch (IOException ioe) { Context.getCurrentLogger().log(Level.FINE, "Unable to complete the IDENT request", ioe); } finally { try { // Always attempt to close the reader, therefore the socket if (in != null) { in.close(); } } catch (IOException ioe) { Context.getCurrentLogger().log(Level.FINE, "Unable to close the socket", ioe); } } } } /** * Returns the remote host type. * * @return The remote host type. */ public String getHostType() { return this.hostType; } /** * Returns the user identifier. * * @return The user identifier. */ public String getUserIdentifier() { return this.userIdentifier; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/LogFilter.java0000664000175000017500000002276211757206346026050 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.engine.component.ChildContext; import org.restlet.routing.Filter; import org.restlet.routing.Template; import org.restlet.service.LogService; /** * Filter logging all calls after their handling by the target Restlet. The * current format is similar to IIS 6 logs. The logging is based on the * java.util.logging package. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class LogFilter extends Filter { /** The log service. */ protected volatile LogService logService; /** The log template to use. */ protected volatile Template logTemplate; /** The log service logger. */ private volatile Logger logLogger; /** * Constructor. * * @param context * The context. * @param logService * The log service descriptor. */ public LogFilter(Context context, LogService logService) { super(context); this.logService = logService; if (logService != null) { this.logTemplate = (logService.getLogFormat() == null) ? null : new Template(logService.getLogFormat()); if (logService.getLoggerName() != null) { this.logLogger = Engine.getLogger(logService.getLoggerName()); } else if ((context != null) && (context.getLogger().getParent() != null)) { this.logLogger = Engine.getLogger(context.getLogger() .getParent().getName() + "." + ChildContext.getBestClassName(logService.getClass())); } else { this.logLogger = Engine.getLogger(ChildContext .getBestClassName(logService.getClass())); } } } /** * Allows filtering after processing by the next Restlet. Logs the call. * * @param request * The request to handle. * @param response * The response to update. */ @Override protected void afterHandle(Request request, Response response) { if (this.logLogger.isLoggable(Level.INFO)) { // Format the call into a log entry if (this.logTemplate != null) { this.logLogger.log(Level.INFO, format(request, response)); } else { long startTime = (Long) request.getAttributes().get( "org.restlet.startTime"); int duration = (int) (System.currentTimeMillis() - startTime); this.logLogger.log(Level.INFO, formatDefault(request, response, duration)); } } } /** * Allows filtering before processing by the next Restlet. Saves the start * time. * * @param request * The request to handle. * @param response * The response to update. * @return The continuation status. */ @Override protected int beforeHandle(Request request, Response response) { request.getAttributes().put("org.restlet.startTime", System.currentTimeMillis()); return CONTINUE; } /** * Format a log entry. * * @param request * The request to log. * @param response * The response to log. * @return The formatted log entry. */ protected String format(Request request, Response response) { return this.logTemplate.format(request, response); } /** * Format a log entry using the default format. * * @param request * The request to log. * @param response * The response to log. * @param duration * The call duration (in milliseconds). * @return The formatted log entry. */ protected String formatDefault(Request request, Response response, int duration) { StringBuilder sb = new StringBuilder(); long currentTime = System.currentTimeMillis(); // Append the date of the request sb.append(String.format("%tF", currentTime)); sb.append('\t'); // Append the time of the request sb.append(String.format("%tT", currentTime)); sb.append('\t'); // Append the client IP address String clientAddress = request.getClientInfo().getUpstreamAddress(); sb.append((clientAddress == null) ? "-" : clientAddress); sb.append('\t'); // Append the user name (via IDENT protocol) if (this.logService.isIdentityCheck()) { IdentClient ic = new IdentClient(request.getClientInfo() .getUpstreamAddress(), request.getClientInfo().getPort(), response.getServerInfo().getPort()); sb.append((ic.getUserIdentifier() == null) ? "-" : ic .getUserIdentifier()); } else if ((request.getChallengeResponse() != null) && (request.getChallengeResponse().getIdentifier() != null)) { sb.append(request.getChallengeResponse().getIdentifier()); } else { sb.append('-'); } sb.append('\t'); // Append the server IP address String serverAddress = response.getServerInfo().getAddress(); sb.append((serverAddress == null) ? "-" : serverAddress); sb.append('\t'); // Append the server port Integer serverport = response.getServerInfo().getPort(); sb.append((serverport == null) ? "-" : serverport.toString()); sb.append('\t'); // Append the method name String methodName = (request.getMethod() == null) ? "-" : request .getMethod().getName(); sb.append((methodName == null) ? "-" : methodName); // Append the resource path sb.append('\t'); String resourcePath = (request.getResourceRef() == null) ? "-" : request.getResourceRef().getPath(); sb.append((resourcePath == null) ? "-" : resourcePath); // Append the resource query sb.append('\t'); String resourceQuery = (request.getResourceRef() == null) ? "-" : request.getResourceRef().getQuery(); sb.append((resourceQuery == null) ? "-" : resourceQuery); // Append the status code sb.append('\t'); sb.append((response.getStatus() == null) ? "-" : Integer .toString(response.getStatus().getCode())); // Append the returned size sb.append('\t'); if (!response.isEntityAvailable() || Status.REDIRECTION_NOT_MODIFIED.equals(response.getStatus()) || Status.SUCCESS_NO_CONTENT.equals(response.getStatus()) || Method.HEAD.equals(request.getMethod())) { sb.append('0'); } else { sb.append((response.getEntity().getSize() == -1) ? "-" : Long .toString(response.getEntity().getSize())); } // Append the received size sb.append('\t'); if (request.getEntity() == null) { sb.append('0'); } else { sb.append((request.getEntity().getSize() == -1) ? "-" : Long .toString(request.getEntity().getSize())); } // Append the duration sb.append('\t'); sb.append(duration); // Append the host reference sb.append('\t'); sb.append((request.getHostRef() == null) ? "-" : request.getHostRef() .toString()); // Append the agent name sb.append('\t'); String agentName = request.getClientInfo().getAgent(); sb.append((agentName == null) ? "-" : agentName); // Append the referrer sb.append('\t'); sb.append((request.getReferrerRef() == null) ? "-" : request .getReferrerRef().getIdentifier()); return sb.toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/package.html0000664000175000017500000000012411757206350025556 0ustar jamespagejamespage Supports the log service.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/log/AccessLogFileHandler.java0000664000175000017500000000734011757206350030110 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.io.IOException; /** * Log file handler that uses the {@link AccessLogFormatter} by default. Also * useful in configuration files to differentiate from the * {@link java.util.logging.FileHandler}. * * @author Jerome Louvel */ public class AccessLogFileHandler extends java.util.logging.FileHandler { /** * Constructor. * * @throws IOException * @throws SecurityException */ public AccessLogFileHandler() throws IOException, SecurityException { super(); init(); } /** * Constructor. * * @param pattern * The name of the output file. * @throws IOException * @throws SecurityException */ public AccessLogFileHandler(String pattern) throws IOException, SecurityException { super(pattern); init(); } /** * Constructor. * * @param pattern * The name of the output file. * @param append * Specifies append mode. * @throws IOException * @throws SecurityException */ public AccessLogFileHandler(String pattern, boolean append) throws IOException, SecurityException { super(pattern, append); init(); } /** * Constructor. * * @param pattern * The name of the output file. * @param limit * The maximum number of bytes to write to any one file. * @param count * The number of files to use. * @throws IOException * @throws SecurityException */ public AccessLogFileHandler(String pattern, int limit, int count) throws IOException, SecurityException { super(pattern, limit, count); init(); } /** * Constructor. * * @param pattern * The name of the output file. * @param limit * The maximum number of bytes to write to any one file. * @param count * The number of files to use. * @param append * Specifies append mode. * @throws IOException * @throws SecurityException */ public AccessLogFileHandler(String pattern, int limit, int count, boolean append) throws IOException, SecurityException { super(pattern, limit, count, append); init(); } /** * Initialization code common to all constructors. */ protected void init() { setFormatter(new AccessLogFormatter()); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/LoggingThreadFactory.java0000664000175000017500000000570411757206346030224 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger; /** * Thread factory that logs uncaught exceptions thrown by the created threads. * * @author Jerome Louvel */ public class LoggingThreadFactory implements ThreadFactory { /** * Handle uncaught thread exceptions. */ private class LoggingExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable ex) { logger.log(Level.SEVERE, "Thread: " + t.getName() + " terminated with exception: " + ex.getMessage(), ex); } } /** The associated logger. */ private final Logger logger; /** Indicates if threads should be created as daemons. */ private final boolean daemon; /** * Constructor. * * @param logger * The associated logger. */ public LoggingThreadFactory(Logger logger) { this(logger, false); } /** * Constructor. * * @param logger * The associated logger. * @param daemon * Indicates if threads should be created as daemons. */ public LoggingThreadFactory(Logger logger, boolean daemon) { this.logger = logger; this.daemon = daemon; } /** * Creates a new thread. * * @param r * The runnable task. */ public Thread newThread(Runnable r) { Thread result = new Thread(r); result.setName("Restlet-" + result.hashCode()); result.setUncaughtExceptionHandler(new LoggingExceptionHandler()); result.setDaemon(this.daemon); return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/LoggerFacade.java0000664000175000017500000000766111757206346026465 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.util.logging.Logger; /** * Logger facade to the underlying logging framework used by the Restlet * Framework. By default, it relies on the JULI mechanism built in Java SE. You * can provide an alternate implementation by extending this class and * overriding the methods. * * @author Jerome Louvel */ public class LoggerFacade { /** * Returns an anonymous logger. By default it calls * {@link Logger#getAnonymousLogger()}. This method should be overridden by * subclasses. * * @return The logger. */ public Logger getAnonymousLogger() { return Logger.getAnonymousLogger(); } /** * Returns a logger based on the class name of the given object. By default, * it calls {@link #getLogger(Class, String)} with a null default logger * name. * * @param clazz * The parent class. * @return The logger. */ public final Logger getLogger(Class clazz) { return getLogger(clazz, null); } /** * Returns a logger based on the class name of the given object. * * @param clazz * The parent class. * @param defaultLoggerName * The default logger name to use if no one can be inferred from * the class. * @return The logger. */ public final Logger getLogger(Class clazz, String defaultLoggerName) { String loggerName = null; if (clazz != null) { loggerName = clazz.getCanonicalName(); } if (loggerName == null) { loggerName = defaultLoggerName; } if (loggerName != null) { return getLogger(loggerName); } return getAnonymousLogger(); } /** * Returns a logger based on the class name of the given object. By default, * it calls {@link #getLogger(Class, String)} with the object's class as a * first parameter. * * @param object * The parent object. * @param defaultLoggerName * The default logger name to use if no one can be inferred from * the object class. * @return The logger. */ public final Logger getLogger(Object object, String defaultLoggerName) { return getLogger(object.getClass(), defaultLoggerName); } /** * Returns a logger based on the given logger name. By default, it calls * {@link Logger#getLogger(String)}. This method should be overridden by * subclasses. * * @param loggerName * The logger name. * @return The logger. */ public Logger getLogger(String loggerName) { return Logger.getLogger(loggerName); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/log/DefaultAccessLogFormatter.java0000664000175000017500000000443211757206346031207 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.log; import java.util.logging.Handler; import org.restlet.engine.Engine; /** * Access log record formatter which writes a header describing the default log * format. * * @author Jerome Louvel */ public class DefaultAccessLogFormatter extends AccessLogFormatter { @Override public String getHead(Handler h) { final StringBuilder sb = new StringBuilder(); sb.append("#Software: Restlet Framework ").append(Engine.VERSION) .append('\n'); sb.append("#Version: 1.0\n"); sb.append("#Date: "); final long currentTime = System.currentTimeMillis(); sb.append(String.format("%tF", currentTime)); sb.append(' '); sb.append(String.format("%tT", currentTime)); sb.append('\n'); sb.append("#Fields: "); sb.append("date time c-ip cs-username s-ip s-port cs-method "); sb.append("cs-uri-stem cs-uri-query sc-status sc-bytes cs-bytes "); sb.append("time-taken cs-host cs(User-Agent) cs(Referrer)\n"); return sb.toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/Method.java0000664000175000017500000000365211757206346024615 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Options; import org.restlet.resource.Post; import org.restlet.resource.Put; /** * Meta annotation to declare method annotations. * * @see Get * @see Post * @see Put * @see Delete * @see Options * @author Jerome Louvel */ @Target(ElementType.ANNOTATION_TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Method { /** * Method name identified by the underlying annotation. */ String value(); } restlet-2.0.14/org.restlet/src/org/restlet/engine/ProtocolHelper.java0000664000175000017500000000327211757206346026334 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; /** * Protocol helper. * * @author Thierry Boileau * */ public abstract class ProtocolHelper extends Helper { /** * Constructor. */ public ProtocolHelper() { super(); registerMethods(); } /** * Register all supported methods. The implementation relies on the * {@link org.restlet.data.Method#register(org.restlet.data.Method)} method. */ public abstract void registerMethods(); } restlet-2.0.14/org.restlet/src/org/restlet/engine/package.html0000664000175000017500000000030111757206350024772 0ustar jamespagejamespage Implementation of Restlet API.

    @since Restlet 2.0 @see User Guide - Engine restlet-2.0.14/org.restlet/src/org/restlet/engine/application/0000775000175000017500000000000011757206350025022 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/application/RangeFilter.java0000664000175000017500000001251411757206346030077 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Range; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.routing.Filter; import org.restlet.service.RangeService; // [excludes gwt] /** * Filter that is in charge to check the responses to requests for partial * content. * * @author Thierry Boileau */ public class RangeFilter extends Filter { /** * Constructor. * * @param context * The parent context. */ public RangeFilter(Context context) { super(context); } @Override protected void afterHandle(Request request, Response response) { if (getRangeService().isEnabled()) { response.getServerInfo().setAcceptingRanges(true); if (request.getMethod().isSafe() && response.isEntityAvailable()) { boolean rangedEntity = response.getEntity().getRange() != null; if (response.getStatus().isSuccess() && !Status.SUCCESS_PARTIAL_CONTENT.equals(response .getStatus())) { // At this time, list of ranges are not supported. if (request.getRanges().size() == 1 && (!request.getConditions().hasSomeRange() || request .getConditions() .getRangeStatus(response.getEntity()) .isSuccess())) { Range requestedRange = request.getRanges().get(0); if ((response.getEntity().getSize() == Representation.UNKNOWN_SIZE) && ((requestedRange.getIndex() == Range.INDEX_LAST || requestedRange .getSize() == Range.SIZE_MAX) && !(requestedRange .getIndex() == Range.INDEX_LAST && requestedRange .getSize() == Range.SIZE_MAX))) { // The end index cannot be properly computed response.setStatus(Status.SERVER_ERROR_INTERNAL); getLogger() .warning( "Unable to serve this range since at least the end index of the range cannot be computed."); response.setEntity(null); } else if (!requestedRange.equals(response.getEntity() .getRange())) { if (rangedEntity) { getLogger() .info("The range of the response entity is not equal to the requested one."); } response.setEntity(new RangeRepresentation(response .getEntity(), requestedRange)); response.setStatus(Status.SUCCESS_PARTIAL_CONTENT); } } else if (request.getRanges().size() > 1) { // Return a server error as this feature isn't supported // yet response.setStatus(Status.SERVER_ERROR_NOT_IMPLEMENTED); getLogger() .warning( "Multiple ranges are not supported at this time."); response.setEntity(null); } } else { if (rangedEntity) { getLogger() .info("The status of a response to a partial GET must be \"206 Partial content\"."); } } } } } /** * Returns the Range service of the parent application. * * @return The Range service of the parent application. */ public RangeService getRangeService() { return getApplication().getRangeService(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/DecodeRepresentation.java0000664000175000017500000002045511757206346032006 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; import java.util.zip.ZipInputStream; import org.restlet.data.Encoding; import org.restlet.engine.io.BioUtils; import org.restlet.engine.io.NioUtils; import org.restlet.representation.Representation; import org.restlet.util.WrapperRepresentation; // [excludes gwt] /** * Representation that decodes a wrapped representation if its encoding is * supported. If at least one encoding of the wrapped representation is not * supported, then the wrapped representation is not decoded. * * @author Jerome Louvel */ public class DecodeRepresentation extends WrapperRepresentation { /** * Returns the list of supported encodings. * * @return The list of supported encodings. */ public static List getSupportedEncodings() { return Arrays. asList(Encoding.GZIP, Encoding.DEFLATE, Encoding.ZIP, Encoding.IDENTITY); } /** Indicates if the decoding can happen. */ private volatile boolean decoding; /** List of encodings still applied to the decodeRepresentation */ private volatile List wrappedEncodings; /** * Constructor. * * @param wrappedRepresentation * The wrapped representation. */ public DecodeRepresentation(Representation wrappedRepresentation) { super(wrappedRepresentation); this.decoding = getSupportedEncodings().containsAll( wrappedRepresentation.getEncodings()); this.wrappedEncodings = new ArrayList(); this.wrappedEncodings.addAll(wrappedRepresentation.getEncodings()); } /** * Indicates if the decoding can happen. * * @return True if the decoding can happen. * @deprecated Use {@link #isDecoding()} instead. */ @Deprecated public boolean canDecode() { return this.decoding; } /** * Indicates if the decoding can happen. * * @return True if the decoding can happen. */ public boolean isDecoding() { return canDecode(); } /** * Returns a readable byte channel. If it is supported by a file a read-only * instance of FileChannel is returned. * * @return A readable byte channel. */ @Override public ReadableByteChannel getChannel() throws IOException { if (isDecoding()) { return NioUtils.getChannel(getStream()); } return getWrappedRepresentation().getChannel(); } /** * Returns a decoded stream for a given encoding and coded stream. * * @param encoding * The encoding to use. * @param encodedStream * The encoded stream. * @return The decoded stream. * @throws IOException */ private InputStream getDecodedStream(Encoding encoding, InputStream encodedStream) throws IOException { InputStream result = null; if (encodedStream != null) { if (encoding.equals(Encoding.GZIP)) { result = new GZIPInputStream(encodedStream); } else if (encoding.equals(Encoding.DEFLATE)) { result = new InflaterInputStream(encodedStream); } else if (encoding.equals(Encoding.ZIP)) { final ZipInputStream stream = new ZipInputStream(encodedStream); if (stream.getNextEntry() != null) { result = stream; } } else if (encoding.equals(Encoding.IDENTITY)) { throw new IOException( "Decoder unecessary for identity decoding"); } } return result; } /** * Returns the encodings applied to the entity. * * @return The encodings applied to the entity. */ @Override public List getEncodings() { if (isDecoding()) { return new ArrayList(); } return this.wrappedEncodings; } /** * Returns the size in bytes of the decoded representation if known, * UNKNOWN_SIZE (-1) otherwise. * * @return The size in bytes if known, UNKNOWN_SIZE (-1) otherwise. */ @Override public long getSize() { long result = UNKNOWN_SIZE; if (isDecoding()) { boolean identity = true; for (final Iterator iter = getEncodings().iterator(); identity && iter.hasNext();) { identity = (iter.next().equals(Encoding.IDENTITY)); } if (identity) { result = getWrappedRepresentation().getSize(); } } else { result = getWrappedRepresentation().getSize(); } return result; } /** * Returns a stream with the representation's content. * * @return A stream with the representation's content. */ @Override public InputStream getStream() throws IOException { InputStream result = null; if (isDecoding()) { result = getWrappedRepresentation().getStream(); for (int i = this.wrappedEncodings.size() - 1; i >= 0; i--) { if (!this.wrappedEncodings.get(i).equals(Encoding.IDENTITY)) { result = getDecodedStream(this.wrappedEncodings.get(i), result); } } } return result; } /** * Converts the representation to a string value. Be careful when using this * method as the conversion of large content to a string fully stored in * memory can result in OutOfMemoryErrors being thrown. * * @return The representation as a string value. */ @Override public String getText() throws IOException { String result = null; if (isDecoding()) { result = BioUtils.toString(getStream(), getCharacterSet()); } else { result = getWrappedRepresentation().getText(); } return result; } /** * Writes the representation to a byte stream. * * @param outputStream * The output stream. */ @Override public void write(OutputStream outputStream) throws IOException { if (isDecoding()) { BioUtils.copy(getStream(), outputStream); } else { getWrappedRepresentation().write(outputStream); } } /** * Writes the representation to a byte channel. * * @param writableChannel * A writable byte channel. */ @Override public void write(WritableByteChannel writableChannel) throws IOException { if (isDecoding()) { write(NioUtils.getStream(writableChannel)); } else { getWrappedRepresentation().write(writableChannel); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/Decoder.java0000664000175000017500000002052611757206346027244 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.util.Iterator; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Encoding; import org.restlet.representation.Representation; import org.restlet.routing.Filter; // [excludes gwt] /** * Filter decompressing entities. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class Decoder extends Filter { /** * Indicates if the request entity should be decoded. */ private volatile boolean decodingRequest; /** * Indicates if the response entity should be decoded. */ private volatile boolean decodingResponse; /** * Constructor to only decode request entities before handling. * * @param context * The context. */ public Decoder(Context context) { this(context, true, false); } /** * Constructor. * * @param context * The context. * @param decodingRequest * Indicates if the request entity should be decoded. * @param decodingResponse * Indicates if the response entity should be decoded. */ public Decoder(Context context, boolean decodingRequest, boolean decodingResponse) { super(context); this.decodingRequest = decodingRequest; this.decodingResponse = decodingResponse; } /** * Allows filtering after its handling by the target Restlet. Does nothing * by default. * * @param request * The request to filter. * @param response * The response to filter. */ @Override public void afterHandle(Request request, Response response) { // Check if decoding of the response entity is needed if (isDecodingResponse() && canDecode(response.getEntity())) { response.setEntity(decode(response.getEntity())); } } /** * Allows filtering before its handling by the target Restlet. Does nothing * by default. * * @param request * The request to filter. * @param response * The response to filter. * @return The continuation status. */ @Override public int beforeHandle(Request request, Response response) { // Check if decoding of the request entity is needed if (isDecodingRequest() && canDecode(request.getEntity())) { request.setEntity(decode(request.getEntity())); } return CONTINUE; } /** * Indicates if a representation can be decoded. * * @param representation * The representation to test. * @return True if the call can be decoded. */ public boolean canDecode(Representation representation) { // Test the existence of the representation and that at least an // encoding applies. boolean result = (representation != null) && (!representation.getEncodings().isEmpty()); if (result) { boolean found = false; for (final Iterator iter = representation.getEncodings() .iterator(); !found && iter.hasNext();) { found = (!iter.next().equals(Encoding.IDENTITY)); } result = found; } return result; } /** * Decodes a given representation if its encodings are supported by NRE. * * @param representation * The representation to encode. * @return The decoded representation or the original one if the encoding * isn't supported by NRE. */ public Representation decode(Representation representation) { Representation result = representation; // Check if all encodings of the representation are supported in order // to avoid the creation of a useless decodeRepresentation object. // False if an encoding is not supported boolean supported = true; // True if all representation's encodings are IDENTITY boolean identityEncodings = true; for (final Iterator iter = representation.getEncodings() .iterator(); supported && iter.hasNext();) { final Encoding encoding = iter.next(); supported = DecodeRepresentation.getSupportedEncodings().contains( encoding); identityEncodings &= encoding.equals(Encoding.IDENTITY); } if (supported && !identityEncodings) { result = new DecodeRepresentation(representation); } return result; } /** * Indicates if the request entity should be decoded. * * @return True if the request entity should be decoded. * @deprecated Use {@link #isDecodingRequest()} instead. */ @Deprecated public boolean isDecodeRequest() { return this.decodingRequest; } /** * Indicates if the response entity should be decoded. * * @return True if the response entity should be decoded. * @deprecated Use {@link #isDecodingResponse()} instead. */ @Deprecated public boolean isDecodeResponse() { return this.decodingResponse; } /** * Indicates if the request entity should be decoded. * * @return True if the request entity should be decoded. */ public boolean isDecodingRequest() { return isDecodeRequest(); } /** * Indicates if the response entity should be decoded. * * @return True if the response entity should be decoded. */ public boolean isDecodingResponse() { return isDecodeResponse(); } /** * Indicates if the request entity should be decoded. * * @param decodingRequest * True if the request entity should be decoded. * @deprecated Use {@link #setDecodingRequest(boolean)} instead. */ @Deprecated public void setDecodeRequest(boolean decodingRequest) { this.decodingRequest = decodingRequest; } /** * Indicates if the response entity should be decoded. * * @param decodingResponse * True if the response entity should be decoded. * @deprecated Use {@link #setDecodingResponse(boolean)} instead. */ @Deprecated public void setDecodeResponse(boolean decodingResponse) { this.decodingResponse = decodingResponse; } /** * Indicates if the request entity should be decoded. * * @param decodingRequest * True if the request entity should be decoded. */ public void setDecodingRequest(boolean decodingRequest) { setDecodeRequest(decodingRequest); } /** * Indicates if the response entity should be decoded. * * @param decodingResponse * True if the response entity should be decoded. */ public void setDecodingResponse(boolean decodingResponse) { setDecodeResponse(decodingResponse); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/TunnelFilter.java0000664000175000017500000005636211757206350030314 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.data.ClientInfo; import org.restlet.data.Encoding; import org.restlet.data.Form; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Preference; import org.restlet.data.Reference; import org.restlet.engine.Engine; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.PreferenceReader; import org.restlet.engine.io.IoUtils; import org.restlet.routing.Filter; import org.restlet.service.MetadataService; import org.restlet.service.TunnelService; import org.restlet.util.Series; // [excludes gwt] /** * Filter tunneling browser calls into full REST calls. The request method can * be changed (via POST requests only) as well as the accepted media types, * languages, encodings and character sets. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class TunnelFilter extends Filter { /** * Used to describe the replacement value for an old client preference and * for a a series of specific agent (i.e. web client) attributes. * * @author Thierry Boileau */ private static class AcceptReplacer { static class Builder { String acceptOld; String acceptNew; Map agentAttributes = new HashMap(); void setAcceptOld(String acceptOld) { this.acceptOld = acceptOld; } void setAcceptNew(String acceptNew) { this.acceptNew = acceptNew; } void putAgentAttribute(String key, String value) { agentAttributes.put(key, value); } AcceptReplacer build() { return new AcceptReplacer(acceptOld, acceptNew, agentAttributes); } } AcceptReplacer(String acceptOld, String acceptNew, Map agentAttributes) { this.acceptOld = acceptOld; this.acceptNew = acceptNew; this.agentAttributes = Collections.unmodifiableMap(agentAttributes); } /** New accept header value. */ private final String acceptNew; /** Old accept header value. */ private final String acceptOld; /** Agent attributes that must be checked. */ private final Map agentAttributes; public String getAcceptNew() { return acceptNew; } public String getAcceptOld() { return acceptOld; } public Map getAgentAttributes() { return agentAttributes; } } /** Used to replace accept header values. */ private final List acceptReplacers = getAcceptReplacers(); /** * Constructor. * * @param context * The parent context. */ public TunnelFilter(Context context) { super(context); } @Override public int beforeHandle(Request request, Response response) { if (getTunnelService().isUserAgentTunnel()) { processUserAgent(request); } if (getTunnelService().isExtensionsTunnel()) { processExtensions(request); } if (getTunnelService().isQueryTunnel()) { processQuery(request); } if (getTunnelService().isHeadersTunnel()) { processHeaders(request); } return CONTINUE; } /** * Returns the list of new accept header values. Each of them describe also * a set of conditions required to set the new value. This method is used * only to initialize the acceptReplacers field. * * @return The list of new accept header values. */ private List getAcceptReplacers() { List acceptReplacers = new ArrayList(); // Load the accept.properties file. final URL userAgentPropertiesUrl = Engine .getResource("org/restlet/service/accept.properties"); if (userAgentPropertiesUrl != null) { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader( userAgentPropertiesUrl.openStream(), CharacterSet.UTF_8 .getName()), IoUtils.getBufferSize()); AcceptReplacer.Builder acceptReplacerBuilder = new AcceptReplacer.Builder(); try { // Read the entire file, excluding comment lines starting // with "#" character. String line = reader.readLine(); for (; line != null; line = reader.readLine()) { if (!line.startsWith("#")) { final String[] keyValue = line.split(":"); if (keyValue.length == 2) { final String key = keyValue[0].trim(); final String value = keyValue[1].trim(); if ("acceptOld".equalsIgnoreCase(key)) { acceptReplacerBuilder.setAcceptOld(("" .equals(value)) ? null : value); } else if ("acceptNew".equalsIgnoreCase(key)) { acceptReplacerBuilder.setAcceptNew(value); acceptReplacers.add(acceptReplacerBuilder .build()); acceptReplacerBuilder = new AcceptReplacer.Builder(); } else { acceptReplacerBuilder.putAgentAttribute( key, value); } } } } } finally { reader.close(); } } catch (IOException e) { getContext().getLogger().warning( "Cannot read '" + userAgentPropertiesUrl.toString() + "' due to: " + e.getMessage()); } } return acceptReplacers; } /** * Returns the metadata associated to the given extension using the * {@link MetadataService}. * * @param extension * The extension to lookup. * @return The matched metadata. */ private Metadata getMetadata(String extension) { return getMetadataService().getMetadata(extension); } /** * Returns the metadata service of the parent application. * * @return The metadata service of the parent application. */ public MetadataService getMetadataService() { return getApplication().getMetadataService(); } /** * Returns the tunnel service of the parent application. * * @return The tunnel service of the parent application. */ public TunnelService getTunnelService() { return getApplication().getTunnelService(); } /** * Updates the client preferences based on file-like extensions. The matched * extensions are removed from the last segment. * * See also section 3.6.1 of JAX-RS specification (https://jsr311.dev.java.net) * * @param request * The request to update. * @return True if the query has been updated, false otherwise. */ private boolean processExtensions(Request request) { final TunnelService tunnelService = getTunnelService(); boolean extensionsModified = false; // Tunnel the client preferences only for GET or HEAD requests final Method method = request.getMethod(); if (tunnelService.isPreferencesTunnel() && (method.equals(Method.GET) || method.equals(Method.HEAD))) { final Reference resourceRef = request.getResourceRef(); if (resourceRef.hasExtensions()) { final ClientInfo clientInfo = request.getClientInfo(); boolean encodingFound = false; boolean characterSetFound = false; boolean mediaTypeFound = false; boolean languageFound = false; String extensions = resourceRef.getExtensions(); // Discover extensions from right to left and stop at the first // unknown extension. Only one extension per type of metadata is // also allowed: i.e. one language, one media type, one // encoding, one character set. while (true) { final int lastIndexOfPoint = extensions.lastIndexOf('.'); final String extension = extensions .substring(lastIndexOfPoint + 1); final Metadata metadata = getMetadata(extension); if (!mediaTypeFound && (metadata instanceof MediaType)) { updateMetadata(clientInfo, metadata); mediaTypeFound = true; } else if (!languageFound && (metadata instanceof Language)) { updateMetadata(clientInfo, metadata); languageFound = true; } else if (!characterSetFound && (metadata instanceof CharacterSet)) { updateMetadata(clientInfo, metadata); characterSetFound = true; } else if (!encodingFound && (metadata instanceof Encoding)) { updateMetadata(clientInfo, metadata); encodingFound = true; } else { // extension do not match -> break loop break; } if (lastIndexOfPoint > 0) { extensions = extensions.substring(0, lastIndexOfPoint); } else { // no more extensions -> break loop extensions = ""; break; } } // Update the extensions if necessary if (encodingFound || characterSetFound || mediaTypeFound || languageFound) { resourceRef.setExtensions(extensions); extensionsModified = true; } } } return extensionsModified; } /** * Updates the request method based on specific header. * * @param request * The request to update. */ @SuppressWarnings("unchecked") private void processHeaders(Request request) { final TunnelService tunnelService = getTunnelService(); if (tunnelService.isMethodTunnel()) { // get the headers final Series extraHeaders = (Series) request .getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); if (extraHeaders != null) { // look for the new value of the method final String newMethodValue = extraHeaders.getFirstValue( getTunnelService().getMethodHeader(), true); if (newMethodValue != null && newMethodValue.trim().length() > 0) { // set the current method to the new method request.setMethod(Method.valueOf(newMethodValue)); } } } } /** * Updates the request method and client preferences based on query * parameters. The matched parameters are removed from the query. * * @param request * The request to update. * @return True if the query has been updated, false otherwise. */ private boolean processQuery(Request request) { TunnelService tunnelService = getTunnelService(); boolean queryModified = false; Reference resourceRef = request.getResourceRef(); if (resourceRef.hasQuery()) { Form query = resourceRef.getQueryAsForm(); // Tunnel the request method Method method = request.getMethod(); if (tunnelService.isMethodTunnel()) { String methodName = query.getFirstValue(tunnelService .getMethodParameter()); Method tunnelledMethod = Method.valueOf(methodName); // The OPTIONS method can be tunneled via GET requests. if (tunnelledMethod != null && (Method.POST.equals(method) || Method.OPTIONS .equals(tunnelledMethod))) { request.setMethod(tunnelledMethod); query.removeFirst(tunnelService.getMethodParameter()); queryModified = true; } } // Tunnel the client preferences if (tunnelService.isPreferencesTunnel()) { // Get the parameter names to look for String charSetParameter = tunnelService .getCharacterSetParameter(); String encodingParameter = tunnelService.getEncodingParameter(); String languageParameter = tunnelService.getLanguageParameter(); String mediaTypeParameter = tunnelService .getMediaTypeParameter(); // Get the preferences from the query String acceptedCharSet = query.getFirstValue(charSetParameter); String acceptedEncoding = query .getFirstValue(encodingParameter); String acceptedLanguage = query .getFirstValue(languageParameter); String acceptedMediaType = query .getFirstValue(mediaTypeParameter); // Updates the client preferences ClientInfo clientInfo = request.getClientInfo(); Metadata metadata = getMetadata(acceptedCharSet); if ((metadata == null) && (acceptedCharSet != null)) { metadata = CharacterSet.valueOf(acceptedCharSet); } if (metadata instanceof CharacterSet) { updateMetadata(clientInfo, metadata); query.removeFirst(charSetParameter); queryModified = true; } metadata = getMetadata(acceptedEncoding); if ((metadata == null) && (acceptedEncoding != null)) { metadata = Encoding.valueOf(acceptedEncoding); } if (metadata instanceof Encoding) { updateMetadata(clientInfo, metadata); query.removeFirst(encodingParameter); queryModified = true; } metadata = getMetadata(acceptedLanguage); if ((metadata == null) && (acceptedLanguage != null)) { metadata = Language.valueOf(acceptedLanguage); } if (metadata instanceof Language) { updateMetadata(clientInfo, metadata); query.removeFirst(languageParameter); queryModified = true; } metadata = getMetadata(acceptedMediaType); if ((metadata == null) && (acceptedMediaType != null)) { metadata = MediaType.valueOf(acceptedMediaType); } if (metadata instanceof MediaType) { updateMetadata(clientInfo, metadata); query.removeFirst(mediaTypeParameter); queryModified = true; } } // Update the query if it has been modified if (queryModified) { request.getResourceRef().setQuery(query.getQueryString(null)); } } return queryModified; } /** * Updates the client preferences according to the user agent properties * (name, version, etc.) taken from the "agent.properties" file located in * the classpath. See {@link ClientInfo#getAgentAttributes()} for more * details.
    * The list of new media type preferences is loaded from a property file * called "accept.properties" located in the classpath in the sub directory * "org/restlet/service". This property file is composed of blocks of * properties. One "block" of properties starts either with the beginning of * the properties file or with the end of the previous block. One block ends * with the "acceptNew" property which contains the value of the new accept * header. Here is a sample block. * *

         * agentName: firefox
         * acceptOld: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,\*\/\*;q=0.5
         * acceptNew: application/xhtml+xml,text/html,text/xml;q=0.9,application/xml;q=0.9,text/plain;q=0.8,image/png,\*\/\*;q=0.5
         * 
    * * Each declared property is a condition that must be filled in order to * update the client preferences. For example "agentName: firefox" expresses * the fact this block concerns only "firefox" clients. * * The "acceptOld" property allows to check the value of the current * "Accept" header. If the latest equals to the value of the "acceptOld" * property then the preferences will be updated. This is useful for Ajax * clients which looks like their browser (same agentName, agentVersion, * etc.) but can provide their own "Accept" header. * * @param request * the request to update. */ private void processUserAgent(Request request) { final Map agentAttributes = request.getClientInfo() .getAgentAttributes(); if (agentAttributes != null) { if (!this.acceptReplacers.isEmpty()) { // Get the old Accept header value Form headers = (Form) request.getAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); String acceptOld = (headers != null) ? headers.getFirstValue( HeaderConstants.HEADER_ACCEPT, true) : null; // Check each replacer for (AcceptReplacer acceptReplacer : this.acceptReplacers) { // Check the conditions boolean checked = true; for (String key : acceptReplacer.getAgentAttributes() .keySet()) { String attribute = agentAttributes.get(key); // Check that the agent properties match the properties // set by the rule. checked = checked && (attribute != null && attribute .equalsIgnoreCase(acceptReplacer .getAgentAttributes().get(key))); } if (checked) { // If the rule defines an acceptOld value, check that it // is the same than the user agent's "accept" header // value. if (acceptReplacer.getAcceptOld() != null) { checked = acceptReplacer.getAcceptOld().equals( acceptOld); } if (checked) { ClientInfo clientInfo = new ClientInfo(); PreferenceReader.addMediaTypes(acceptReplacer .getAcceptNew(), clientInfo); request.getClientInfo().setAcceptedMediaTypes( clientInfo.getAcceptedMediaTypes()); break; } } } } } } /** * Updates the client info with the given metadata. It clears existing * preferences for the same type of metadata if necessary. * * @param clientInfo * The client info to update. * @param metadata * The metadata to use. */ private void updateMetadata(ClientInfo clientInfo, Metadata metadata) { if (metadata != null) { if (metadata instanceof CharacterSet) { clientInfo.getAcceptedCharacterSets().clear(); clientInfo.getAcceptedCharacterSets().add( new Preference((CharacterSet) metadata)); } else if (metadata instanceof Encoding) { clientInfo.getAcceptedEncodings().clear(); clientInfo.getAcceptedEncodings().add( new Preference((Encoding) metadata)); } else if (metadata instanceof Language) { clientInfo.getAcceptedLanguages().clear(); clientInfo.getAcceptedLanguages().add( new Preference((Language) metadata)); } else if (metadata instanceof MediaType) { clientInfo.getAcceptedMediaTypes().clear(); clientInfo.getAcceptedMediaTypes().add( new Preference((MediaType) metadata)); } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/StatusFilter.java0000664000175000017500000002754611757206346030341 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.routing.Filter; import org.restlet.service.StatusService; // [excludes gwt] /** * Filter associating a response entity based on the status. In order to * customize the default representation, just subclass this class and override * the "getRepresentation" method.
    * If any exception occurs during the call handling, a "server internal error" * status is automatically associated to the call. Of course, you can * personalize the representation of this error. Also, if no status is set * (null), then the "success OK" status is assumed. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class StatusFilter extends Filter { /** The email address of the administrator to contact in case of error. */ private volatile String contactEmail; /** The home URI to propose in case of error. */ private volatile Reference homeRef; /** Indicates if existing representations should be overwritten. */ private volatile boolean overwriting; /** The helped status service. */ private volatile StatusService statusService; /** * Constructor. * * @param context * The context. * @param overwriting * Indicates whether an existing representation should be * overwritten. * @param email * Email address of the administrator to contact in case of * error. * @param homeRef * The home URI to propose in case of error. */ public StatusFilter(Context context, boolean overwriting, String email, Reference homeRef) { super(context); this.overwriting = overwriting; this.contactEmail = email; this.homeRef = homeRef; this.statusService = null; } /** * Constructor from a status service. * * @param context * The context. * @param statusService * The helped status service. */ public StatusFilter(Context context, StatusService statusService) { this(context, statusService.isOverwriting(), statusService .getContactEmail(), statusService.getHomeRef()); this.statusService = statusService; } /** * Allows filtering after its handling by the target Restlet. Does nothing * by default. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void afterHandle(Request request, Response response) { // If no status is set, then the "success ok" status is assumed. if (response.getStatus() == null) { response.setStatus(Status.SUCCESS_OK); } // Do we need to get a representation for the current status? if (response.getStatus().isError() && ((response.getEntity() == null) || isOverwriting())) { response.setEntity(getRepresentation(response.getStatus(), request, response)); } } /** * Handles the call by distributing it to the next Restlet. If a throwable * is caught, the {@link #getStatus(Throwable, Request, Response)} method is * invoked. * * @param request * The request to handle. * @param response * The response to update. * @return The continuation status. */ @Override protected int doHandle(Request request, Response response) { // Normally handle the call try { super.doHandle(request, response); } catch (Throwable t) { getLogger().log(Level.WARNING, "Exception or error caught in status service", t); response.setStatus(getStatus(t, request, response)); } return CONTINUE; } /** * Returns the email address of the administrator to contact in case of * error. * * @return The email address. */ public String getContactEmail() { return contactEmail; } /** * Returns a representation for the given status.
    * In order to customize the default representation, this method can be * overridden. * * @param status * The status to represent. * @param request * The request handled. * @param response * The response updated. * @return The representation of the given status. */ protected Representation getDefaultRepresentation(Status status, Request request, Response response) { final StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("\n"); sb.append(" Status page\n"); sb.append("\n"); sb.append("\n"); sb.append("

    "); sb.append(getStatusInfo(status)); sb.append("

    \n"); if (status.getDescription() != null) { sb.append("

    "); sb.append(status.getDescription()); sb.append("

    \n"); } sb.append("

    You can get technical details here.
    \n"); if (getContactEmail() != null) { sb.append("For further assistance, you can contact the administrator.
    \n"); } if (getHomeRef() != null) { sb.append("Please continue your visit at our home page.\n"); } sb.append("

    \n"); sb.append("\n"); sb.append("\n"); return new StringRepresentation(sb.toString(), MediaType.TEXT_HTML); } /** * Returns the home URI to propose in case of error. * * @return The home URI. */ public Reference getHomeRef() { return homeRef; } /** * Returns a representation for the given status.
    * In order to customize the default representation, this method can be * overridden. * * @param status * The status to represent. * @param request * The request handled. * @param response * The response updated. * @return The representation of the given status. */ protected Representation getRepresentation(Status status, Request request, Response response) { Representation result = getStatusService().getRepresentation(status, request, response); if (result == null) { result = getDefaultRepresentation(status, request, response); } return result; } /** * Returns a status for a given exception or error. By default it returns an * {@link Status#SERVER_ERROR_INTERNAL} status including the related error * or exception and logs a severe message.
    * In order to customize the default behavior, this method can be overriden. * * @param throwable * The exception or error caught. * @param request * The request handled. * @param response * The response updated. * @return The representation of the given status. */ protected Status getStatus(Throwable throwable, Request request, Response response) { return getStatusService().getStatus(throwable, request, response); } /** * Returns the status information to display in the default representation. * By default it returns the status's name. * * @param status * The status. * @return The status information. * @see #getDefaultRepresentation(Status, Request, Response) */ protected String getStatusInfo(Status status) { return (status.getName() != null) ? status.getName() : "No information available for this result status"; } /** * Returns the helped status service. * * @return The helped status service. */ public StatusService getStatusService() { return statusService; } /** * Indicates if existing representations should be overwritten. * * @return True if existing representations should be overwritten. * @deprecated Use {@link #isOverwriting()} instead. */ @Deprecated public boolean isOverwrite() { return overwriting; } /** * Indicates if existing representations should be overwritten. * * @return True if existing representations should be overwritten. */ public boolean isOverwriting() { return isOverwrite(); } /** * Sets the email address of the administrator to contact in case of error. * * @param email * The email address. */ public void setContactEmail(String email) { this.contactEmail = email; } /** * Sets the home URI to propose in case of error. * * @param homeRef * The home URI. */ public void setHomeRef(Reference homeRef) { this.homeRef = homeRef; } /** * Indicates if existing representations should be overwritten. * * @param overwriting * True if existing representations should be overwritten. * @deprecated Use {@link #setOverwriting(boolean)} instead. */ @Deprecated public void setOverwrite(boolean overwriting) { this.overwriting = overwriting; } /** * Indicates if existing representations should be overwritten. * * @param overwriting * True if existing representations should be overwritten. */ public void setOverwriting(boolean overwriting) { setOverwrite(overwriting); } /** * Sets the helped status service. * * @param statusService * The helped status service. */ public void setStatusService(StatusService statusService) { this.statusService = statusService; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/ApplicationHelper.java0000664000175000017500000000604211757206350031272 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.engine.ChainHelper; import org.restlet.routing.Filter; import org.restlet.service.Service; // [excludes gwt] /** * Application implementation. * * @author Jerome Louvel */ public class ApplicationHelper extends ChainHelper { /** * Constructor. * * @param application * The application to help. */ public ApplicationHelper(Application application) { super(application); } /** * In addition to the default behavior, it saves the current application * instance into the current thread. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { // Save the current application Application.setCurrent(getHelped()); // Actually handle call super.handle(request, response); } /** Start hook. */ @Override public synchronized void start() throws Exception { // Attach the service inbound filters Filter inboundFilter = null; for (Service service : getHelped().getServices()) { if (service.isEnabled()) { inboundFilter = service.createInboundFilter(getContext()); if (inboundFilter != null) { addFilter(inboundFilter); } } } // Attach the Application's server root Restlet setNext(getHelped().getInboundRoot()); } @Override public synchronized void stop() throws Exception { clear(); } @Override public void update() throws Exception { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/package.html0000664000175000017500000000013111757206350027276 0ustar jamespagejamespage Supports Restlet applications.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/application/RangeRepresentation.java0000664000175000017500000001054311757206346031654 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.nio.channels.WritableByteChannel; import org.restlet.data.Range; import org.restlet.engine.io.BioUtils; import org.restlet.engine.io.NioUtils; import org.restlet.representation.Representation; import org.restlet.util.WrapperRepresentation; // [excludes gwt] /** * Representation that exposes only a range of the content of a wrapped * representation. * * @author Jerome Louvel */ public class RangeRepresentation extends WrapperRepresentation { /** The range specific to this wrapper. */ private volatile Range range; /** * Constructor. * * @param wrappedRepresentation * The wrapped representation with a complete content. */ public RangeRepresentation(Representation wrappedRepresentation) { this(wrappedRepresentation, null); } /** * Constructor. * * @param wrappedRepresentation * The wrapped representation with a complete content. * @param range * The range to expose. */ public RangeRepresentation(Representation wrappedRepresentation, Range range) { super(wrappedRepresentation); if (wrappedRepresentation.getRange() != null) { throw new IllegalArgumentException( "The wrapped representation must not have a range set."); } setRange(range); } @Override public long getAvailableSize() { return BioUtils.getAvailableSize(this); } @Override public java.nio.channels.ReadableByteChannel getChannel() throws IOException { return org.restlet.engine.io.NioUtils.getChannel(getStream()); } /** * Returns the range specific to this wrapper. The wrapped representation * must not have a range set itself. * * @return The range specific to this wrapper. */ @Override public Range getRange() { return this.range; } @Override public Reader getReader() throws IOException { return BioUtils.getReader(getStream(), getCharacterSet()); } @Override public InputStream getStream() throws IOException { return new RangeInputStream(super.getStream(), getSize(), getRange()); } @Override public String getText() throws IOException { return BioUtils.getText(this); } /** * Sets the range specific to this wrapper. This will not affect the wrapped * representation. * * @param range * The range specific to this wrapper. */ @Override public void setRange(Range range) { this.range = range; } @Override public void write(java.io.Writer writer) throws IOException { write(BioUtils.getStream(writer)); } @Override public void write(OutputStream outputStream) throws IOException { BioUtils.copy(getStream(), outputStream); } @Override public void write(WritableByteChannel writableChannel) throws IOException { write(NioUtils.getStream(writableChannel)); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/Encoder.java0000664000175000017500000003535511757206346027264 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ClientInfo; import org.restlet.data.Encoding; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.representation.Representation; import org.restlet.routing.Filter; // [excludes gwt] /** * Filter compressing entities. The best encoding is automatically selected * based on the preferences of the client and on the encoding supported by NRE: * GZip, Zip and Deflate. *

    * If the {@link org.restlet.representation.Representation} has an unknown size, * it will always be a candidate for encoding. Candidate representations need to * respect media type criteria by the lists of accepted and ignored media types. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Lars Heuer (heuer[at]semagia.com) Semagia * @author Jerome Louvel */ public class Encoder extends Filter { /** * Indicates if the encoding should always occur, regardless of the size. */ public static final int ENCODE_ALL_SIZES = -1; /** * Returns the list of default encoded media types. This can be overridden * by subclasses. By default, all media types are encoded (except those * explicitly ignored). * * @return The list of default encoded media types. */ public static List getDefaultAcceptedMediaTypes() { final List result = new ArrayList(); result.add(MediaType.ALL); return result; } /** * Returns the list of default ignored media types. This can be overridden * by subclasses. By default, all archive, audio, image and video media * types are ignored. * * @return The list of default ignored media types. */ public static List getDefaultIgnoredMediaTypes() { final List result = Arrays. asList( MediaType.APPLICATION_CAB, MediaType.APPLICATION_GNU_ZIP, MediaType.APPLICATION_ZIP, MediaType.APPLICATION_GNU_TAR, MediaType.APPLICATION_JAVA_ARCHIVE, MediaType.APPLICATION_STUFFIT, MediaType.APPLICATION_TAR, MediaType.AUDIO_ALL, MediaType.IMAGE_ALL, MediaType.VIDEO_ALL); return result; } /** * The media types that should be encoded. */ private volatile List acceptedMediaTypes; /** * Indicates if the request entity should be encoded. */ private volatile boolean encodingRequest; /** * Indicates if the response entity should be encoded. */ private volatile boolean encodingResponse; /** * The media types that should be ignored. */ private volatile List ignoredMediaTypes; /** * The minimal size necessary for encoding. */ private volatile long mininumSize; /** * Constructor using the default media types and with * {@link #ENCODE_ALL_SIZES} setting. This constructor will only encode * response entities after call handling. * * @param context * The context. */ public Encoder(Context context) { this(context, false, true, ENCODE_ALL_SIZES, getDefaultAcceptedMediaTypes(), getDefaultIgnoredMediaTypes()); } /** * Constructor. * * @param context * The context. * @param encodingInput * Indicates if the request entities should be encoded. * @param encodingOutput * Indicates if the response entities should be encoded. * @param minimumSize * The minimal size of the representation where compression * should be used. * @param acceptedMediaTypes * The media types that should be encoded. * @param ignoredMediaTypes * The media types that should be ignored. */ public Encoder(Context context, boolean encodingInput, boolean encodingOutput, long minimumSize, List acceptedMediaTypes, List ignoredMediaTypes) { super(context); this.encodingRequest = encodingInput; this.encodingResponse = encodingOutput; this.mininumSize = minimumSize; this.acceptedMediaTypes = acceptedMediaTypes; this.ignoredMediaTypes = ignoredMediaTypes; } /** * Allows filtering after its handling by the target Restlet. Does nothing * by default. * * @param request * The request to filter. * @param response * The response to filter. */ @Override public void afterHandle(Request request, Response response) { // Check if encoding of the response entity is needed if (isEncodingResponse() && canEncode(response.getEntity())) { response.setEntity(encode(request.getClientInfo(), response.getEntity())); } } /** * Allows filtering before its handling by the target Restlet. Does nothing * by default. * * @param request * The request to filter. * @param response * The response to filter. * @return The continuation status. */ @Override public int beforeHandle(Request request, Response response) { // Check if encoding of the request entity is needed if (isEncodingRequest() && canEncode(request.getEntity())) { request.setEntity(encode(request.getClientInfo(), request.getEntity())); } return CONTINUE; } /** * Indicates if a representation can be encoded. * * @param representation * The representation to test. * @return True if the call can be encoded. */ public boolean canEncode(Representation representation) { // Test the existence of the representation and that no existing // encoding applies boolean result = false; if (representation != null) { boolean identity = true; for (final Iterator iter = representation.getEncodings() .iterator(); identity && iter.hasNext();) { identity = (iter.next().equals(Encoding.IDENTITY)); } result = identity; } if (result) { // Test the size of the representation result = (getMinimumSize() == ENCODE_ALL_SIZES) || (representation.getSize() == Representation.UNKNOWN_SIZE) || (representation.getSize() >= getMinimumSize()); } if (result) { // Test the acceptance of the media type final MediaType mediaType = representation.getMediaType(); boolean accepted = false; for (final Iterator iter = getAcceptedMediaTypes() .iterator(); !accepted && iter.hasNext();) { accepted = iter.next().includes(mediaType); } result = accepted; } if (result) { // Test the rejection of the media type final MediaType mediaType = representation.getMediaType(); boolean rejected = false; for (final Iterator iter = getIgnoredMediaTypes() .iterator(); !rejected && iter.hasNext();) { rejected = iter.next().includes(mediaType); } result = !rejected; } return result; } /** * Encodes a given representation if an encoding is supported by the client. * * @param client * The client preferences to use. * @param representation * The representation to encode. * @return The encoded representation or the original one if no encoding * supported by the client. */ public Representation encode(ClientInfo client, Representation representation) { Representation result = representation; final Encoding bestEncoding = getBestEncoding(client); if (bestEncoding != null) { result = new EncodeRepresentation(bestEncoding, representation); } return result; } /** * Returns the media types that should be encoded. * * @return The media types that should be encoded. */ public List getAcceptedMediaTypes() { return this.acceptedMediaTypes; } /** * Returns the best supported encoding for a given client. * * @param client * The client preferences to use. * @return The best supported encoding for the given call. */ public Encoding getBestEncoding(ClientInfo client) { Encoding bestEncoding = null; Encoding currentEncoding = null; Preference currentPref = null; float bestScore = 0F; for (Iterator iter = getSupportedEncodings().iterator(); iter .hasNext();) { currentEncoding = iter.next(); for (Iterator> iter2 = client .getAcceptedEncodings().iterator(); iter2.hasNext();) { currentPref = iter2.next(); if (currentPref.getMetadata().equals(Encoding.ALL) || currentPref.getMetadata().equals(currentEncoding)) { // A match was found, compute its score if (currentPref.getQuality() > bestScore) { bestScore = currentPref.getQuality(); bestEncoding = currentEncoding; } } } } return bestEncoding; } /** * Returns the media types that should be ignored. * * @return The media types that should be ignored. */ public List getIgnoredMediaTypes() { return this.ignoredMediaTypes; } /** * Returns the minimum size a representation must have before compression is * done. * * @return The minimum size a representation must have before compression is * done. */ public long getMinimumSize() { return this.mininumSize; } /** * Returns the list of supported encodings. By default it calls * {@link EncodeRepresentation#getSupportedEncodings()} static method. * * @return The list of supported encodings. */ public List getSupportedEncodings() { return EncodeRepresentation.getSupportedEncodings(); } /** * Indicates if the request entity should be encoded. * * @return True if the request entity should be encoded. * @deprecated Use {@link #isEncodingRequest()} instead. */ @Deprecated public boolean isEncodeRequest() { return this.encodingRequest; } /** * Indicates if the response entity should be encoded. * * @return True if the response entity should be encoded. * @deprecated Use {@link #isEncodingResponse()} instead. */ @Deprecated public boolean isEncodeResponse() { return this.encodingResponse; } /** * Indicates if the request entity should be encoded. * * @return True if the request entity should be encoded. */ public boolean isEncodingRequest() { return isEncodeRequest(); } /** * Indicates if the response entity should be encoded. * * @return True if the response entity should be encoded. */ public boolean isEncodingResponse() { return isEncodeResponse(); } /** * Indicates if the request entity should be encoded. * * @param encodingRequest * True if the request entity should be encoded. * @deprecated Use {@link #setEncodingRequest(boolean)} instead. */ @Deprecated public void setEncodeRequest(boolean encodingRequest) { this.encodingRequest = encodingRequest; } /** * Indicates if the response entity should be encoded. * * @param encodingResponse * True if the response entity should be encoded. * @deprecated Use {@link #setEncodingResponse(boolean)} instead. */ @Deprecated public void setEncodeResponse(boolean encodingResponse) { this.encodingResponse = encodingResponse; } /** * Indicates if the request entity should be encoded. * * @param encodingRequest * True if the request entity should be encoded. */ public void setEncodingRequest(boolean encodingRequest) { setEncodeRequest(encodingRequest); } /** * Indicates if the response entity should be encoded. * * @param encodingResponse * True if the response entity should be encoded. */ public void setEncodingResponse(boolean encodingResponse) { setEncodeResponse(encodingResponse); } /** * Sets the minimum size a representation must have before compression is * done. * * @param mininumSize * The minimum size a representation must have before compression * is done. */ public void setMinimumSize(long mininumSize) { this.mininumSize = mininumSize; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/MetadataExtension.java0000664000175000017500000000576411757206346031323 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import org.restlet.data.CharacterSet; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; /** * Associates an extension name and a metadata. * * @author Alex Milowski (alexml@milowski.org) * @author Thierry Boileau */ public class MetadataExtension { /** The mapped metadata. */ private final Metadata metadata; /** The name of the extension. */ private final String name; /** * Constructor. * * @param name * The extension name. * @param metadata * The metadata. */ public MetadataExtension(String name, Metadata metadata) { this.name = name; this.metadata = metadata; } /** * Returns the character set. * * @return the character set. */ public CharacterSet getCharacterSet() { return (CharacterSet) getMetadata(); } /** * Returns the encoding. * * @return the encoding. */ public Encoding getEncoding() { return (Encoding) getMetadata(); } /** * Returns the language. * * @return the language. */ public Language getLanguage() { return (Language) getMetadata(); } /** * Returns the media type. * * @return the media type. */ public MediaType getMediaType() { return (MediaType) getMetadata(); } /** * Returns the metadata. * * @return the metadata. */ public Metadata getMetadata() { return this.metadata; } /** * Returns the extension name. * * @return The extension name. */ public String getName() { return this.name; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/RangeInputStream.java0000664000175000017500000001420211757206346031121 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import org.restlet.data.Range; import org.restlet.representation.Representation; // [excludes gwt] /** * Filters an input stream to expose only a given range. * * @author Jerome Louvel */ public class RangeInputStream extends FilterInputStream { /** The current position. */ private volatile long position; /** The range to satisfy. */ private volatile Range range; /** The total size of the source stream. */ private volatile long totalSize; /** The start index inside the source stream. */ private final long startIndex; /** The end index inside the source stream. */ private final long endIndex; /** The range size available. */ private volatile int availableSize; /** * Constructs a stream exposing only a range of a given source stream. * * @param in * The source input stream. * @param totalSize * The total size of the source stream. * @param range * The range to satisfy. */ protected RangeInputStream(InputStream in, long totalSize, Range range) { super(in); this.range = range; this.position = 0; this.totalSize = totalSize; this.availableSize = (int) range.getSize(); if (totalSize == Representation.UNKNOWN_SIZE) { if (range.getIndex() == Range.INDEX_LAST) { if (range.getSize() == Range.SIZE_MAX) { // Read the whole stream this.startIndex = -1; this.endIndex = -1; } else { throw new IllegalArgumentException( "Can't determine the start and end index."); } } else { if (range.getSize() == Range.SIZE_MAX) { this.startIndex = range.getIndex(); this.endIndex = -1; } else { this.startIndex = range.getIndex(); this.endIndex = range.getIndex() + range.getSize() - 1; } } } else { if (range.getIndex() == Range.INDEX_LAST) { if (range.getSize() == Range.SIZE_MAX) { this.startIndex = -1; this.endIndex = -1; } else { this.startIndex = totalSize - range.getSize(); this.endIndex = -1; } } else { if (range.getSize() == Range.SIZE_MAX) { this.startIndex = range.getIndex(); this.endIndex = -1; } else { this.startIndex = range.getIndex(); this.endIndex = range.getIndex() + range.getSize() - 1; } } } } @Override public int available() throws IOException { return this.availableSize; } @Override public synchronized void mark(int readlimit) { if (range.getIndex() == Range.INDEX_LAST) { super.mark(readlimit + (int) (totalSize - range.getSize())); } else { super.mark(readlimit + (int) range.getIndex()); } } @Override public int read() throws IOException { int result = super.read(); while ((result != -1) && !this.range.isIncluded(position++, totalSize)) { result = super.read(); } if ((result != -1) && (this.availableSize > 0)) { this.availableSize--; } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { // Reach the start index. while (!(position >= startIndex)) { long skipped = skip(startIndex - position); if (skipped <= 0) { throw new IOException("Cannot skip ahead in FilterInputStream"); } position += skipped; } int result = -1; if (endIndex != -1) { // Read up until the end index if (position > endIndex) { // The end index is reached. result = -1; } else { // Take care to read the right number of bytes according to the // end index and the buffer size. result = super.read(b, off, ((position + len) > endIndex) ? (int) (endIndex - position + 1) : len); } } else { // Read normally up until the end of the stream. result = super.read(b, off, len); } if (result > 0) { // Move the cursor. position += result; } if ((result != -1) && (this.availableSize > 0)) { this.availableSize -= result; } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/application/EncodeRepresentation.java0000664000175000017500000002514711757206346032023 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.application; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.restlet.data.Disposition; import org.restlet.data.Encoding; import org.restlet.engine.io.BioUtils; import org.restlet.engine.io.NioUtils; import org.restlet.representation.Representation; import org.restlet.util.WrapperList; import org.restlet.util.WrapperRepresentation; // [excludes gwt] /** * Content that encodes a wrapped content. Allows to apply only one encoding. * * @author Jerome Louvel */ public class EncodeRepresentation extends WrapperRepresentation { /** * Returns the list of supported encodings. * * @return The list of supported encodings. */ public static List getSupportedEncodings() { return Arrays. asList(Encoding.GZIP, Encoding.DEFLATE, Encoding.ZIP, Encoding.IDENTITY); } /** Indicates if the encoding can happen. */ private volatile boolean canEncode; /** The encoding to apply. */ private volatile Encoding encoding; /** The applied encodings. */ private volatile List encodings; /** * Constructor. * * @param encoding * Encoder algorithm. * @param wrappedRepresentation * The wrapped representation. */ public EncodeRepresentation(Encoding encoding, Representation wrappedRepresentation) { super(wrappedRepresentation); this.canEncode = getSupportedEncodings().contains(encoding); this.encodings = null; this.encoding = encoding; } /** * Indicates if the encoding can happen. * * @return True if the encoding can happen. */ public boolean canEncode() { return this.canEncode; } /** * Returns the available size in bytes of the encoded representation if * known, UNKNOWN_SIZE (-1) otherwise. * * @return The available size in bytes if known, UNKNOWN_SIZE (-1) * otherwise. */ @Override public long getAvailableSize() { long result = UNKNOWN_SIZE; if (canEncode()) { if (this.encoding.equals(Encoding.IDENTITY)) { result = getWrappedRepresentation().getAvailableSize(); } } else { result = getWrappedRepresentation().getAvailableSize(); } return result; } /** * Returns a readable byte channel. If it is supported by a file a read-only * instance of FileChannel is returned. * * @return A readable byte channel. */ @Override public ReadableByteChannel getChannel() throws IOException { if (canEncode()) { return NioUtils.getChannel(getStream()); } return getWrappedRepresentation().getChannel(); } /** * Returns the applied encodings. * * @return The applied encodings. */ @Override public List getEncodings() { if (this.encodings == null) { this.encodings = new WrapperList() { @Override public boolean add(Encoding element) { if (element == null) { throw new IllegalArgumentException( "Cannot add a null encoding."); } return super.add(element); } @Override public void add(int index, Encoding element) { if (element == null) { throw new IllegalArgumentException( "Cannot add a null encoding."); } super.add(index, element); } @Override public boolean addAll(Collection elements) { boolean addNull = (elements == null); if (!addNull) { for (final Iterator iterator = elements .iterator(); !addNull && iterator.hasNext();) { addNull = (iterator.next() == null); } } if (addNull) { throw new IllegalArgumentException( "Cannot add a null encoding."); } return super.addAll(elements); } @Override public boolean addAll(int index, Collection elements) { boolean addNull = (elements == null); if (!addNull) { for (final Iterator iterator = elements .iterator(); !addNull && iterator.hasNext();) { addNull = (iterator.next() == null); } } if (addNull) { throw new IllegalArgumentException( "Cannot add a null encoding."); } return super.addAll(index, elements); } }; this.encodings.addAll(getWrappedRepresentation().getEncodings()); if (canEncode()) { this.encodings.add(this.encoding); } } return this.encodings; } /** * Returns the size in bytes of the encoded representation if known, * UNKNOWN_SIZE (-1) otherwise. * * @return The size in bytes if known, UNKNOWN_SIZE (-1) otherwise. */ @Override public long getSize() { long result = UNKNOWN_SIZE; if (canEncode()) { if (this.encoding.equals(Encoding.IDENTITY)) { result = getWrappedRepresentation().getSize(); } } else { result = getWrappedRepresentation().getSize(); } return result; } /** * Returns a stream with the representation's content. * * @return A stream with the representation's content. */ @Override public InputStream getStream() throws IOException { if (canEncode()) { return BioUtils.getStream(this); } return getWrappedRepresentation().getStream(); } /** * Converts the representation to a string value. Be careful when using this * method as the conversion of large content to a string fully stored in * memory can result in OutOfMemoryErrors being thrown. * * @return The representation as a string value. */ @Override public String getText() throws IOException { String result = null; if (canEncode()) { result = BioUtils.toString(getStream(), getCharacterSet()); } else { result = getWrappedRepresentation().getText(); } return result; } /** * Writes the representation to a byte stream. * * @param outputStream * The output stream. */ @Override public void write(OutputStream outputStream) throws IOException { if (canEncode()) { DeflaterOutputStream encoderOutputStream = null; if (this.encoding.equals(Encoding.GZIP)) { encoderOutputStream = new GZIPOutputStream(outputStream); } else if (this.encoding.equals(Encoding.DEFLATE)) { encoderOutputStream = new DeflaterOutputStream(outputStream); } else if (this.encoding.equals(Encoding.ZIP)) { final ZipOutputStream stream = new ZipOutputStream(outputStream); String name = "entry"; if (getWrappedRepresentation().getDisposition() != null) { name = getWrappedRepresentation() .getDisposition() .getParameters() .getFirstValue(Disposition.NAME_FILENAME, true, name); } stream.putNextEntry(new ZipEntry(name)); encoderOutputStream = stream; } else if (this.encoding.equals(Encoding.IDENTITY)) { // Encoder unnecessary for identity encoding } if (encoderOutputStream != null) { getWrappedRepresentation().write(encoderOutputStream); encoderOutputStream.flush(); encoderOutputStream.finish(); } else { getWrappedRepresentation().write(outputStream); } } else { getWrappedRepresentation().write(outputStream); } } /** * Writes the representation to a byte channel. * * @param writableChannel * A writable byte channel. */ @Override public void write(WritableByteChannel writableChannel) throws IOException { if (canEncode()) { write(NioUtils.getStream(writableChannel)); } else { getWrappedRepresentation().write(writableChannel); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/Engine.java0000664000175000017500000010365011757206354024600 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.engine.http.HttpProtocolHelper; import org.restlet.engine.http.WebDavProtocolHelper; import org.restlet.engine.io.IoUtils; import org.restlet.engine.log.LoggerFacade; /** * Engine supporting the Restlet API. The engine acts as a registry of various * {@link Helper} types: {@link org.restlet.engine.security.AuthenticatorHelper} * , {@link ClientHelper}, {@link org.restlet.engine.converter.ConverterHelper} * and {@link ServerHelper} classes.
    *
    * Note that by default the JULI logging mechanism is used but it is possible to * replace it by providing an alternate {@link LoggerFacade} implementation. For * this, just pass a system property named * "org.restlet.engine.loggerFacadeClass" with the qualified class name as a * value. * * @author Jerome Louvel */ public class Engine { public static final String DESCRIPTOR = "META-INF/services"; public static final String DESCRIPTOR_AUTHENTICATOR = "org.restlet.engine.security.AuthenticatorHelper"; public static final String DESCRIPTOR_AUTHENTICATOR_PATH = DESCRIPTOR + "/" + DESCRIPTOR_AUTHENTICATOR; public static final String DESCRIPTOR_CLIENT = "org.restlet.engine.ClientHelper"; public static final String DESCRIPTOR_CLIENT_PATH = DESCRIPTOR + "/" + DESCRIPTOR_CLIENT; public static final String DESCRIPTOR_CONVERTER = "org.restlet.engine.converter.ConverterHelper"; public static final String DESCRIPTOR_CONVERTER_PATH = DESCRIPTOR + "/" + DESCRIPTOR_CONVERTER; public static final String DESCRIPTOR_PROTOCOL = "org.restlet.engine.ProtocolHelper"; public static final String DESCRIPTOR_PROTOCOL_PATH = DESCRIPTOR + "/" + DESCRIPTOR_PROTOCOL; public static final String DESCRIPTOR_SERVER = "org.restlet.engine.ServerHelper"; public static final String DESCRIPTOR_SERVER_PATH = DESCRIPTOR + "/" + DESCRIPTOR_SERVER; // [enddef] /** The registered engine. */ private static volatile Engine instance = null; /** Major version number. */ public static final String MAJOR_NUMBER = "2"; /** Minor version number. */ public static final String MINOR_NUMBER = "0"; /** Release number. */ public static final String RELEASE_NUMBER = ".14"; /** Complete version. */ public static final String VERSION = MAJOR_NUMBER + '.' + MINOR_NUMBER + RELEASE_NUMBER; /** Complete version header. */ public static final String VERSION_HEADER = "Restlet-Framework/" + VERSION; /** * Clears the thread local variables set by the Restlet API and engine. */ public static void clearThreadLocalVariables() { Response.setCurrent(null); Context.setCurrent(null); org.restlet.routing.VirtualHost.setCurrent(null); org.restlet.Application.setCurrent(null); } /** * Returns an anonymous logger. By default it calls * {@link #getLogger(String)} with a "" name. * * @return The logger. */ public static Logger getAnonymousLogger() { return getInstance().getLoggerFacade().getAnonymousLogger(); } /** * Returns the registered Restlet engine. * * @return The registered Restlet engine. */ public static synchronized Engine getInstance() { Engine result = instance; if (result == null) { result = register(); } return result; } /** * Returns a logger based on the class name of the given object. * * @param clazz * The parent class. * @return The logger. */ public static Logger getLogger(Class clazz) { return getInstance().getLoggerFacade().getLogger(clazz); } /** * Returns a logger based on the class name of the given object. * * @param clazz * The parent class. * @param defaultLoggerName * The default logger name to use if no one can be inferred from * the class. * @return The logger. */ public static Logger getLogger(Class clazz, String defaultLoggerName) { return getInstance().getLoggerFacade().getLogger(clazz, defaultLoggerName); } /** * Returns a logger based on the class name of the given object. * * @param object * The parent object. * @param defaultLoggerName * The default logger name to use if no one can be inferred from * the object class. * @return The logger. */ public static Logger getLogger(Object object, String defaultLoggerName) { return getInstance().getLoggerFacade().getLogger(object, defaultLoggerName); } /** * Returns a logger based on the given logger name. * * @param loggerName * The logger name. * @return The logger. */ public static Logger getLogger(String loggerName) { return getInstance().getLoggerFacade().getLogger(loggerName); } /** * Returns the classloader resource for a given name/path. * * @param name * The name/path to lookup. * @return The resource URL. */ public static java.net.URL getResource(String name) { return getInstance().getClassLoader().getResource(name); } /** * Returns the class object for the given name using the engine classloader. * * @param className * The class name to lookup. * @return The class object or null if the class was not found. * @see #getClassLoader() */ public static Class loadClass(String className) throws ClassNotFoundException { return getInstance().getClassLoader().loadClass(className); } /** * Registers a new Restlet Engine. * * @return The registered engine. */ public static synchronized Engine register() { return register(true); } /** * Registers a new Restlet Engine. * * @param discoverPlugins * True if plug-ins should be automatically discovered. * @return The registered engine. */ public static synchronized Engine register(boolean discoverPlugins) { Engine result = new Engine(discoverPlugins); org.restlet.engine.Engine.setInstance(result); return result; } /** * Sets the registered Restlet engine. * * @param engine * The registered Restlet engine. */ public static synchronized void setInstance(Engine engine) { instance = engine; } /** Class loader to use for dynamic class loading. */ private volatile ClassLoader classLoader; /** The logger facade to use. */ private LoggerFacade loggerFacade; /** List of available authenticator helpers. */ private final List registeredAuthenticators; /** List of available client connectors. */ private final List> registeredClients; /** List of available converter helpers. */ private final List registeredConverters; /** List of available protocol helpers. */ private final List registeredProtocols; /** List of available server connectors. */ private final List> registeredServers; /** User class loader to use for dynamic class loading. */ private volatile ClassLoader userClassLoader; /** * Constructor that will automatically attempt to discover connectors. */ public Engine() { this(true); } /** * Constructor. * * @param discoverHelpers * True if helpers should be automatically discovered. */ public Engine(boolean discoverHelpers) { // Prevent engine initialization code from recreating other engines setInstance(this); // Instantiate the logger facade if (Edition.CURRENT == Edition.GWT) { this.loggerFacade = new LoggerFacade(); } else { this.classLoader = createClassLoader(); this.userClassLoader = null; String loggerFacadeClass = System.getProperty( "org.restlet.engine.loggerFacadeClass", "org.restlet.engine.log.LoggerFacade"); try { this.loggerFacade = (LoggerFacade) getClassLoader().loadClass( loggerFacadeClass).newInstance(); } catch (Exception e) { this.loggerFacade = new LoggerFacade(); this.loggerFacade.getLogger("org.restlet").log(Level.WARNING, "Unable to register the logger facade", e); } } this.registeredClients = new CopyOnWriteArrayList>(); this.registeredProtocols = new CopyOnWriteArrayList(); this.registeredServers = new CopyOnWriteArrayList>(); this.registeredAuthenticators = new CopyOnWriteArrayList(); this.registeredConverters = new CopyOnWriteArrayList(); if (discoverHelpers) { try { discoverConnectors(); discoverProtocols(); discoverAuthenticators(); discoverConverters(); } catch (IOException e) { Context.getCurrentLogger() .log(Level.WARNING, "An error occured while discovering the engine helpers.", e); } } } /** * Creates a new class loader. By default, it returns an instance of * {@link org.restlet.engine.util.EngineClassLoader}. * * @return A new class loader. */ protected ClassLoader createClassLoader() { return new org.restlet.engine.util.EngineClassLoader(this); } /** * Creates a new helper for a given client connector. * * @param client * The client to help. * @param helperClass * Optional helper class name. * @return The new helper. */ @SuppressWarnings("unchecked") public ConnectorHelper createHelper(Client client, String helperClass) { ConnectorHelper result = null; if (client.getProtocols().size() > 0) { ConnectorHelper connector = null; for (final Iterator> iter = getRegisteredClients() .iterator(); (result == null) && iter.hasNext();) { connector = iter.next(); if (connector.getProtocols().containsAll(client.getProtocols())) { if ((helperClass == null) || connector.getClass().getCanonicalName() .equals(helperClass)) { try { result = connector.getClass() .getConstructor(Client.class) .newInstance(client); } catch (Exception e) { Context.getCurrentLogger() .log(Level.SEVERE, "Exception during the instantiation of the client connector.", e); } } } } if (result == null) { // Couldn't find a matching connector StringBuilder sb = new StringBuilder(); sb.append("No available client connector supports the required protocols: "); for (Protocol p : client.getProtocols()) { sb.append("'").append(p.getName()).append("' "); } sb.append(". Please add the JAR of a matching connector to your classpath."); if (Edition.CURRENT == Edition.ANDROID) { sb.append(" Then, register this connector helper manually."); } Context.getCurrentLogger().log(Level.WARNING, sb.toString()); } } return result; } /** * Creates a new helper for a given server connector. * * @param server * The server to help. * @param helperClass * Optional helper class name. * @return The new helper. */ @SuppressWarnings("unchecked") public ConnectorHelper createHelper( org.restlet.Server server, String helperClass) { ConnectorHelper result = null; if (server.getProtocols().size() > 0) { ConnectorHelper connector = null; for (final Iterator> iter = getRegisteredServers() .iterator(); (result == null) && iter.hasNext();) { connector = iter.next(); if ((helperClass == null) || connector.getClass().getCanonicalName() .equals(helperClass)) { if (connector.getProtocols().containsAll( server.getProtocols())) { try { result = connector.getClass() .getConstructor(org.restlet.Server.class) .newInstance(server); } catch (Exception e) { Context.getCurrentLogger() .log(Level.SEVERE, "Exception while instantiation the server connector.", e); } } } } if (result == null) { // Couldn't find a matching connector final StringBuilder sb = new StringBuilder(); sb.append("No available server connector supports the required protocols: "); for (final Protocol p : server.getProtocols()) { sb.append("'").append(p.getName()).append("' "); } sb.append(". Please add the JAR of a matching connector to your classpath."); if (Edition.CURRENT == Edition.ANDROID) { sb.append(" Then, register this connector helper manually."); } Context.getCurrentLogger().log(Level.WARNING, sb.toString()); } } return result; } /** * Discovers the authenticator helpers and register the default helpers. * * @throws IOException */ private void discoverAuthenticators() throws IOException { registerHelpers(DESCRIPTOR_AUTHENTICATOR_PATH, getRegisteredAuthenticators(), null); registerDefaultAuthentications(); } /** * Discovers the server and client connectors and register the default * connectors. * * @throws IOException */ private void discoverConnectors() throws IOException { registerHelpers(DESCRIPTOR_CLIENT_PATH, getRegisteredClients(), Client.class); registerHelpers(DESCRIPTOR_SERVER_PATH, getRegisteredServers(), org.restlet.Server.class); registerDefaultConnectors(); } /** * Discovers the converter helpers and register the default helpers. * * @throws IOException */ private void discoverConverters() throws IOException { registerHelpers(DESCRIPTOR_CONVERTER_PATH, getRegisteredConverters(), null); registerDefaultConverters(); } /** * Discovers the protocol helpers and register the default helpers. * * @throws IOException */ private void discoverProtocols() throws IOException { registerHelpers(DESCRIPTOR_PROTOCOL_PATH, getRegisteredProtocols(), null); registerDefaultProtocols(); } /** * Finds the converter helper supporting the given conversion. * * @return The converter helper or null. */ public org.restlet.engine.converter.ConverterHelper findHelper() { return null; } /** * Finds the authenticator helper supporting the given scheme. * * @param challengeScheme * The challenge scheme to match. * @param clientSide * Indicates if client side support is required. * @param serverSide * Indicates if server side support is required. * @return The authenticator helper or null. */ public org.restlet.engine.security.AuthenticatorHelper findHelper( ChallengeScheme challengeScheme, boolean clientSide, boolean serverSide) { org.restlet.engine.security.AuthenticatorHelper result = null; final List helpers = getRegisteredAuthenticators(); org.restlet.engine.security.AuthenticatorHelper current; for (int i = 0; (result == null) && (i < helpers.size()); i++) { current = helpers.get(i); if (current.getChallengeScheme().equals(challengeScheme) && ((clientSide && current.isClientSide()) || !clientSide) && ((serverSide && current.isServerSide()) || !serverSide)) { result = helpers.get(i); } } return result; } /** * Returns the class loader. It uses the delegation model with the Engine * class's class loader as a parent. If this parent doesn't find a class or * resource, it then tries the user class loader (via * {@link #getUserClassLoader()} and finally the * {@link Thread#getContextClassLoader()}. * * @return The engine class loader. * @see org.restlet.engine.util.EngineClassLoader */ public ClassLoader getClassLoader() { return classLoader; } /** * Returns the logger facade to use. * * @return The logger facade to use. */ public LoggerFacade getLoggerFacade() { return loggerFacade; } /** * Parses a line to extract the provider class name. * * @param line * The line to parse. * @return The provider's class name or an empty string. */ private String getProviderClassName(String line) { final int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } return line.trim(); } /** * Returns the list of available authentication helpers. * * @return The list of available authentication helpers. */ public List getRegisteredAuthenticators() { return this.registeredAuthenticators; } /** * Returns the list of available client connectors. * * @return The list of available client connectors. */ public List> getRegisteredClients() { return this.registeredClients; } /** * Returns the list of available converters. * * @return The list of available converters. */ public List getRegisteredConverters() { return registeredConverters; } /** * Returns the list of available protocol connectors. * * @return The list of available protocol connectors. */ public List getRegisteredProtocols() { return this.registeredProtocols; } /** * Returns the list of available server connectors. * * @return The list of available server connectors. */ public List> getRegisteredServers() { return this.registeredServers; } /** * Returns the class loader specified by the user and that should be used in * priority. * * @return The user class loader */ public ClassLoader getUserClassLoader() { return userClassLoader; } /** * Registers the default authentication helpers. */ public void registerDefaultAuthentications() { getRegisteredAuthenticators().add( new org.restlet.engine.http.security.HttpBasicHelper()); getRegisteredAuthenticators().add( new org.restlet.engine.security.SmtpPlainHelper()); } /** * Registers the default client and server connectors. */ public void registerDefaultConnectors() { getRegisteredClients().add( new org.restlet.engine.http.connector.HttpClientHelper(null)); getRegisteredClients().add( new org.restlet.engine.local.ClapClientHelper(null)); getRegisteredClients().add( new org.restlet.engine.local.FileClientHelper(null)); getRegisteredClients().add( new org.restlet.engine.local.ZipClientHelper(null)); getRegisteredClients().add( new org.restlet.engine.riap.RiapClientHelper(null)); getRegisteredServers().add( new org.restlet.engine.riap.RiapServerHelper(null)); getRegisteredServers().add( new org.restlet.engine.http.connector.HttpServerHelper(null)); } /** * Registers the default converters. */ public void registerDefaultConverters() { getRegisteredConverters().add( new org.restlet.engine.converter.DefaultConverter()); } /** * Registers the default protocols. */ public void registerDefaultProtocols() { getRegisteredProtocols().add(new HttpProtocolHelper()); getRegisteredProtocols().add(new WebDavProtocolHelper()); } /** * Registers a helper. * * @param classLoader * The classloader to use. * @param provider * Bynary name of the helper's class. * @param helpers * The list of helpers to update. * @param constructorClass * The constructor parameter class to look for. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void registerHelper(ClassLoader classLoader, String provider, List helpers, Class constructorClass) { if ((provider != null) && (!provider.equals(""))) { // Instantiate the factory try { Class providerClass = classLoader.loadClass(provider); if (constructorClass == null) { helpers.add(providerClass.newInstance()); } else { helpers.add(providerClass.getConstructor(constructorClass) .newInstance(constructorClass.cast(null))); } } catch (Throwable t) { Context.getCurrentLogger().log(Level.INFO, "Unable to register the helper " + provider, t); } } } /** * Registers a helper. * * @param classLoader * The classloader to use. * @param configUrl * Configuration URL to parse * @param helpers * The list of helpers to update. * @param constructorClass * The constructor parameter class to look for. */ public void registerHelpers(ClassLoader classLoader, java.net.URL configUrl, List helpers, Class constructorClass) { try { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( configUrl.openStream(), "utf-8"), IoUtils.getBufferSize()); String line = reader.readLine(); while (line != null) { registerHelper(classLoader, getProviderClassName(line), helpers, constructorClass); line = reader.readLine(); } } catch (IOException e) { Context.getCurrentLogger().log( Level.SEVERE, "Unable to read the provider descriptor: " + configUrl.toString()); } finally { if (reader != null) { reader.close(); } } } catch (IOException ioe) { Context.getCurrentLogger().log(Level.SEVERE, "Exception while detecting the helpers.", ioe); } } /** * Registers a list of helpers. * * @param descriptorPath * Classpath to the descriptor file. * @param helpers * The list of helpers to update. * @param constructorClass * The constructor parameter class to look for. * @throws IOException */ public void registerHelpers(String descriptorPath, List helpers, Class constructorClass) throws IOException { final ClassLoader classLoader = getClassLoader(); Enumeration configUrls = classLoader .getResources(descriptorPath); if (configUrls != null) { for (final Enumeration configEnum = configUrls; configEnum .hasMoreElements();) { registerHelpers(classLoader, configEnum.nextElement(), helpers, constructorClass); } } } /** * Registers a factory that is used by the URL class to create the * {@link java.net.URLConnection} instances when the * {@link java.net.URL#openConnection()} or * {@link java.net.URL#openStream()} methods are invoked. *

    * The implementation is based on the client dispatcher of the current * context, as provided by {@link Context#getCurrent()} method. */ public void registerUrlFactory() { // Set up an java.net.URLStreamHandlerFactory for // proper creation of java.net.URL instances java.net.URL .setURLStreamHandlerFactory(new java.net.URLStreamHandlerFactory() { public java.net.URLStreamHandler createURLStreamHandler( String protocol) { final java.net.URLStreamHandler result = new java.net.URLStreamHandler() { @Override protected java.net.URLConnection openConnection( java.net.URL url) throws IOException { return new java.net.URLConnection(url) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { InputStream result = null; // Retrieve the current context final Context context = Context .getCurrent(); if (context != null) { final Response response = context .getClientDispatcher() .handle(new Request( Method.GET, this.url.toString())); if (response.getStatus() .isSuccess()) { result = response.getEntity() .getStream(); } } return result; } }; } }; return result; } }); } /** * Sets the engine class loader. * * @param newClassLoader * The new user class loader to use. */ public void setClassLoader(ClassLoader newClassLoader) { this.classLoader = newClassLoader; } /** * Sets the logger facade to use. * * @param loggerFacade * The logger facade to use. */ public void setLoggerFacade(LoggerFacade loggerFacade) { this.loggerFacade = loggerFacade; } /** * Sets the list of available authentication helpers. * * @param registeredAuthenticators * The list of available authentication helpers. */ public void setRegisteredAuthenticators( List registeredAuthenticators) { synchronized (this.registeredAuthenticators) { if (registeredAuthenticators != this.registeredAuthenticators) { this.registeredAuthenticators.clear(); if (registeredAuthenticators != null) { this.registeredAuthenticators .addAll(registeredAuthenticators); } } } } /** * Sets the list of available client helpers. * * @param registeredClients * The list of available client helpers. */ public void setRegisteredClients( List> registeredClients) { synchronized (this.registeredClients) { if (registeredClients != this.registeredClients) { this.registeredClients.clear(); if (registeredClients != null) { this.registeredClients.addAll(registeredClients); } } } } /** * Sets the list of available converter helpers. * * @param registeredConverters * The list of available converter helpers. */ public void setRegisteredConverters( List registeredConverters) { synchronized (this.registeredConverters) { if (registeredConverters != this.registeredConverters) { this.registeredConverters.clear(); if (registeredConverters != null) { this.registeredConverters.addAll(registeredConverters); } } } } /** * Sets the list of available protocol helpers. * * @param registeredProtocols * The list of available protocol helpers. */ public void setRegisteredProtocols(List registeredProtocols) { synchronized (this.registeredProtocols) { if (registeredProtocols != this.registeredProtocols) { this.registeredProtocols.clear(); if (registeredProtocols != null) { this.registeredProtocols.addAll(registeredProtocols); } } } } /** * Sets the list of available server helpers. * * @param registeredServers * The list of available server helpers. */ public void setRegisteredServers( List> registeredServers) { synchronized (this.registeredServers) { if (registeredServers != this.registeredServers) { this.registeredServers.clear(); if (registeredServers != null) { this.registeredServers.addAll(registeredServers); } } } } /** * Sets the user class loader that should used in priority. * * @param newClassLoader * The new user class loader to use. */ public void setUserClassLoader(ClassLoader newClassLoader) { this.userClassLoader = newClassLoader; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/ConnectorHelper.java0000664000175000017500000000613011757206346026461 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Connector; import org.restlet.Context; import org.restlet.data.Protocol; /** * Base connector helper. * * @author Jerome Louvel */ public abstract class ConnectorHelper extends RestletHelper { /** * Returns the connector service associated to a request. * * @return The connector service associated to a request. */ public static org.restlet.service.ConnectorService getConnectorService() { org.restlet.service.ConnectorService result = null; org.restlet.Application application = org.restlet.Application .getCurrent(); if (application != null) { result = application.getConnectorService(); } else { result = new org.restlet.service.ConnectorService(); } return result; } /** The protocols simultaneously supported. */ private final List protocols; /** * Constructor. */ public ConnectorHelper(T connector) { super(connector); this.protocols = new CopyOnWriteArrayList(); } /** * Returns the helped Restlet context. * * @return The helped Restlet context. */ @Override public Context getContext() { if (Edition.CURRENT == Edition.GWT) { return null; } return super.getContext(); } /** * Returns the protocols simultaneously supported. * * @return The protocols simultaneously supported. */ public List getProtocols() { return this.protocols; } @Override public void start() throws Exception { } @Override public void stop() throws Exception { } @Override public void update() throws Exception { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/riap/0000775000175000017500000000000011757206350023452 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/riap/RiapClientHelper.java0000664000175000017500000000670011757206346027517 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.riap; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.LocalReference; import org.restlet.data.Protocol; import org.restlet.engine.ClientHelper; /** * Client connector for RIAP calls. Only the "component" authority is supported. * * @author Thierry Boileau * @see Protocol#RIAP */ public class RiapClientHelper extends ClientHelper { /** * Constructor. * * @param client * The client to help. */ public RiapClientHelper(Client client) { super(client); getProtocols().add(Protocol.RIAP); } /** * Handles a call. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { final String scheme = request.getResourceRef().getScheme(); if (Protocol.RIAP.getSchemeName().equalsIgnoreCase(scheme)) { // Support only the "component" authority LocalReference ref = new LocalReference(request.getResourceRef()); if (ref.getRiapAuthorityType() == LocalReference.RIAP_COMPONENT) { if (RiapServerHelper.instance != null && RiapServerHelper.instance.getContext() != null && RiapServerHelper.instance.getContext() .getClientDispatcher() != null) { RiapServerHelper.instance.getContext() .getClientDispatcher().handle(request, response); } else { super.handle(request, response); } } else { throw new IllegalArgumentException( "Authority \"" + ref.getAuthority() + "\" not supported by the connector. Only \"component\" is supported."); } } else { throw new IllegalArgumentException( "Protocol \"" + scheme + "\" not supported by the connector. Only RIAP is supported."); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/riap/RiapServerHelper.java0000664000175000017500000000422111757206346027543 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.riap; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.ServerHelper; /** * Server connector handling RIAP calls. By design, there is only one instance * by JVM. * * @author Thierry Boileau */ public class RiapServerHelper extends ServerHelper { /** The unique registered helper. */ public static RiapServerHelper instance = null; /** * Constructor. * * @param server * The server to help. */ public RiapServerHelper(Server server) { super(server); getProtocols().add(Protocol.RIAP); // Lazy initialization with double-check. if (server != null && RiapServerHelper.instance == null) { synchronized (this.getClass()) { if (RiapServerHelper.instance == null) { RiapServerHelper.instance = this; } } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/riap/package.html0000664000175000017500000000016711757206350025737 0ustar jamespagejamespage Supports RIAP (Restlet Internal Access Protocol) connectors.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/Edition.java0000664000175000017500000000567211757206354024773 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; /** * Enumeration of Restlet editions. * * @author Jerome Louvel */ public enum Edition { /** Android mobile OS, Google App Engine, Google Web Toolkit, JEE, JSE. */ ANDROID, GAE, GWT, JEE, JSE; /** The current engine edition. */ public static final Edition CURRENT = Edition.JSE; /** * Returns the full size name of the edition. * * @return The full size of the edition. */ public String getFullName() { switch (this) { case ANDROID: return "Android"; case GAE: return "Google App Engine"; case GWT: return "Google Web Toolkit"; case JEE: return "Java Enterprise Edition"; case JSE: return "Java Standard Edition"; } return null; } /** * Returns the medium size name of the edition. * * @return The medium size name of the edition. */ public String getMediumName() { switch (this) { case ANDROID: return "Android"; case GAE: return "GAE"; case GWT: return "GWT"; case JEE: return "Java EE"; case JSE: return "Java SE"; } return null; } /** * Returns the short size name of the edition. * * @return The short size name of the edition. */ public String getShortName() { switch (this) { case ANDROID: return "Android"; case GAE: return "GAE"; case GWT: return "GWT"; case JEE: return "JEE"; case JSE: return "JSE"; } return null; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/ServerHelper.java0000664000175000017500000000601711757206346026001 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import java.net.ServerSocket; import org.restlet.Request; import org.restlet.Response; import org.restlet.Server; /** * Server connector helper. * * @author Jerome Louvel */ public class ServerHelper extends ConnectorHelper { /** * Constructor. * * @param server * The client to help. */ public ServerHelper(Server server) { super(server); // Clear the ephemeral port getAttributes().put("ephemeralPort", -1); } /** * Handles a call by invoking the helped Server's * {@link Server#handle(Request, Response)} method. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { super.handle(request, response); getHelped().handle(request, response); } /** * Sets the ephemeral port in the attributes map if necessary. * * @param localPort * The ephemeral local port. */ public void setEphemeralPort(int localPort) { // If an ephemeral port is used, make sure we update the attribute for // the API if (getHelped().getPort() == 0) { getAttributes().put("ephemeralPort", localPort); } } /** * Sets the ephemeral port in the attributes map if necessary. * * @param socket * The bound server socket. */ public void setEphemeralPort(ServerSocket socket) { setEphemeralPort(socket.getLocalPort()); } @Override public synchronized void stop() throws Exception { super.stop(); // Clear the ephemeral port getAttributes().put("ephemeralPort", -1); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/TemplateDispatcher.java0000664000175000017500000001115011757206346027147 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Template; /** * Base call dispatcher capable of resolving target resource URI templates. * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state as member variables. * * @author Jerome Louvel */ public class TemplateDispatcher extends Client { /** The context. */ private volatile Context context; /** * Constructor. * * @param context * The context. */ public TemplateDispatcher(Context context) { super(null, (Protocol) null); this.context = context; } /** * Actually handles the call. Since this method only sets the request's * original reference ({@link Request#getOriginalRef()} with the the * targeted one, it must be overridden by subclasses. * * * @param request * The request to handle. * @param response * The response to update. */ protected void doHandle(Request request, Response response) { request.setOriginalRef(request.getResourceRef().getTargetRef()); } /** * Returns the context. Override default behavior from {@link Restlet}. * * @return The context. */ @Override public Context getContext() { return context; } /** * Handles the call after resolving any URI template on the request's target * resource reference. * * @param request * The request to handle. * @param response * The response to update. */ public void handle(Request request, Response response) { // Associate the response to the current thread Response.setCurrent(response); Protocol protocol = request.getProtocol(); if (protocol == null) { throw new UnsupportedOperationException( "Unable to determine the protocol to use for this call."); } String targetUri = request.getResourceRef().toString(true, false); if (targetUri.contains("{")) { // Template URI detected, create the template Template template = new Template(targetUri); // Set the formatted target URI request.setResourceRef(template.format(request, response)); } // Actually handle the formatted URI doHandle(request, response); // If the response entity comes back with no identifier, // automatically set the request's resource reference's identifier. // This is very useful to resolve relative references in XSLT for // example. if ((response.getEntity() != null) && (response.getEntity().getLocationRef() == null)) { response.getEntity().setLocationRef( request.getResourceRef().getTargetRef().toString()); } } /** * Sets the context. Override default behavior from {@link Restlet}. * * @param context * The context to set. */ @Override public void setContext(Context context) { this.context = context; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/resource/0000775000175000017500000000000011757206350024346 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/resource/VariantInfo.java0000664000175000017500000000717711757206346027452 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.resource; import org.restlet.data.MediaType; import org.restlet.representation.Variant; // [excludes gwt] /** * Variant that is declared by an annotated Java method. * * @author Jerome Louvel */ public class VariantInfo extends Variant { /** The optional annotation descriptor. */ private final AnnotationInfo annotationInfo; /** * Constructor. * * @param mediaType * The media type. */ public VariantInfo(MediaType mediaType) { this(mediaType, null); } /** * Indicates if the current variant is equal to the given variant. * * @param other * The other variant. * @return True if the current variant includes the other. */ @Override public boolean equals(Object other) { boolean result = super.equals(other) && (other instanceof VariantInfo); if (result && (other != this)) { VariantInfo otherVariant = (VariantInfo) other; // Compare the annotation info if (result) { result = ((getAnnotationInfo() == null) && (otherVariant.getAnnotationInfo() == null) || (getAnnotationInfo() != null) && getAnnotationInfo().equals( otherVariant.getAnnotationInfo())); } } return result; } /** * Constructor. * * @param mediaType * The media type. * @param annotationInfo * The optional annotation descriptor. */ public VariantInfo(MediaType mediaType, AnnotationInfo annotationInfo) { super(mediaType); this.annotationInfo = annotationInfo; } /** * Constructor. * * @param variant * The variant to enrich. * @param annotationInfo * The optional annotation descriptor. */ public VariantInfo(Variant variant, AnnotationInfo annotationInfo) { super(variant.getMediaType()); setCharacterSet(variant.getCharacterSet()); setEncodings(variant.getEncodings()); setLanguages(variant.getLanguages()); this.annotationInfo = annotationInfo; } /** * Returns the optional annotation descriptor. * * @return The optional annotation descriptor. */ public AnnotationInfo getAnnotationInfo() { return annotationInfo; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/resource/AnnotationInfo.java0000664000175000017500000004175011757206346030153 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.resource; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.service.MetadataService; // [excludes gwt] /** * Descriptor for method annotations. * * @author Jerome Louvel */ public class AnnotationInfo { /** * Returns the actual type for a given generic type name. * * @param currentClass * The current class to walk up. * @param genericTypeName * The generic type name to resolve. * @return The actual type. */ private static Class getJavaActualType(Class currentClass, String genericTypeName) { Class result = null; // Lookup in the super class result = getJavaActualType(currentClass.getGenericSuperclass(), genericTypeName); if (result == null) { // Lookup in the implemented interfaces Type[] interfaceTypes = currentClass.getGenericInterfaces(); for (int i = 0; (result == null) && (i < interfaceTypes.length); i++) { result = getJavaActualType(interfaceTypes[i], genericTypeName); } } return result; } /** * Returns the actual type for a given generic type name. * * @param currentType * The current type to start with. * @param genericTypeName * The generic type name to resolve. * @return The actual type. */ private static Class getJavaActualType(Type currentType, String genericTypeName) { Class result = null; if (currentType != null) { if (currentType instanceof Class) { // Look in the generic super class or the implemented interfaces result = getJavaActualType((Class) currentType, genericTypeName); } else if (currentType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) currentType; Class rawType = (Class) parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType .getActualTypeArguments(); TypeVariable[] typeParameters = rawType.getTypeParameters(); for (int i = 0; (result == null) && (i < actualTypeArguments.length); i++) { if (genericTypeName.equals(typeParameters[i].getName())) { result = getTypeClass(actualTypeArguments[i]); } } } } return result; } /** * Returns the underlying class for a type or null. * * @param type * The generic type. * @return The underlying class */ private static Class getTypeClass(Type type) { Class result = null; if (type instanceof Class) { result = (Class) type; } else if (type instanceof ParameterizedType) { result = getTypeClass(((ParameterizedType) type).getRawType()); } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type) .getGenericComponentType(); Class componentClass = getTypeClass(componentType); if (componentClass != null) { result = Array.newInstance(componentClass, 0).getClass(); } } return result; } /** The annotated Java method. */ private final java.lang.reflect.Method javaMethod; /** The class that hosts the annotated Java method. */ private final Class resourceClass; /** The matching Restlet method. */ private final Method restletMethod; /** The annotation value. */ private final String value; /** * Constructor. * * @param resourceClass * The class or interface that hosts the annotated Java method. * @param restletMethod * The matching Restlet method. * @param javaMethod * The annotated Java method. * @param value * The annotation value. */ public AnnotationInfo(Class resourceClass, Method restletMethod, java.lang.reflect.Method javaMethod, String value) { super(); this.resourceClass = resourceClass; this.restletMethod = restletMethod; this.javaMethod = javaMethod; this.value = value; } /** * Indicates if the current variant is equal to the given variant. * * @param other * The other variant. * @return True if the current variant includes the other. */ @Override public boolean equals(Object other) { boolean result = (other instanceof AnnotationInfo); if (result && (other != this)) { AnnotationInfo otherAnnotation = (AnnotationInfo) other; // Compare the method if (result) { result = ((getJavaMethod() == null) && (otherAnnotation.getJavaMethod() == null) || (getJavaMethod() != null) && getJavaMethod().equals( otherAnnotation.getJavaMethod())); } // Compare the resource interface if (result) { result = ((getResourceClass() == null) && (otherAnnotation.getResourceClass() == null) || (getResourceClass() != null) && getResourceClass().equals( otherAnnotation.getResourceClass())); } // Compare the Restlet method if (result) { result = ((getRestletMethod() == null) && (otherAnnotation.getRestletMethod() == null) || (getRestletMethod() != null) && getRestletMethod().equals( otherAnnotation.getRestletMethod())); } // Compare the value if (result) { result = ((getValue() == null) && (otherAnnotation.getValue() == null) || (getValue() != null) && getValue().equals(otherAnnotation.getValue())); } } return result; } /** * Returns the input part of the annotation value. * * @return The input part of the annotation value. */ public String getInputValue() { String result = getValue(); if (result != null) { int colonIndex = result.indexOf(':'); if (colonIndex != -1) { result = result.substring(0, colonIndex); } } return result; } /** * Returns the actual type for a given generic type. * * @param initialType * The initial type, which may be generic. * @param genericType * The generic type information if any. * @return The actual type. */ private Class getJavaActualType(Class initialType, Type genericType) { Class result = initialType; try { if (genericType instanceof TypeVariable) { TypeVariable genericTypeVariable = (TypeVariable) genericType; String genericTypeName = genericTypeVariable.getName(); result = getJavaActualType(getResourceClass(), genericTypeName); } } catch (Throwable t) { t.printStackTrace(); } return result; } /** * Returns the generic type for the given input parameter. * * @param index * The input parameter index. * * @return The generic type. */ public Class getJavaInputType(int index) { return getJavaActualType(getJavaMethod().getParameterTypes()[index], getJavaMethod().getGenericParameterTypes()[index]); } /** * Returns the input types of the Java method. * * @return The input types of the Java method. */ public Class[] getJavaInputTypes() { int count = getJavaMethod().getParameterTypes().length; Class[] classes = new Class[count]; for (int i = 0; i < count; i++) { classes[i] = getJavaInputType(i); } return classes; } /** * Returns the annotated Java method. * * @return The annotated Java method. */ public java.lang.reflect.Method getJavaMethod() { return javaMethod; } /** * Returns the output type of the Java method. * * @return The output type of the Java method. */ public Class getJavaOutputType() { return getJavaActualType(getJavaMethod().getReturnType(), getJavaMethod().getGenericReturnType()); } /** * Returns the output part of the annotation value. * * @return The output part of the annotation value. */ public String getOutputValue() { String result = getValue(); if (result != null) { int colonIndex = result.indexOf(':'); if (colonIndex != -1) { result = result.substring(colonIndex + 1); } } return result; } /** * Returns a list of request variants based on the annotation value. * * @param metadataService * The metadata service to use. * @return A list of request variants. */ @SuppressWarnings("unchecked") public List getRequestVariants(MetadataService metadataService, org.restlet.service.ConverterService converterService) { List result = null; Class[] classes = getJavaInputTypes(); if (classes != null && classes.length >= 1) { String value = getInputValue(); if (value != null) { String[] extensions = value.split("\\|"); if (extensions != null) { for (String extension : extensions) { List mediaTypes = metadataService .getAllMediaTypes(extension); if (mediaTypes != null) { if (result == null) { result = new ArrayList(); } for (MediaType mediaType : mediaTypes) { result.add(new Variant(mediaType)); } } } } } if (result == null) { Class inputClass = classes[0]; result = (List) converterService.getVariants( inputClass, null); } } return result; } /** * Returns the resource interface value. * * @return The resource interface value. */ public Class getResourceClass() { return resourceClass; } /** * Returns a list of response variants based on the annotation value. * * @param metadataService * The metadata service to use. * @param converterService * The converter service to use. * @return A list of response variants. */ @SuppressWarnings("unchecked") public List getResponseVariants(MetadataService metadataService, org.restlet.service.ConverterService converterService) { List result = null; if ((getJavaOutputType() != null) && (getJavaOutputType() != void.class) && (getJavaOutputType() != Void.class)) { String value = getOutputValue(); if (value != null) { String[] extensions = value.split("\\|"); for (String extension : extensions) { List mediaTypes = metadataService .getAllMediaTypes(extension); if (mediaTypes != null) { for (MediaType mediaType : mediaTypes) { if ((result == null) || (!result.contains(mediaType))) { if (result == null) { result = new ArrayList(); } result.add(new Variant(mediaType)); } } } } } if (result == null) { result = (List) converterService.getVariants( getJavaOutputType(), null); } } return result; } /** * Returns the matching Restlet method. * * @return The matching Restlet method. */ public Method getRestletMethod() { return restletMethod; } /** * Returns the annotation value. * * @return The annotation value. */ public String getValue() { return value; } /** * Indicates if the annotated method described is compatible with the given * parameters. * * @param restletMethod * The Restlet method to match. * @param requestEntity * Optional request entity. * @param metadataService * The metadata service to use. * @param converterService * The converter service to use. * @return True if the annotated method is compatible. */ public boolean isCompatible(Method restletMethod, Representation requestEntity, MetadataService metadataService, org.restlet.service.ConverterService converterService) { return getRestletMethod().equals(restletMethod) && isCompatibleRequestEntity(requestEntity, metadataService, converterService); } /** * Indicates if the given request entity is compatible with the annotated * method described. * * @param requestEntity * Optional request entity. * @param metadataService * The metadata service to use. * @param converterService * The converter service to use. * @return True if the given request entity is compatible with the annotated * method described. */ public boolean isCompatibleRequestEntity(Representation requestEntity, MetadataService metadataService, org.restlet.service.ConverterService converterService) { boolean result = true; if ((requestEntity != null) && requestEntity.isAvailable()) { List requestVariants = getRequestVariants(metadataService, converterService); if ((requestVariants != null) && !requestVariants.isEmpty()) { // Check that the compatibility result = false; for (int i = 0; (!result) && (i < requestVariants.size()); i++) { result = (requestVariants.get(i) .isCompatible(requestEntity)); } } else { result = false; } } return result; } @Override public String toString() { return "AnnotationInfo [javaMethod=" + javaMethod + ", resourceInterface=" + resourceClass + ", restletMethod=" + restletMethod + ", value=" + value + "]"; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/resource/package.html0000664000175000017500000000011611757206350026625 0ustar jamespagejamespage Supports resources.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/resource/AnnotationUtils.java0000664000175000017500000002143411757206346030355 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.resource; import java.lang.annotation.Annotation; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.Method; import org.restlet.representation.Representation; import org.restlet.resource.ServerResource; import org.restlet.service.MetadataService; // [excludes gwt] /** * Utilities to manipulate Restlet annotations. * * @author Jerome Louvel */ public class AnnotationUtils { /** Annotation info cache. */ private static final ConcurrentMap, List> cache = new ConcurrentHashMap, List>(); /** * Computes the annotation descriptors for the given Java method. * * @param descriptors * The annotation descriptors to update or null to create a new * one. * @param resourceClass * The class or interface that hosts the javaMethod. * @param javaMethod * The Java method to inspect. * @return The annotation descriptors. */ private static List addAnnotationDescriptors( List descriptors, Class resourceClass, java.lang.reflect.Method javaMethod) { List result = descriptors; // Add the annotation descriptor if (result == null) { result = new CopyOnWriteArrayList(); } for (Annotation annotation : javaMethod.getAnnotations()) { Annotation methodAnnotation = annotation.annotationType() .getAnnotation(org.restlet.engine.Method.class); if (methodAnnotation != null) { Method restletMethod = Method .valueOf(((org.restlet.engine.Method) methodAnnotation) .value()); String toString = annotation.toString(); int startIndex = annotation.annotationType().getCanonicalName() .length() + 8; int endIndex = toString.length() - 1; String value = null; if (endIndex > startIndex) { value = toString.substring(startIndex, endIndex); if ("".equals(value)) { value = null; } } result.add(new AnnotationInfo(resourceClass, restletMethod, javaMethod, value)); } } return result; } /** * Computes the annotation descriptors for the given class or interface. * * @param descriptors * The annotation descriptors to update or null to create a new * one. * @param clazz * The class or interface to introspect. * @return The annotation descriptors. */ private static List addAnnotations( List descriptors, Class clazz) { List result = descriptors; if (clazz != null && !ServerResource.class.equals(clazz)) { // Add the annotation descriptor if (result == null) { result = new CopyOnWriteArrayList(); } // Inspect the current class if (clazz.isInterface()) { for (java.lang.reflect.Method javaMethod : clazz.getMethods()) { addAnnotationDescriptors(result, clazz, javaMethod); } } else { for (java.lang.reflect.Method javaMethod : clazz .getDeclaredMethods()) { addAnnotationDescriptors(result, clazz, javaMethod); } } // Inspect the implemented interfaces for annotations Class[] interfaces = clazz.getInterfaces(); if (interfaces != null) { for (Class interfaceClass : interfaces) { result = addAnnotations(result, interfaceClass); } } // Add the annotations from the super class. addAnnotations(result, clazz.getSuperclass()); } return result; } /** * Clears the annotation descriptors cache. */ public static void clearCache() { cache.clear(); } /** * Returns the first annotation descriptor matching the given Java method. * * @param annotations * The list of annotations. * @param javaMethod * The method to match. * @return The annotation descriptor. */ public static AnnotationInfo getAnnotation( List annotations, java.lang.reflect.Method javaMethod) { if (annotations != null) { for (AnnotationInfo annotationInfo : annotations) { if (annotationInfo.getJavaMethod().equals(javaMethod)) { return annotationInfo; } } } return null; } /** * Returns the first annotation descriptor matching the given Restlet * method. * * @param annotations * The list of annotations. * @param restletMethod * The method to match. * @param entity * The request entity to match or null if no entity is provided. * @param metadataService * The metadata service to use. * @param converterService * The converter service to use. * @return The annotation descriptor. */ public static AnnotationInfo getAnnotation( List annotations, Method restletMethod, Representation entity, MetadataService metadataService, org.restlet.service.ConverterService converterService) { if (annotations != null) { for (AnnotationInfo annotationInfo : annotations) { if (annotationInfo.isCompatible(restletMethod, entity, metadataService, converterService)) { return annotationInfo; } } } return null; } /** * Returns the annotation descriptors for the given resource class. * * @param clazz * The resource class to introspect. * @return The list of annotation descriptors. */ public static List getAnnotations(Class clazz) { List result = cache.get(clazz); if (result == null) { // Inspect the class itself for annotations result = addAnnotations(result, clazz); // Put the list in the cache if no one was previously present List prev = cache.putIfAbsent(clazz, result); if (prev != null) { // Reuse the previous entry result = prev; } } return result; } /** * Returns the annotation descriptors for the given resource class. * * @param javaMethod * The Java method. * @return The list of annotation descriptors. */ public static List getAnnotations(Class clazz, java.lang.reflect.Method javaMethod) { return addAnnotationDescriptors(null, clazz, javaMethod); } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private AnnotationUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/ChainHelper.java0000664000175000017500000001010211757206346025543 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import java.util.logging.Level; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Status; import org.restlet.routing.Filter; /** * Chain helper serving as base class for Application and Component helpers. * * @author Jerome Louvel */ public abstract class ChainHelper extends RestletHelper { /** The first Restlet. */ private volatile Restlet first; /** The last Filter. */ private volatile Filter last; /** * Constructor. * * @param helped * The helped Restlet. */ public ChainHelper(T helped) { super(helped); this.first = null; } /** * Adds a new filter to the chain. * * @param filter * The filter to add. */ protected synchronized void addFilter(Filter filter) { if (getLast() != null) { getLast().setNext(filter); setLast(filter); } else { setFirst(filter); setLast(filter); } } /** * Clears the chain. Sets the first and last filters to null. */ public void clear() { setFirst(null); setLast(null); } /** * Returns the first Restlet. * * @return the first Restlet. */ protected Restlet getFirst() { return this.first; } /** * Returns the last Filter. * * @return the last Filter. */ protected Filter getLast() { return this.last; } @Override public void handle(Request request, Response response) { super.handle(request, response); if (getFirst() != null) { getFirst().handle(request, response); } else { response.setStatus(Status.SERVER_ERROR_INTERNAL); getHelped() .getLogger() .log(Level.SEVERE, "The " + getHelped().getClass().getName() + " class has no Restlet defined to process calls. Maybe it wasn't properly started."); } } /** * Sets the first Restlet. * * @param first * The first Restlet. */ protected void setFirst(Restlet first) { this.first = first; } /** * Sets the last Filter. * * @param last * The last Filter. */ protected void setLast(Filter last) { this.last = last; } /** * Sets the next Restlet after the chain. * * @param next * The Restlet to process after the chain. */ protected synchronized void setNext(Restlet next) { if (getFirst() == null) { setFirst(next); } else { getLast().setNext(next); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/converter/0000775000175000017500000000000011757206350024526 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/converter/ConverterUtils.java0000664000175000017500000001450411757206346030372 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.converter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.engine.Engine; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Utilities for the converter service. * * @author Jerome Louvel */ public class ConverterUtils { /** * Adds a variant to the given list. * * @param variants * The list to update. * @param variant * The variant info to add. * @return The updated list. */ protected static List addVariant(List variants, VariantInfo variant) { List result = variants; if (result == null) { result = new ArrayList(); } if (!result.contains(variant)) { result.add(variant); } return result; } /** * Returns the list of variants that can be converted from a given object * class. * * @param sourceClass * The source class. * @param targetVariant * The expected representation metadata. * @return The list of variants that can be converted. */ public static List getVariants(Class sourceClass, Variant targetVariant) { List result = null; List helperVariants = null; for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { // List of variants that can be converted from the source class helperVariants = ch.getVariants(sourceClass); if (helperVariants != null) { // Loop over the variants list for (VariantInfo helperVariant : helperVariants) { if (targetVariant == null) { result = addVariant(result, helperVariant); } else if (helperVariant.includes(targetVariant)) { // Detected a more generic variant, but still consider // the conversion is possible to the target variant. result = addVariant(result, new VariantInfo( targetVariant.getMediaType())); } else if (targetVariant.includes(helperVariant)) { // Detected a more specific variant, but still consider // the conversion is possible to the target variant. result = addVariant(result, helperVariant); } } } } return result; } /** * Returns the best converter helper matching the given parameters. * * @param source * The object to convert to a representation. * @param target * The target representation variant. * @param resource * The optional parent resource. * @return The matched converter helper or null. */ public static ConverterHelper getBestHelper(Object source, Variant target, UniformResource resource) { ConverterHelper result = null; float bestScore = -1.0F; float currentScore; for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { try { currentScore = ch.score(source, target, resource); if (currentScore > bestScore) { bestScore = currentScore; result = ch; } } catch (Exception e) { Context.getCurrentLogger().log( Level.SEVERE, "Unable get the score of the " + ch + " converter helper.", e); } } return result; } /** * Returns the best converter helper matching the given parameters. * * @param * The target class. * @param source * The source representation variant. * @param target * The target class. * @param resource * The parent resource. * @return The matched converter helper or null. */ public static ConverterHelper getBestHelper(Representation source, Class target, UniformResource resource) { ConverterHelper result = null; float bestScore = -1.0F; float currentScore; for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { currentScore = ch.score(source, target, resource); if (currentScore > bestScore) { bestScore = currentScore; result = ch; } } return result; } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private ConverterUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/converter/package.html0000664000175000017500000000013211757206350027003 0ustar jamespagejamespage Supports the converter service.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java0000664000175000017500000001607711757206346030520 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.converter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.data.ClientInfo; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.Helper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between Representations and regular Java objects. * * @author Jerome Louvel */ public abstract class ConverterHelper extends Helper { /** * Adds an object class to the given list. Creates a new list if necessary. * * @param objectClasses * The object classes list to update or null. * @param objectClass * The object class to add. * @return The input object classes list or a new one. */ protected List> addObjectClass(List> objectClasses, Class objectClass) { if (objectClasses == null) { objectClasses = new ArrayList>(); } objectClasses.add(objectClass); return objectClasses; } /** * Adds a variant to the given list. Creates a new list if necessary. * * @param variants * The variants list to update or null. * @param userVariant * The variant to add if not null. * @return The input variants list or a new one. */ protected List addVariant(List variants, VariantInfo userVariant) { if (userVariant != null) { if (variants == null) { variants = new ArrayList(); } variants.add(userVariant); } return variants; } /** * Returns the list of object classes that can be converted from a given * variant. * * @param source * The source variant. * @return The list of object class that can be converted. */ public abstract List> getObjectClasses(Variant source); /** * Returns the list of variants that can be converted from a given object * class. The preferred variant should be set in first position. * * @param source * The source object class. * @return The list of variants that can be converted. */ public abstract List getVariants(Class source); /** * Scores the affinity of this helper with the source class. * * @param source * The source object to convert. * @param target * The expected representation metadata. * @param resource * The calling resource. * @return The affinity score of this helper. */ public abstract float score(Object source, Variant target, UniformResource resource); /** * Scores the affinity of this helper with the source class. * * @param source * The source representation to convert. * @param target * The expected class of the Java object. * @param resource * The calling resource. * @return The affinity score of this helper. */ public abstract float score(Representation source, Class target, UniformResource resource); /** * Converts a Representation into a regular Java object. * * @param * The expected class of the Java object. * @param source * The source representation to convert. * @param target * The expected class of the Java object. * @param resource * The calling resource. * @return The converted Java object. */ public abstract T toObject(Representation source, Class target, UniformResource resource) throws IOException; /** * Converts a regular Java object into a Representation. * * @param source * The source object to convert. * @param target * The expected representation metadata. * @param resource * The calling resource. * @return The converted representation. */ public abstract Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException; /** * Updates the preferences of the given {@link ClientInfo} object with * conversion capabilities for the given entity class. * * @param preferences * The media type preferences. * @param entity * The entity class to convert. */ public void updatePreferences(List> preferences, Class entity) { // Does nothing by default } /** * Updates the preferences of the given {@link ClientInfo} object with * conversion capabilities for the given entity class. * * @param preferences * The media type preferences. * @param mediaType * The media type to update to add to the preferences. * @param score * The media type score to use as a quality score. */ public void updatePreferences(List> preferences, MediaType mediaType, float score) { boolean found = false; Preference preference; for (int i = 0; !found && (i < preferences.size()); i++) { preference = preferences.get(i); if (preference.getMetadata().equals(mediaType) && (preference.getQuality() < score)) { preference.setQuality(score); found = true; } } if (!found) { preferences.add(new Preference(mediaType, score)); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/converter/DefaultConverter.java0000664000175000017500000003435111757206346030660 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.converter; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.Serializable; import java.nio.channels.ReadableByteChannel; import java.util.List; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.FileRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.ObjectRepresentation; import org.restlet.representation.ReaderRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter for the built-in Representation classes. * * @author Jerome Louvel */ public class DefaultConverter extends ConverterHelper { /** Neutral variant. */ private static final VariantInfo VARIANT_ALL = new VariantInfo( MediaType.ALL); /** Web form variant. */ private static final VariantInfo VARIANT_FORM = new VariantInfo( MediaType.APPLICATION_WWW_FORM); /** Octet stream variant. */ private static final VariantInfo VARIANT_OBJECT = new VariantInfo( MediaType.APPLICATION_JAVA_OBJECT); /** Octet stream variant. */ private static final VariantInfo VARIANT_OBJECT_XML = new VariantInfo( MediaType.APPLICATION_JAVA_OBJECT_XML); @Override public List> getObjectClasses(Variant source) { List> result = null; result = addObjectClass(result, String.class); result = addObjectClass(result, InputStream.class); result = addObjectClass(result, Reader.class); result = addObjectClass(result, ReadableByteChannel.class); if (source.getMediaType() != null) { MediaType mediaType = source.getMediaType(); if (MediaType.APPLICATION_JAVA_OBJECT.equals(mediaType) || MediaType.APPLICATION_JAVA_OBJECT_XML.equals(mediaType)) { result = addObjectClass(result, Object.class); } else if (MediaType.APPLICATION_WWW_FORM.equals(mediaType)) { result = addObjectClass(result, Form.class); } } return result; } @Override public List getVariants(Class source) { List result = null; if (source != null) { if (String.class.isAssignableFrom(source) || StringRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ALL); } else if (File.class.isAssignableFrom(source) || FileRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ALL); } else if (InputStream.class.isAssignableFrom(source) || InputRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ALL); } else if (Reader.class.isAssignableFrom(source) || ReaderRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ALL); } else if (Representation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ALL); } else if (Form.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_FORM); } else if (Serializable.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_OBJECT); result = addVariant(result, VARIANT_OBJECT_XML); } } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source instanceof String) { result = 1.0F; } else if (source instanceof File) { result = 1.0F; } else if (source instanceof Form) { if ((target != null) && MediaType.APPLICATION_WWW_FORM.isCompatible(target .getMediaType())) { result = 1.0F; } else { result = 0.6F; } } else if (source instanceof InputStream) { result = 1.0F; } else if (source instanceof Reader) { result = 1.0F; } else if (source instanceof Representation) { result = 1.0F; } else if (source instanceof Serializable) { if (target != null) { if (MediaType.APPLICATION_JAVA_OBJECT.equals(target .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_JAVA_OBJECT .isCompatible(target.getMediaType())) { result = 0.6F; } else if (MediaType.APPLICATION_JAVA_OBJECT_XML.equals(target .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_JAVA_OBJECT_XML .isCompatible(target.getMediaType())) { result = 0.6F; } } else { result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (target != null) { if (target.isAssignableFrom(source.getClass())) { result = 1.0F; } else if (String.class.isAssignableFrom(target)) { result = 1.0F; } else if (StringRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (EmptyRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (File.class.isAssignableFrom(target)) { if (source instanceof FileRepresentation) { result = 1.0F; } } else if (Form.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_WWW_FORM.isCompatible(source .getMediaType())) { result = 1.0F; } else { result = 0.5F; } } else if (InputStream.class.isAssignableFrom(target)) { result = 1.0F; } else if (InputRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (Reader.class.isAssignableFrom(target)) { result = 1.0F; } else if (ReaderRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (Serializable.class.isAssignableFrom(target) || target.isPrimitive()) { if (MediaType.APPLICATION_JAVA_OBJECT.equals(source .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_JAVA_OBJECT .isCompatible(source.getMediaType())) { result = 0.6F; } else if (MediaType.APPLICATION_JAVA_OBJECT_XML.equals(source .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_JAVA_OBJECT_XML .isCompatible(source.getMediaType())) { result = 0.6F; } else { result = 0.5F; } } } else if (source instanceof ObjectRepresentation) { result = 1.0F; } return result; } @SuppressWarnings("unchecked") @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (target != null) { if (target.isAssignableFrom(source.getClass())) { result = source; } else if (String.class.isAssignableFrom(target)) { result = source.getText(); } else if (StringRepresentation.class.isAssignableFrom(target)) { result = new StringRepresentation(source.getText(), source.getMediaType()); } else if (EmptyRepresentation.class.isAssignableFrom(target)) { result = null; } else if (File.class.isAssignableFrom(target)) { if (source instanceof FileRepresentation) { result = ((FileRepresentation) source).getFile(); } else { result = null; } } else if (Form.class.isAssignableFrom(target)) { result = new Form(source); } else if (InputStream.class.isAssignableFrom(target)) { result = source.getStream(); } else if (InputRepresentation.class.isAssignableFrom(target)) { result = new InputRepresentation(source.getStream()); } else if (Reader.class.isAssignableFrom(target)) { result = source.getReader(); } else if (ReaderRepresentation.class.isAssignableFrom(target)) { result = new ReaderRepresentation(source.getReader()); } else if (Serializable.class.isAssignableFrom(target) || (target.isPrimitive())) { if (source instanceof ObjectRepresentation) { result = ((ObjectRepresentation) source).getObject(); } else { try { result = new ObjectRepresentation(source) .getObject(); } catch (Exception e) { IOException ioe = new IOException( "Unable to create the Object representation"); ioe.initCause(e); result = null; } } } } else if (source instanceof ObjectRepresentation) { result = ((ObjectRepresentation) source).getObject(); } return (T) result; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { Representation result = null; if (source instanceof String) { result = new StringRepresentation((String) source, MediaType.getMostSpecific(target.getMediaType(), MediaType.TEXT_PLAIN)); } else if (source instanceof File) { result = new FileRepresentation((File) source, MediaType.getMostSpecific(target.getMediaType(), MediaType.APPLICATION_OCTET_STREAM)); } else if (source instanceof Form) { result = ((Form) source).getWebRepresentation(); } else if (source instanceof InputStream) { result = new InputRepresentation((InputStream) source, MediaType.getMostSpecific(target.getMediaType(), MediaType.APPLICATION_OCTET_STREAM)); } else if (source instanceof Reader) { result = new ReaderRepresentation((Reader) source, MediaType.getMostSpecific(target.getMediaType(), MediaType.TEXT_PLAIN)); } else if (source instanceof Representation) { result = (Representation) source; } else if (source instanceof Serializable) { result = new ObjectRepresentation( (Serializable) source, MediaType.getMostSpecific( target.getMediaType(), MediaType.APPLICATION_OCTET_STREAM)); } return result; } @Override public void updatePreferences(List> preferences, Class entity) { if (Form.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_WWW_FORM, 1.0F); } else if (Serializable.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_JAVA_OBJECT, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_JAVA_OBJECT_XML, 1.0F); } else if (String.class.isAssignableFrom(entity) || Reader.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.TEXT_PLAIN, 1.0F); updatePreferences(preferences, MediaType.TEXT_ALL, 0.5F); } else if (InputStream.class.isAssignableFrom(entity) || ReadableByteChannel.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_OCTET_STREAM, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_ALL, 0.5F); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/0000775000175000017500000000000011757206350023611 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java0000664000175000017500000001123511757206350030007 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.engine.ClientHelper; /** * Connector to the local resources accessible via file system, class loaders * and similar mechanisms. Here is the list of parameters that are supported. * They should be set in the Client's context before it is started: * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    timeToLiveint600Time to live for a representation before it expires (in seconds). If you * set the value to '0', the representation will never expire.
    defaultLanguageStringWhen no metadata service is available (simple client connector with no * parent application), falls back on this default language. To indicate that no * default language should be set, "" can be used.
    * * @see org.restlet.data.LocalReference * @author Jerome Louvel * @author Thierry Boileau */ public abstract class LocalClientHelper extends ClientHelper { /** * Constructor. Note that the common list of metadata associations based on * extensions is added, see the addCommonExtensions() method. * * @param client * The client to help. */ public LocalClientHelper(Client client) { super(client); } /** * Returns the default language. When no metadata service is available * (simple client connector with no parent application), falls back on this * default language. * * @return The default language. */ public String getDefaultLanguage() { return getHelpedParameters().getFirstValue("defaultLanguage", ""); } /** * Returns the time to live for a file representation before it expires (in * seconds). * * @return The time to live for a file representation before it expires (in * seconds). */ public int getTimeToLive() { return Integer.parseInt(getHelpedParameters().getFirstValue( "timeToLive", "600")); } /** * Handles a call. Note that this implementation will systematically * normalize and URI-decode the resource reference. * * @param request * The request to handle. * @param response * The response to update. */ @Override public final void handle(Request request, Response response) { // Ensure that all ".." and "." are normalized into the path // to prevent unauthorized access to user directories. request.getResourceRef().normalize(); // As the path may be percent-encoded, it has to be percent-decoded. // Then, all generated URIs must be encoded. String path = request.getResourceRef().getPath(); String decodedPath = Reference.decode(path); // Continue the local handling handleLocal(request, response, decodedPath); } /** * Handles a local call. * * @param request * The request to handle. * @param response * The response to update. * @param decodedPath * The decoded local path. */ protected abstract void handleLocal(Request request, Response response, String decodedPath); } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/FileEntity.java0000664000175000017500000000635011757206346026541 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.io.File; import java.util.ArrayList; import java.util.List; import org.restlet.data.MediaType; import org.restlet.representation.FileRepresentation; import org.restlet.representation.Representation; import org.restlet.service.MetadataService; /** * Local entity based on a regular {@link File}. */ public class FileEntity extends Entity { /** The underlying regular file. */ private final File file; /** * Constructor. * * @param file * The underlying file. * @param metadataService * The metadata service to use. */ public FileEntity(File file, MetadataService metadataService) { super(metadataService); this.file = file; } @Override public boolean exists() { return getFile().exists(); } @Override public List getChildren() { List result = null; if (isDirectory()) { result = new ArrayList(); for (File f : getFile().listFiles()) { result.add(new FileEntity(f, getMetadataService())); } } return result; } /** * Returns the underlying regular file. * * @return The underlying regular file. */ public File getFile() { return file; } @Override public String getName() { return getFile().getName(); } @Override public Entity getParent() { File parentFile = getFile().getParentFile(); return (parentFile == null) ? null : new FileEntity(parentFile, getMetadataService()); } @Override public Representation getRepresentation(MediaType defaultMediaType, int timeToLive) { return new FileRepresentation(getFile(), defaultMediaType, timeToLive); } @Override public boolean isDirectory() { return getFile().isDirectory(); } @Override public boolean isNormal() { return getFile().isFile(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/ZipEntryEntity.java0000664000175000017500000001132411757206346027443 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.service.MetadataService; /** * Local entity based on an entry in a Zip archive. * * @author Remi Dewitte */ public class ZipEntryEntity extends Entity { /** The Zip file. */ protected final ZipFile zipFile; /** The Zip entry. */ protected final ZipEntry entry; /** * Constructor. * * @param zipFile * The Zip file. * @param entryName * The Zip entry name. * @param metadataService * The metadata service to use. */ public ZipEntryEntity(ZipFile zipFile, String entryName, MetadataService metadataService) { super(metadataService); this.zipFile = zipFile; ZipEntry entry = zipFile.getEntry(entryName); if (entry == null) this.entry = new ZipEntry(entryName); else { // Checking we don't have a directory ZipEntry entryDir = zipFile.getEntry(entryName + "/"); if (entryDir != null) this.entry = entryDir; else this.entry = entry; } } /** * Constructor. * * @param zipFile * The Zip file. * @param entry * The Zip entry. * @param metadataService * The metadata service to use. */ public ZipEntryEntity(ZipFile zipFile, ZipEntry entry, MetadataService metadataService) { super(metadataService); this.zipFile = zipFile; this.entry = entry; } @Override public boolean exists() { if ("".equals(getName())) return true; // ZipEntry re = zipFile.getEntry(entry.getName()); // return re != null; return entry.getSize() != -1; } @Override public List getChildren() { List result = null; if (isDirectory()) { result = new ArrayList(); Enumeration entries = zipFile.entries(); String n = entry.getName(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().startsWith(n) && e.getName().length() != n.length()) result.add(new ZipEntryEntity(zipFile, e, getMetadataService())); } } return result; } @Override public String getName() { return entry.getName(); } @Override public Entity getParent() { if ("".equals(entry.getName())) return null; String n = entry.getName(); String pn = n.substring(0, n.lastIndexOf('/') + 1); return new ZipEntryEntity(zipFile, zipFile.getEntry(pn), getMetadataService()); } @Override public Representation getRepresentation(MediaType defaultMediaType, int timeToLive) { return new ZipEntryRepresentation(defaultMediaType, zipFile, entry); } @Override public boolean isDirectory() { if ("".equals(entry.getName())) return true; return entry.isDirectory(); } @Override public boolean isNormal() { return !entry.isDirectory(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/package.html0000664000175000017500000000014311757206350026070 0ustar jamespagejamespage Supports local connectors and resources.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/local/DirectoryServerResource.java0000664000175000017500000010423511757206350031324 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Reference; import org.restlet.data.ReferenceList; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.Directory; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Resource supported by a set of context representations (from file system, * class loaders and webapp context). A content negotiation mechanism (similar * to Apache HTTP server) is available. It is based on path extensions to detect * variants (languages, media types or character sets). * * @see Apache * mod_negotiation module * @author Jerome Louvel * @author Thierry Boileau */ public class DirectoryServerResource extends ServerResource { /** The list of variants for the GET method. */ private volatile List variantsGet; /** * The local base name of the resource. For example, "foo.en" and * "foo.en-GB.html" return "foo". */ private volatile String baseName; /** The base variant. */ private volatile Variant baseVariant; /** The parent directory handler. */ private volatile Directory directory; /** If the resource is a directory, this contains its content. */ private volatile ReferenceList directoryContent; /** * If the resource is a directory, the non-trailing slash character leads to * redirection. */ private volatile boolean directoryRedirection; /** Indicates if the target resource is a directory. */ private volatile boolean directoryTarget; /** The context's directory URI (file, clap URI). */ private volatile String directoryUri; /** If the resource is a file, this contains its content. */ private volatile Representation fileContent; /** Indicates if the target resource is a file. */ private volatile boolean fileTarget; /** Indicates if the target resource is a directory with an index. */ private volatile boolean indexTarget; /** The original target URI, in case of extensions tunneling. */ private volatile Reference originalRef; /** The prototype variant. */ private volatile Variant protoVariant; /** The resource path relative to the directory URI. */ private volatile String relativePart; /** The context's target URI (file, clap URI). */ private volatile String targetUri; /** The unique representation of the target URI, if it exists. */ private volatile Reference uniqueReference; @Override public Representation delete() throws ResourceException { if (this.directory.isModifiable()) { Request contextRequest = new Request(Method.DELETE, this.targetUri); Response contextResponse = new Response(contextRequest); if (this.directoryTarget && !this.indexTarget) { contextRequest.setResourceRef(this.targetUri); getClientDispatcher().handle(contextRequest, contextResponse); } else { // Check if there is only one representation // Try to get the unique representation of the resource ReferenceList references = getVariantsReferences(); if (!references.isEmpty()) { if (this.uniqueReference != null) { contextRequest.setResourceRef(this.uniqueReference); getClientDispatcher().handle(contextRequest, contextResponse); } else { // We found variants, but not the right one contextResponse .setStatus(new Status( Status.CLIENT_ERROR_NOT_ACCEPTABLE, "Unable to process properly the request. Several variants exist but none of them suits precisely. ")); } } else { contextResponse.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } setStatus(contextResponse.getStatus()); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, "The directory is not modifiable."); } return null; } /** * This initialization method aims at answering the following questions:
    *

      *
    • does this request target a directory?
    • *
    • does this request target a directory, with an index file?
    • *
    • should this request be redirected (target is a directory with no * trailing "/")?
    • *
    • does this request target a file?
    • *
    *
    * The following constraints must be taken into account:
    *
      *
    • the underlying helper may not support content negotiation and be able * to return the list of possible variants of the target file (e.g. the CLAP * helper).
    • *
    • the underlying helper may not support directory listing
    • *
    • the extensions tunneling cannot apply on a directory
    • *
    • underlying helpers that do not support content negotiation cannot * support extensions tunneling
    • *
    */ @Override public void doInit() throws ResourceException { try { // Update the member variables this.directory = (Directory) getRequestAttributes().get( "org.restlet.directory"); this.relativePart = getReference().getRemainingPart(false, false); setNegotiated(this.directory.isNegotiatingContent()); // Restore the original URI in case the call has been tunneled. if ((getApplication() != null) && getApplication().getTunnelService().isExtensionsTunnel()) { this.originalRef = getOriginalRef(); if (this.originalRef != null) { this.originalRef.setBaseRef(getReference().getBaseRef()); this.relativePart = this.originalRef.getRemainingPart(); } } if (this.relativePart.startsWith("/")) { // We enforce the leading slash on the root URI this.relativePart = this.relativePart.substring(1); } // The target URI does not take into account the query and fragment // parts of the resource. this.targetUri = new Reference(directory.getRootRef().toString() + this.relativePart).normalize().toString(false, false); if (!this.targetUri.startsWith(directory.getRootRef().toString())) { // Prevent the client from accessing resources in upper // directories this.targetUri = directory.getRootRef().toString(); } if (getClientDispatcher() == null) { getLogger().warning( "No client dispatcher is available on the context. Can't get the target URI: " + this.targetUri); } else { // Try to detect the presence of a directory Response contextResponse = getRepresentation(this.targetUri); if (contextResponse.getEntity() != null) { // As a convention, underlying client connectors return the // directory listing with the media-type // "MediaType.TEXT_URI_LIST" when handling directories if (MediaType.TEXT_URI_LIST.equals(contextResponse .getEntity().getMediaType())) { this.directoryTarget = true; this.fileTarget = false; this.directoryContent = new ReferenceList( contextResponse.getEntity()); if (!getReference().getPath().endsWith("/")) { // All requests will be automatically redirected this.directoryRedirection = true; } if (!this.targetUri.endsWith("/")) { this.targetUri += "/"; this.relativePart += "/"; } // Append the index name if ((getDirectory().getIndexName() != null) && (getDirectory().getIndexName().length() > 0)) { this.directoryUri = this.targetUri; this.baseName = getDirectory().getIndexName(); this.targetUri = this.directoryUri + this.baseName; this.indexTarget = true; } else { this.directoryUri = this.targetUri; this.baseName = null; } } else { // Allows underlying helpers that do not support // "content negotiation" to return the targeted file. // Sometimes we immediately reach the target entity, so // we return it directly. this.directoryTarget = false; this.fileTarget = true; this.fileContent = contextResponse.getEntity(); } } else { this.directoryTarget = false; this.fileTarget = false; // Let's try with the optional index, in case the underlying // client connector does not handle directory listing. if (this.targetUri.endsWith("/")) { // In this case, the trailing "/" shows that the URI // must point to a directory if ((getDirectory().getIndexName() != null) && (getDirectory().getIndexName().length() > 0)) { this.directoryUri = this.targetUri; this.directoryTarget = true; contextResponse = getRepresentation(this.directoryUri + getDirectory().getIndexName()); if (contextResponse.getEntity() != null) { this.baseName = getDirectory().getIndexName(); this.targetUri = this.directoryUri + this.baseName; this.directoryContent = new ReferenceList(); this.directoryContent.add(new Reference( this.targetUri)); this.indexTarget = true; } } } else { // Try to determine if this target URI with no trailing // "/" is a directory, in order to force the // redirection. if ((getDirectory().getIndexName() != null) && (getDirectory().getIndexName().length() > 0)) { // Append the index name contextResponse = getRepresentation(this.targetUri + "/" + getDirectory().getIndexName()); if (contextResponse.getEntity() != null) { this.directoryUri = this.targetUri + "/"; this.baseName = getDirectory().getIndexName(); this.targetUri = this.directoryUri + this.baseName; this.directoryTarget = true; this.directoryRedirection = true; this.directoryContent = new ReferenceList(); this.directoryContent.add(new Reference( this.targetUri)); this.indexTarget = true; } } } } // In case the request does not target a directory and the file // has not been found, try with the tunneled URI. if (isNegotiated() && !this.directoryTarget && !this.fileTarget && (this.originalRef != null)) { this.relativePart = getReference().getRemainingPart(); // The target URI does not take into account the query and // fragment parts of the resource. this.targetUri = new Reference(directory.getRootRef() .toString() + this.relativePart).normalize() .toString(false, false); if (!this.targetUri.startsWith(directory.getRootRef() .toString())) { // Prevent the client from accessing resources in upper // directories this.targetUri = directory.getRootRef().toString(); } } if (!fileTarget || (fileContent == null) || !getRequest().getMethod().isSafe()) { // Try to get the directory content, in case the request // does not target a directory if (!this.directoryTarget) { int lastSlashIndex = this.targetUri.lastIndexOf('/'); if (lastSlashIndex == -1) { this.directoryUri = ""; this.baseName = this.targetUri; } else { this.directoryUri = this.targetUri.substring(0, lastSlashIndex + 1); this.baseName = this.targetUri .substring(lastSlashIndex + 1); } contextResponse = getRepresentation(this.directoryUri); if ((contextResponse.getEntity() != null) && MediaType.TEXT_URI_LIST .equals(contextResponse.getEntity() .getMediaType())) { this.directoryContent = new ReferenceList( contextResponse.getEntity()); } } if (this.baseName != null) { // Analyze extensions this.baseVariant = new Variant(); Entity.updateMetadata(this.baseName, this.baseVariant, true, getMetadataService()); this.protoVariant = new Variant(); Entity.updateMetadata(this.baseName, this.protoVariant, false, getMetadataService()); // Remove stored extensions from the base name this.baseName = Entity.getBaseName(this.baseName, getMetadataService()); } // Check if the resource exists or not. List variants = getVariants(Method.GET); if ((variants == null) || (variants.isEmpty())) { setExisting(false); } } // Check if the resource is located in a sub directory. if (isExisting() && !this.directory.isDeeplyAccessible()) { // Count the number of "/" character. int index = this.relativePart.indexOf("/"); if (index != -1) { index = this.relativePart.indexOf("/", index); setExisting((index == -1)); } } } // Log results getLogger().info("Converted target URI: " + this.targetUri); getLogger().fine("Converted base name : " + this.baseName); } catch (IOException ioe) { throw new ResourceException(ioe); } } @Override protected Representation get() throws ResourceException { // Content negotiation has been disabled // The variant that may need to meet the request conditions Representation result = null; List variants = getVariants(Method.GET); if ((variants == null) || (variants.isEmpty())) { // Resource not found getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { if (variants.size() == 1) { result = (Representation) variants.get(0); } else { ReferenceList variantRefs = new ReferenceList(); for (Variant variant : variants) { if (variant.getLocationRef() != null) { variantRefs.add(variant.getLocationRef()); } else { getLogger() .warning( "A resource with multiple variants should provide a location for each variant when content negotiation is turned off"); } } if (variantRefs.size() > 0) { // Return the list of variants setStatus(Status.REDIRECTION_MULTIPLE_CHOICES); result = variantRefs.getTextRepresentation(); } else { setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } } return result; } /** * Returns the local base name of the file. For example, "foo.en" and * "foo.en-GB.html" return "foo". * * @return The local name of the file. */ public String getBaseName() { return this.baseName; } /** * Returns a client dispatcher. * * @return A client dispatcher. */ protected Client getClientDispatcher() { return getDirectory().getContext() == null ? null : getDirectory() .getContext().getClientDispatcher(); } /** * Returns the parent directory handler. * * @return The parent directory handler. */ public Directory getDirectory() { return this.directory; } /** * If the resource is a directory, this returns its content. * * @return The directory content. */ protected ReferenceList getDirectoryContent() { return directoryContent; } /** * Returns the context's directory URI (file, clap URI). * * @return The context's directory URI (file, clap URI). */ public String getDirectoryUri() { return this.directoryUri; } /** * Returns a representation of the resource at the target URI. Leverages the * client dispatcher of the parent directory's context. * * @param resourceUri * The URI of the target resource. * @return A response with the representation if success. */ private Response getRepresentation(String resourceUri) { return getClientDispatcher().handle( new Request(Method.GET, resourceUri)); } /** * Returns a representation of the resource at the target URI. Leverages the * client dispatcher of the parent directory's context. * * @param resourceUri * The URI of the target resource. * @param acceptedMediaType * The accepted media type or null. * @return A response with the representation if success. */ protected Response getRepresentation(String resourceUri, MediaType acceptedMediaType) { if (acceptedMediaType == null) { return getClientDispatcher().handle( new Request(Method.GET, resourceUri)); } Request request = new Request(Method.GET, resourceUri); request.getClientInfo().getAcceptedMediaTypes() .add(new Preference(acceptedMediaType)); return getClientDispatcher().handle(request); } /** * Allows to sort the list of representations set by the resource. * * @return A Comparator instance imposing a sort order of representations or * null if no special order is wanted. */ private Comparator getRepresentationsComparator() { // Sort the list of representations by their identifier. Comparator identifiersComparator = new Comparator() { public int compare(Representation rep0, Representation rep1) { boolean bRep0Null = (rep0.getLocationRef() == null); boolean bRep1Null = (rep1.getLocationRef() == null); if (bRep0Null && bRep1Null) { return 0; } if (bRep0Null) { return -1; } if (bRep1Null) { return 1; } return rep0.getLocationRef().getLastSegment() .compareTo(rep1.getLocationRef().getLastSegment()); } }; return identifiersComparator; } /** * Returns the context's target URI (file, clap URI). * * @return The context's target URI (file, clap URI). */ public String getTargetUri() { return this.targetUri; } @Override public List getVariants() { return getVariants(getMethod()); } /** * Returns the list of variants for the given method. * * @param method * The related method. * @return The list of variants for the given method. */ protected List getVariants(Method method) { List result = null; if ((Method.GET.equals(method) || Method.HEAD.equals(method))) { if (variantsGet != null) { result = variantsGet; } else { getLogger().info("Getting variants for : " + getTargetUri()); if ((this.directoryContent != null) && (getReference() != null) && (getReference().getBaseRef() != null)) { // Allows to sort the list of representations SortedSet resultSet = new TreeSet( getRepresentationsComparator()); // Compute the base reference (from a call's client point of // view) String baseRef = getReference().getBaseRef().toString( false, false); if (!baseRef.endsWith("/")) { baseRef += "/"; } int lastIndex = this.relativePart.lastIndexOf("/"); if (lastIndex != -1) { baseRef += this.relativePart.substring(0, lastIndex); } int rootLength = getDirectoryUri().length(); if (this.baseName != null) { String filePath; for (Reference ref : getVariantsReferences()) { // Add the new variant to the result list Response contextResponse = getRepresentation(ref .toString()); if (contextResponse.getStatus().isSuccess() && (contextResponse.getEntity() != null)) { filePath = ref.toString(false, false) .substring(rootLength); Representation rep = contextResponse .getEntity(); if (filePath.startsWith("/")) { rep.setLocationRef(baseRef + filePath); } else { rep.setLocationRef(baseRef + "/" + filePath); } resultSet.add(rep); } } } if (!resultSet.isEmpty()) { result = new ArrayList(resultSet); } if (resultSet.isEmpty()) { if (this.directoryTarget && getDirectory().isListingAllowed()) { ReferenceList userList = new ReferenceList( this.directoryContent.size()); // Set the list identifier userList.setIdentifier(baseRef); SortedSet sortedSet = new TreeSet( getDirectory().getComparator()); sortedSet.addAll(this.directoryContent); for (Reference ref : sortedSet) { String filePart = ref.toString(false, false) .substring(rootLength); StringBuilder filePath = new StringBuilder(); if ((!baseRef.endsWith("/")) && (!filePart.startsWith("/"))) { filePath.append('/'); } filePath.append(filePart); userList.add(baseRef + filePath); } List list = getDirectory() .getIndexVariants(userList); for (Variant variant : list) { if (result == null) { result = new ArrayList(); } result.add(getDirectory() .getIndexRepresentation(variant, userList)); } } } } else if (this.fileTarget && (this.fileContent != null)) { // Sets the location of the target representation. if (getOriginalRef() != null) { this.fileContent.setLocationRef(getRequest() .getOriginalRef()); } else { this.fileContent.setLocationRef(getReference()); } result = new ArrayList(); result.add(this.fileContent); } this.variantsGet = result; } } return result; } /** * Returns the references of the representations of the target resource * according to the directory handler property * * @return The list of variants references */ private ReferenceList getVariantsReferences() { ReferenceList result = new ReferenceList(0); try { this.uniqueReference = null; // Ask for the list of all variants of this resource Response contextResponse = getRepresentation(this.targetUri, MediaType.TEXT_URI_LIST); if (contextResponse.getEntity() != null) { // Test if the given response is the list of all variants for // this resource if (MediaType.TEXT_URI_LIST.equals(contextResponse.getEntity() .getMediaType())) { ReferenceList listVariants = new ReferenceList( contextResponse.getEntity()); String entryUri; String fullEntryName; String baseEntryName; int lastSlashIndex; int firstDotIndex; for (Reference ref : listVariants) { entryUri = ref.toString(); lastSlashIndex = entryUri.lastIndexOf('/'); fullEntryName = (lastSlashIndex == -1) ? entryUri : entryUri.substring(lastSlashIndex + 1); baseEntryName = fullEntryName; // Remove the extensions from the base name firstDotIndex = fullEntryName.indexOf('.'); if (firstDotIndex != -1) { baseEntryName = fullEntryName.substring(0, firstDotIndex); } // Check if the current file is a valid variant if (baseEntryName.equals(this.baseName)) { // Test if the variant is included in the base // prototype variant Variant variant = new Variant(); Entity.updateMetadata(fullEntryName, variant, true, getMetadataService()); if (this.protoVariant.includes(variant)) { result.add(ref); } // Test if the variant is equal to the base variant if (this.baseVariant.equals(variant)) { // The unique reference has been found. this.uniqueReference = ref; } } } } else { result.add(contextResponse.getEntity().getLocationRef()); } } } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to get resource variants", ioe); } return result; } @Override public Representation handle() { Representation result = null; if (this.directoryRedirection) { if (this.originalRef != null) { if (this.originalRef.hasQuery()) { redirectSeeOther(this.originalRef.getPath() + "/?" + this.originalRef.getQuery()); } else { redirectSeeOther(this.originalRef.getPath() + "/"); } } else { if (getReference().hasQuery()) { redirectSeeOther(getReference().getPath() + "/?" + getReference().getQuery()); } else { redirectSeeOther(getReference().getPath() + "/"); } } } else { result = super.handle(); } return result; } /** * Indicates if the target resource is a directory. * * @return True if the target resource is a directory. */ public boolean isDirectoryTarget() { return this.directoryTarget; } /** * Indicates if the target resource is a file. * * @return True if the target resource is a file. */ public boolean isFileTarget() { return this.fileTarget; } @Override public Representation put(Representation entity) throws ResourceException { if (this.directory.isModifiable()) { // Transfer of PUT calls is only allowed if the readOnly flag is // not set. Request contextRequest = new Request(Method.PUT, this.targetUri); // Add support of partial PUT calls. contextRequest.getRanges().addAll(getRanges()); contextRequest.setEntity(entity); Response contextResponse = new Response(contextRequest); contextRequest.setResourceRef(this.targetUri); getClientDispatcher().handle(contextRequest, contextResponse); setStatus(contextResponse.getStatus()); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, "The directory is not modifiable."); } return null; } /** * Sets the context's target URI (file, clap URI). * * @param targetUri * The context's target URI. */ public void setTargetUri(String targetUri) { this.targetUri = targetUri; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/ClapClientHelper.java0000664000175000017500000002007311757206346027641 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Date; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.service.MetadataService; /** * Connector to the resources accessed via class loaders. Note that if you use * the class authority for your CLAP URIs, you can provide a custom classloader * instead of the one of the connector. For this, your requests need to have a * "org.restlet.clap.classLoader" attribute set with the instance of your * classloader and use the {@link LocalReference#CLAP_CLASS} authority. * * @author Jerome Louvel */ public class ClapClientHelper extends LocalClientHelper { /** * Constructor. * * @param client * The client to help. */ public ClapClientHelper(Client client) { super(client); getProtocols().add(Protocol.CLAP); } /** * Handles a call with a given class loader. * * @param request * The request to handle. * @param response * The response to update. */ protected void handleClassLoader(Request request, Response response, ClassLoader classLoader) { MetadataService metadataService = getMetadataService(); if (request.getMethod().equals(Method.GET) || request.getMethod().equals(Method.HEAD)) { String path = request.getResourceRef().getPath(); URL url = null; Date modificationDate = null; // Prepare a classloader URI, removing the leading slash if ((path != null) && path.startsWith("/")) { path = path.substring(1); } // Get the URL to the classloader 'resource' if (classLoader != null) { // As the path may be percent-encoded, it has to be // percent-decoded. url = classLoader.getResource(Reference.decode(path)); } else { getLogger() .warning( "Unable to get the resource. The selected classloader is null."); } // The ClassLoader returns a directory listing in some cases. // As this listing is partial, it is of little value in the context // of the CLAP client, so we have to ignore them. if (url != null) { if (url.getProtocol().equals("file")) { File file = new File(url.getFile()); modificationDate = new Date(file.lastModified()); if (file.isDirectory()) { url = null; } } } if (url != null) { try { Representation output = new InputRepresentation(url .openStream(), metadataService .getDefaultMediaType()); output.setLocationRef(request.getResourceRef()); output.setModificationDate(modificationDate); // Update the expiration date long timeToLive = getTimeToLive(); if (timeToLive == 0) { output.setExpirationDate(null); } else if (timeToLive > 0) { output.setExpirationDate(new Date(System .currentTimeMillis() + (1000L * timeToLive))); } // Update the metadata based on file extensions String name = path.substring(path.lastIndexOf('/') + 1); Entity.updateMetadata(name, output, true, getMetadataService()); // Update the response response.setEntity(output); response.setStatus(Status.SUCCESS_OK); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to open the representation's input stream", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL); } } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); } } @Override protected void handleLocal(Request request, Response response, String decodedPath) { String scheme = request.getResourceRef().getScheme(); if (scheme.equalsIgnoreCase(Protocol.CLAP.getSchemeName())) { LocalReference cr = new LocalReference(request.getResourceRef()); ClassLoader classLoader = null; if ((cr.getClapAuthorityType() == LocalReference.CLAP_CLASS) || (cr.getClapAuthorityType() == LocalReference.CLAP_DEFAULT)) { // Sometimes, a specific class loader needs to be used, // make sure that it can be provided as a request's attribute Object classLoaderAttribute = request.getAttributes().get( "org.restlet.clap.classLoader"); if (classLoaderAttribute != null) { classLoader = (ClassLoader) classLoaderAttribute; } else { // Old name to be deprecated classLoaderAttribute = request.getAttributes().get( "org.restlet.clap.classloader"); if (classLoaderAttribute != null) { classLoader = (ClassLoader) classLoaderAttribute; } else { classLoader = getClass().getClassLoader(); } } } else if (cr.getClapAuthorityType() == LocalReference.CLAP_SYSTEM) { classLoader = ClassLoader.getSystemClassLoader(); } else if (cr.getClapAuthorityType() == LocalReference.CLAP_THREAD) { classLoader = Thread.currentThread().getContextClassLoader(); } handleClassLoader(request, response, classLoader); } else { throw new IllegalArgumentException( "Protocol \"" + scheme + "\" not supported by the connector. Only CLAP is supported."); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/ZipClientHelper.java0000664000175000017500000003336011757206346027527 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.LocalReference; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.ReferenceList; import org.restlet.data.Status; import org.restlet.engine.io.BioUtils; import org.restlet.representation.Representation; import org.restlet.service.MetadataService; /** * ZIP and JAR client connector. Only works for archives available as local * files.
    *
    * Handles GET, HEAD and PUT request on resources referenced as : * zip:file:// * * @author Remi Dewitte */ public class ZipClientHelper extends LocalClientHelper { /** * Constructor. * * @param client * The helped client. */ public ZipClientHelper(Client client) { super(client); getProtocols().add(Protocol.ZIP); getProtocols().add(Protocol.JAR); } /** * Handles a call for a local entity. By default, only GET and HEAD methods * are implemented. * * @param request * The request to handle. * @param response * The response to update. * @param decodedPath * The URL decoded entity path. */ @Override protected void handleLocal(Request request, Response response, String decodedPath) { int spi = decodedPath.indexOf("!/"); String fileUri; String entryName; if (spi != -1) { fileUri = decodedPath.substring(0, spi); entryName = decodedPath.substring(spi + 2); } else { fileUri = decodedPath; entryName = ""; } LocalReference fileRef = new LocalReference(fileUri); if (Protocol.FILE.equals(fileRef.getSchemeProtocol())) { final File file = fileRef.getFile(); if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) { handleGet(request, response, file, entryName, getMetadataService()); } else if (Method.PUT.equals(request.getMethod())) { handlePut(request, response, file, entryName); } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); response.getAllowedMethods().add(Method.PUT); } } else { response.setStatus(Status.SERVER_ERROR_NOT_IMPLEMENTED, "Only works on local files."); } } /** * Handles a GET call. * * @param request * The request to answer. * @param response * The response to update. * @param file * The Zip archive file. * @param entryName * The Zip archive entry name. * @param metadataService * The metadata service. */ protected void handleGet(Request request, Response response, File file, String entryName, final MetadataService metadataService) { if (!file.exists()) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { ZipFile zipFile; try { zipFile = new ZipFile(file); } catch (Exception e) { response.setStatus(Status.SERVER_ERROR_INTERNAL, e); return; } Entity entity = new ZipEntryEntity(zipFile, entryName, metadataService); if (!entity.exists()) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { final Representation output; if (entity.isDirectory()) { // Return the directory listing final Collection children = entity.getChildren(); final ReferenceList rl = new ReferenceList(children.size()); String fileUri = LocalReference.createFileReference(file) .toString(); String scheme = request.getResourceRef().getScheme(); String baseUri = scheme + ":" + fileUri + "!/"; for (final Entity entry : children) { rl.add(baseUri + entry.getName()); } output = rl.getTextRepresentation(); try { zipFile.close(); } catch (IOException e) { // Do something ??? } } else { // Return the file content output = entity.getRepresentation(metadataService .getDefaultMediaType(), getTimeToLive()); output.setLocationRef(request.getResourceRef()); Entity.updateMetadata(entity.getName(), output, true, getMetadataService()); } response.setStatus(Status.SUCCESS_OK); response.setEntity(output); } } } /** * Handles a PUT call. * * @param request * The request to answer. * @param response * The response to update. * @param file * The Zip archive file. * @param entryName * The Zip archive entry name. */ protected void handlePut(Request request, Response response, File file, String entryName) { boolean zipExists = file.exists(); ZipOutputStream zipOut = null; if ("".equals(entryName) && request.getEntity() != null && request.getEntity().getDisposition() != null) { entryName = request.getEntity().getDisposition().getFilename(); } if (entryName == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Must specify an entry name."); return; } // boolean canAppend = true; boolean canAppend = !zipExists; boolean isDirectory = entryName.endsWith("/"); boolean wrongReplace = false; try { if (zipExists) { ZipFile zipFile = new ZipFile(file); // Already exists ? canAppend &= null == zipFile.getEntry(entryName); // Directory with the same name ? if (isDirectory) { wrongReplace = null != zipFile.getEntry(entryName .substring(0, entryName.length() - 1)); } else { wrongReplace = null != zipFile.getEntry(entryName + "/"); } canAppend &= !wrongReplace; zipFile.close(); } Representation entity; if (isDirectory) { entity = null; } else { entity = request.getEntity(); } if (canAppend) { try { // zipOut = new ZipOutputStream(new BufferedOutputStream(new // FileOutputStream(file, true))); zipOut = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(file))); writeEntityStream(entity, zipOut, entryName); zipOut.close(); } catch (Exception e) { response.setStatus(Status.SERVER_ERROR_INTERNAL, e); return; } finally { if (zipOut != null) zipOut.close(); } response.setStatus(Status.SUCCESS_CREATED); } else { if (wrongReplace) { response .setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Directory cannot be replace by a file or file by a directory."); } else { File writeTo = null; ZipFile zipFile = null; try { writeTo = File.createTempFile("restlet_zip_", "zip"); zipFile = new ZipFile(file); zipOut = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(writeTo))); Enumeration entries = zipFile .entries(); boolean replaced = false; while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (!replaced && entryName.equals(e.getName())) { writeEntityStream(entity, zipOut, entryName); replaced = true; } else { zipOut.putNextEntry(e); BioUtils.copy(new BufferedInputStream(zipFile .getInputStream(e)), zipOut); zipOut.closeEntry(); } } if (!replaced) { writeEntityStream(entity, zipOut, entryName); } zipFile.close(); zipOut.close(); } finally { try { if (zipFile != null) zipFile.close(); } finally { if (zipOut != null) zipOut.close(); } } if (!(BioUtils.delete(file) && writeTo.renameTo(file))) { if (!file.exists()) file.createNewFile(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(writeTo); fos = new FileOutputStream(file); // ByteUtils.write(fis.getChannel(), // fos.getChannel()); BioUtils.copy(fis, fos); response.setStatus(Status.SUCCESS_OK); } finally { try { if (fis != null) fis.close(); } finally { if (fos != null) fos.close(); } } } else { response.setStatus(Status.SUCCESS_OK); } } } } catch (Exception e) { response.setStatus(Status.SERVER_ERROR_INTERNAL, e); return; } } /** * Writes an entity to a given ZIP output stream with a given ZIP entry * name. * * @param entity * The entity to write. * @param out * The ZIP output stream. * @param entryName * The ZIP entry name. * @return True if the writing was successful. * @throws IOException */ private boolean writeEntityStream(Representation entity, ZipOutputStream out, String entryName) throws IOException { if (entity != null && !entryName.endsWith("/")) { ZipEntry entry = new ZipEntry(entryName); if (entity.getModificationDate() != null) entry.setTime(entity.getModificationDate().getTime()); else { entry.setTime(System.currentTimeMillis()); } out.putNextEntry(entry); BioUtils.copy(new BufferedInputStream(entity.getStream()), out); out.closeEntry(); return true; } out.putNextEntry(new ZipEntry(entryName)); out.closeEntry(); return false; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/EntityClientHelper.java0000664000175000017500000002740311757206350030235 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.util.Collection; import java.util.Iterator; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Reference; import org.restlet.data.ReferenceList; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.Variant; /** * Connector to the local entities. That connector supports the content * negotiation feature (i.e. for GET and HEAD methods) and implements the * response to GET/HEAD methods. * * @author Thierry Boileau */ public abstract class EntityClientHelper extends LocalClientHelper { /** * Constructor. * * @param client * The client to help. */ public EntityClientHelper(Client client) { super(client); } /** * Generate a Reference for a variant name (which is URL decoded) and handle * the translation between the incoming requested path (which is URL * encoded). * * @param scheme * The scheme of the requested resource. * @param encodedParentDirPath * The encoded path of the parent directory of the requested * resource. * @param encodedEntityName * The encoded name of the requested resource. * @param decodedVariantName * The decoded name of a returned resource. * @return A new Reference. */ public Reference createReference(String scheme, String encodedParentDirPath, String encodedEntityName, String decodedVariantName) { Reference result = new Reference(scheme + "://" + encodedParentDirPath + "/" + getReencodedVariantEntityName(encodedEntityName, decodedVariantName)); return result; } /** * Returns a local entity for the given path. * * @param path * The path of the entity. * @return A local entity for the given path. */ public abstract Entity getEntity(String path); /** * Percent-encodes the given percent-decoded variant name of a resource * whose percent-encoded name is given. Tries to match the longest common * part of both encoded entity name and decoded variant name. * * @param encodedEntityName * the percent-encoded name of the initial resource * @param decodedVariantEntityName * the percent-decoded entity name of a variant of the initial * resource. * @return The variant percent-encoded entity name. */ protected String getReencodedVariantEntityName(String encodedEntityName, String decodedVariantEntityName) { int i = 0; int j = 0; boolean stop = false; char[] encodeds = encodedEntityName.toCharArray(); char[] decodeds = decodedVariantEntityName.toCharArray(); for (i = 0; (i < decodeds.length) && (j < encodeds.length) && !stop; i++) { char decodedChar = decodeds[i]; char encodedChar = encodeds[j]; if (encodedChar == '%') { String dec = Reference.decode(encodedEntityName.substring(j, j + 3)); if (decodedChar == dec.charAt(0)) { j += 3; } else { stop = true; } } else if (decodedChar == encodedChar) { j++; } else { String dec = Reference.decode(encodedEntityName.substring(j, j + 1)); if (decodedChar == dec.charAt(0)) { j++; } else { stop = true; } } } if (stop) { return encodedEntityName.substring(0, j) + decodedVariantEntityName.substring(i - 1); } if (j == encodedEntityName.length()) { return encodedEntityName.substring(0, j) + decodedVariantEntityName.substring(i); } return encodedEntityName.substring(0, j); } /** * Handles a GET call. * * @param request * The request to answer. * @param response * The response to update. * @param entity * The requested entity (normal or directory). */ protected void handleEntityGet(Request request, Response response, Entity entity) { Representation output = null; // Get variants for a resource boolean found = false; Iterator> iterator = request.getClientInfo() .getAcceptedMediaTypes().iterator(); while (iterator.hasNext() && !found) { Preference pref = iterator.next(); found = pref.getMetadata().equals(MediaType.TEXT_URI_LIST); } if (found) { // Try to list all variants of this resource // 1- set up base name as the longest part of the name without known // extensions (beginning from the left) String baseName = entity.getBaseName(); // 2- looking for resources with the same base name Entity parent = entity.getParent(); if (parent != null) { Collection entities = parent.getChildren(); if (entities != null) { ReferenceList rl = new ReferenceList(entities.size()); String scheme = request.getResourceRef().getScheme(); String path = request.getResourceRef().getPath(); String encodedParentDirectoryURI = path.substring(0, path .lastIndexOf("/")); String encodedEntityName = path.substring(path .lastIndexOf("/") + 1); for (Entity entry : entities) { if (baseName.equals(entry.getBaseName())) { rl.add(createReference(scheme, encodedParentDirectoryURI, encodedEntityName, entry.getName())); } } output = rl.getTextRepresentation(); } } } else { if (entity.exists()) { if (entity.isDirectory()) { // Return the directory listing Collection children = entity.getChildren(); ReferenceList rl = new ReferenceList(children.size()); String directoryUri = request.getResourceRef() .getTargetRef().toString(); // Ensures that the directory URI ends with a slash if (!directoryUri.endsWith("/")) { directoryUri += "/"; } for (Entity entry : children) { if (entry.isDirectory()) { rl.add(directoryUri + Reference.encode(entry.getName()) + "/"); } else { rl.add(directoryUri + Reference.encode(entry.getName())); } } output = rl.getTextRepresentation(); } else { // Return the file content output = entity.getRepresentation(getMetadataService() .getDefaultMediaType(), getTimeToLive()); output.setLocationRef(request.getResourceRef()); Entity.updateMetadata(entity.getName(), output, true, getMetadataService()); } } else { // We look for the possible variant which has the same // metadata based on extensions (in a distinct order) and // default metadata. Entity uniqueVariant = null; // 1- set up base name as the longest part of the name without // known extensions (beginning from the left) String baseName = entity.getBaseName(); Variant entityVariant = entity.getVariant(); // 2- looking for resources with the same base name Entity parent = entity.getParent(); if (parent != null) { Collection files = parent.getChildren(); if (files != null) { for (Entity entry : files) { if (baseName.equals(entry.getBaseName())) { Variant entryVariant = entry.getVariant(); if (entityVariant.isCompatible(entryVariant)) { // The right representation has been found. uniqueVariant = entry; break; } } } } } if (uniqueVariant != null) { // Return the file content output = uniqueVariant.getRepresentation( getMetadataService().getDefaultMediaType(), getTimeToLive()); output.setLocationRef(request.getResourceRef()); Entity.updateMetadata(entity.getName(), output, true, getMetadataService()); } } } if (output == null) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { output.setLocationRef(request.getResourceRef()); response.setEntity(output); response.setStatus(Status.SUCCESS_OK); } } @Override protected void handleLocal(Request request, Response response, String decodedPath) { if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) { handleEntityGet(request, response, getEntity(decodedPath)); } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/Entity.java0000664000175000017500000003121711757206350025734 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.io.File; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.restlet.data.CharacterSet; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.service.MetadataService; /** * Represents a local entity, for example a regular file or a directory. * * @author Thierry Boileau * @author Jerome Louvel */ public abstract class Entity { /** * Return the base name that is to say the longest part of a given name * without known extensions (beginning from the left). * * @param name * The given name. * @param metadataService * Service that holds the known extensions. * @return The base name of this entity. */ public static String getBaseName(String name, MetadataService metadataService) { final String[] result = name.split("\\."); final StringBuilder baseName = new StringBuilder().append(result[0]); boolean extensionFound = false; for (int i = 1; (i < result.length) && !extensionFound; i++) { extensionFound = metadataService.getMetadata(result[i]) != null; if (!extensionFound) { baseName.append(".").append(result[i]); } } return baseName.toString(); } /** * Returns the list of known extensions taken from a given entity name. * * @param name * the given name. * @param metadataService * Service that holds the known extensions. * @return The list of known extensions taken from the entity name. */ public static Collection getExtensions(String name, MetadataService metadataService) { final Set result = new TreeSet(); final String[] tokens = name.split("\\."); boolean extensionFound = false; int i; for (i = 1; (i < tokens.length) && !extensionFound; i++) { extensionFound = metadataService.getMetadata(tokens[i]) != null; } if (extensionFound) { for (--i; (i < tokens.length); i++) { result.add(tokens[i]); } } return result; } /** * Returns the list of known extensions taken from a given variant. * * @param variant * the given variant. * @param metadataService * Service that holds the known extensions. * @return The list of known extensions taken from the variant. */ public static Collection getExtensions(Variant variant, MetadataService metadataService) { final Set result = new TreeSet(); String extension = metadataService.getExtension(variant .getCharacterSet()); if (extension != null) { result.add(extension); } extension = metadataService.getExtension(variant.getMediaType()); if (extension != null) { result.add(extension); } for (Language language : variant.getLanguages()) { extension = metadataService.getExtension(language); if (extension != null) { result.add(extension); } } for (Encoding encoding : variant.getEncodings()) { extension = metadataService.getExtension(encoding); if (extension != null) { result.add(extension); } } return result; } /** * Updates some variant metadata based on a given entry name with * extensions. * * @param entryName * The entry name with extensions. * @param variant * The variant to update. * @param applyDefault * Indicate if default metadata must be applied. * @param metadataService * The parent metadata service. */ public static void updateMetadata(String entryName, Variant variant, boolean applyDefault, MetadataService metadataService) { if (variant != null) { String[] tokens = entryName.split("\\."); Metadata current; // We found a potential variant for (int j = 1; j < tokens.length; j++) { current = metadataService.getMetadata(tokens[j]); if (current != null) { // Metadata extension detected if (current instanceof MediaType) { variant.setMediaType((MediaType) current); } else if (current instanceof CharacterSet) { variant.setCharacterSet((CharacterSet) current); } else if (current instanceof Encoding) { // Do we need to add this metadata? boolean found = false; for (int i = 0; !found && i < variant.getEncodings().size(); i++) { found = current.includes(variant.getEncodings() .get(i)); } if (!found) { variant.getEncodings().add((Encoding) current); } } else if (current instanceof Language) { // Do we need to add this metadata? boolean found = false; for (int i = 0; !found && i < variant.getLanguages().size(); i++) { found = current.includes(variant.getLanguages() .get(i)); } if (!found) { variant.getLanguages().add((Language) current); } } } final int dashIndex = tokens[j].indexOf('-'); if (dashIndex != -1) { // We found a language extension with a region area // specified. // Try to find a language matching the primary part of the // extension. final String primaryPart = tokens[j] .substring(0, dashIndex); current = metadataService.getMetadata(primaryPart); if (current instanceof Language) { variant.getLanguages().add((Language) current); } } } if (applyDefault) { // If no language is defined, take the default one if (variant.getLanguages().isEmpty()) { final Language defaultLanguage = metadataService .getDefaultLanguage(); if ((defaultLanguage != null) && !defaultLanguage.equals(Language.ALL)) { variant.getLanguages().add(defaultLanguage); } } // If no media type is defined, take the default one if (variant.getMediaType() == null) { final MediaType defaultMediaType = metadataService .getDefaultMediaType(); if ((defaultMediaType != null) && !defaultMediaType.equals(MediaType.ALL)) { variant.setMediaType(defaultMediaType); } } // If no encoding is defined, take the default one if (variant.getEncodings().isEmpty()) { final Encoding defaultEncoding = metadataService .getDefaultEncoding(); if ((defaultEncoding != null) && !defaultEncoding.equals(Encoding.ALL) && !defaultEncoding.equals(Encoding.IDENTITY)) { variant.getEncodings().add(defaultEncoding); } } // If no character set is defined, take the default one if (variant.getCharacterSet() == null) { final CharacterSet defaultCharacterSet = metadataService .getDefaultCharacterSet(); if ((defaultCharacterSet != null) && !defaultCharacterSet.equals(CharacterSet.ALL)) { variant.setCharacterSet(defaultCharacterSet); } } } } } /** The metadata service to use. */ private volatile MetadataService metadataService; /** * Constructor. * * @param metadataService * The metadata service to use. */ public Entity(MetadataService metadataService) { this.metadataService = metadataService; } /** * Indicates if the entity does exist. * * @return True if the entity does exists. */ public abstract boolean exists(); /** * Return the base name of this entity that is to say the longest part of * the name without known extensions (beginning from the left). * * @return The base name of this entity. */ public String getBaseName() { return getBaseName(getName(), getMetadataService()); } /** * Returns the list of contained entities if the current entity is a * directory, null otherwise. * * @return The list of contained entities. */ public abstract List getChildren(); /** * Returns the list of known extensions. * * @return The list of known extensions taken from the entity name. */ public Collection getExtensions() { return getExtensions(getName(), getMetadataService()); } /** * Returns the metadata service to use. * * @return The metadata service to use. */ public MetadataService getMetadataService() { return metadataService; } /** * Returns the name. * * @return The name. */ public abstract String getName(); /** * Returns the parent directory (if any). * * @return The parent directory, null otherwise. */ public abstract Entity getParent(); /** * Returns a representation of this local entity. * * @return A representation of this entity. */ public abstract Representation getRepresentation( MediaType defaultMediaType, int timeToLive); /** * Returns a variant corresponding to the extensions of this entity. * * @return A variant corresponding to the extensions of this entity. */ public Variant getVariant() { Variant result = new Variant(); updateMetadata(getName(), result, true, getMetadataService()); return result; } /** * Indicates if the entity is a directory. * * @return True if the entity is a directory. */ public abstract boolean isDirectory(); /** * Indicates if the entity is a normal entity, especially if it is not a * directory. * * @return True if the entity is a normal entity. * @see File#isFile() * @see File#isDirectory() */ public abstract boolean isNormal(); } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/ZipEntryRepresentation.java0000664000175000017500000000575011757206350031172 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.restlet.data.Disposition; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; import org.restlet.representation.StreamRepresentation; /** * An entry in a Zip/JAR file. * * It is very important {@link #release()} is called to close the underlying Zip * file. * * @author Remi Dewitte */ public class ZipEntryRepresentation extends StreamRepresentation { /** The Zip file. */ protected final ZipFile zipFile; /** The Zip entry. */ protected final ZipEntry entry; /** * Constructor. * * @param mediaType * The entry media type. * @param zipFile * The parent Zip archive file. * @param entry * The Zip entry. */ public ZipEntryRepresentation(MediaType mediaType, ZipFile zipFile, ZipEntry entry) { super(mediaType); this.zipFile = zipFile; this.entry = entry; Disposition disposition = new Disposition(); disposition.setFilename(entry.getName()); this.setDisposition(disposition); setSize(entry.getSize()); setModificationDate(new Date(entry.getTime())); } @Override public void release() { try { zipFile.close(); } catch (IOException e) { } } @Override public InputStream getStream() throws IOException { return zipFile.getInputStream(entry); } @Override public void write(OutputStream outputStream) throws IOException { BioUtils.copy(getStream(), outputStream); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/local/FileClientHelper.java0000664000175000017500000007166611757206346027657 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.local; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Range; import org.restlet.data.Status; import org.restlet.engine.io.BioUtils; import org.restlet.representation.Representation; import org.restlet.representation.Variant; /** * Connector to the file resources accessible. Here is the list of parameters * that are supported. They should be set in the Client's context before it is * started: * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    temporaryExtensionStringtmpThe name of the extension to use to store the temporary content while * uploading content via the PUT method.
    resumeUploadbooleanfalseIndicates if a failed upload can be resumed. This will prevent the * deletion of the temporary file created.
    * * @author Jerome Louvel * @author Thierry Boileau */ public class FileClientHelper extends EntityClientHelper { /** * Constructor. * * @param client * The client to help. */ public FileClientHelper(Client client) { super(client); getProtocols().add(Protocol.FILE); } /** * Check that all extensions of the file correspond to a known metadata. * * @param file * The file whose extensions are checked. * @return True if all extensions of the file are known by the metadata * service. */ protected boolean checkExtensionsConsistency(File file) { boolean knownExtension = true; Collection set = Entity.getExtensions(file.getName(), getMetadataService()); Iterator iterator = set.iterator(); while (iterator.hasNext() && knownExtension) { knownExtension = getMetadataService().getMetadata(iterator.next()) != null; } return knownExtension; } /** * Checks that the URI and the representation are compatible. The whole set * of metadata of the representation must be included in the set of those of * the URI * * @param fileName * The name of the resource * @param representation * The provided representation. * @return True if the metadata of the representation are compatible with * the metadata extracted from the filename */ private boolean checkMetadataConsistency(String fileName, Representation representation) { boolean result = true; if (representation != null) { Variant var = new Variant(); Entity.updateMetadata(fileName, var, true, getMetadataService()); // "var" contains the theoretical correct metadata if (!var.getLanguages().isEmpty() && !representation.getLanguages().isEmpty() && !var.getLanguages().containsAll( representation.getLanguages())) { result = false; } if ((var.getMediaType() != null) && (representation.getMediaType() != null) && !(var.getMediaType().includes(representation .getMediaType()))) { result = false; } if (!var.getEncodings().isEmpty() && !representation.getEncodings().isEmpty() && !var.getEncodings().containsAll( representation.getEncodings())) { result = false; } } return result; } @Override public Entity getEntity(String decodedPath) { // Take care of the file separator. return new FileEntity( new File(LocalReference.localizePath(decodedPath)), getMetadataService()); } /** * Returns the name of the extension to use to store the temporary content * while uploading content via the PUT method. Defaults to "tmp". * * @return The name of the extension to use to store the temporary content. */ public String getTemporaryExtension() { return getHelpedParameters().getFirstValue("temporaryExtension", "tmp"); } @Override protected void handleLocal(Request request, Response response, String decodedPath) { String scheme = request.getResourceRef().getScheme(); if (Protocol.FILE.getSchemeName().equalsIgnoreCase(scheme)) { handleFile(request, response, decodedPath); } else { throw new IllegalArgumentException( "Protocol \"" + scheme + "\" not supported by the connector. Only FILE is supported."); } } protected void handleFile(Request request, Response response, String decodedPath) { if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) { handleEntityGet(request, response, getEntity(decodedPath)); } else if (Method.PUT.equals(request.getMethod())) { handleFilePut(request, response, decodedPath, new File(decodedPath)); } else if (Method.DELETE.equals(request.getMethod())) { handleFileDelete(response, new File(decodedPath)); } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); response.getAllowedMethods().add(Method.PUT); response.getAllowedMethods().add(Method.DELETE); } } /** * Handles a DELETE call for the FILE protocol. * * @param response * The response to update. * @param file * The file or directory to delete. */ protected void handleFileDelete(Response response, File file) { if (file.isDirectory()) { if (file.listFiles().length == 0) { if (BioUtils.delete(file)) { response.setStatus(Status.SUCCESS_NO_CONTENT); } else { response.setStatus(Status.SERVER_ERROR_INTERNAL, "Couldn't delete the directory"); } } else { response.setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Couldn't delete the non-empty directory"); } } else { if (BioUtils.delete(file)) { response.setStatus(Status.SUCCESS_NO_CONTENT); } else { response.setStatus(Status.SERVER_ERROR_INTERNAL, "Couldn't delete the file"); } } } /** * Handles a PUT call for the FILE protocol. * * @param request * The request to update. * @param response * The response to update. * @param path * The encoded path of the requested file or directory. * @param file * The requested file or directory. */ protected void handleFilePut(Request request, Response response, String path, File file) { // Deals with directory boolean isDirectory = false; if (file.exists()) { if (file.isDirectory()) { isDirectory = true; response.setStatus(new Status(Status.CLIENT_ERROR_FORBIDDEN, "Can't put a new representation of a directory")); return; } } else { // No existing file or directory found if (path.endsWith("/")) { isDirectory = true; // Create a new directory and its parents if necessary if (file.mkdirs()) { response.setStatus(Status.SUCCESS_NO_CONTENT); } else { getLogger().log(Level.WARNING, "Unable to create the new directory"); response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL, "Unable to create the new directory")); } return; } } if (!isDirectory) { // Several checks : first the consistency of the metadata and the // filename boolean partialPut = !request.getRanges().isEmpty(); if (!checkMetadataConsistency(file.getName(), request.getEntity())) { // ask the client to reiterate properly its request response.setStatus(new Status(Status.REDIRECTION_SEE_OTHER, "The metadata are not consistent with the URI")); return; } // We look for the possible variants // Set up base name as the longest part of the name without known // extensions (beginning from the left) final String baseName = Entity.getBaseName(file.getName(), getMetadataService()); // Look for resources with the same base name FileFilter filter = new FileFilter() { public boolean accept(File file) { return file.isFile() && baseName.equals(Entity.getBaseName(file .getName(), getMetadataService())); } }; File[] files = file.getParentFile().listFiles(filter); File uniqueVariant = null; List variantsList = new ArrayList(); if (files != null && files.length > 0) { // Set the list of extensions, due to the file name and the // default metadata. // TODO It seems we may handle more clearly the equivalence // between the file name space and the target resource (URI // completed by default metadata) Variant variant = new Variant(); Entity.updateMetadata(file.getName(), variant, true, getMetadataService()); Collection extensions = Entity.getExtensions(variant, getMetadataService()); for (File entry : files) { Collection entryExtensions = Entity.getExtensions( entry.getName(), getMetadataService()); if (entryExtensions.containsAll(extensions)) { variantsList.add(entry); if (extensions.containsAll(entryExtensions)) { // The right representation has been found. uniqueVariant = entry; } } } } if (uniqueVariant != null) { file = uniqueVariant; } else { if (!variantsList.isEmpty()) { // Negotiated resource (several variants, but not the right // one). Check if the request could be completed or not. // The request could be more precise response .setStatus(new Status( Status.CLIENT_ERROR_NOT_ACCEPTABLE, "Unable to process properly the request. Several variants exist but none of them suits precisely.")); return; } // This resource does not exist, yet. Complete it with the // default metadata Entity.updateMetadata(file.getName(), request.getEntity(), true, getMetadataService()); // Update the URI StringBuilder fileName = new StringBuilder(baseName); updateFileExtension(fileName, request.getEntity() .getMediaType()); for (Language language : request.getEntity().getLanguages()) { updateFileExtension(fileName, language); } for (Encoding encoding : request.getEntity().getEncodings()) { updateFileExtension(fileName, encoding); } file = new File(file.getParentFile(), fileName.toString()); } // Before putting the file representation, we check that all the // extensions are known if (!checkExtensionsConsistency(file)) { response .setStatus(new Status( Status.SERVER_ERROR_INTERNAL, "Unable to process properly the URI. At least one extension is not known by the server.")); return; } File tmp = null; boolean error = false; if (file.exists()) { // The PUT call is handled in two phases: // 1- write a temporary file // 2- rename the target file if (partialPut) { RandomAccessFile raf = null; // Replace the content of the file. First, create a // temporary file try { // The temporary file used for partial PUT. tmp = new File(file.getCanonicalPath() + "." + getTemporaryExtension()); // Support only one range. Range range = request.getRanges().get(0); if (tmp.exists() && !isResumeUpload()) { BioUtils.delete(tmp); } if (!tmp.exists()) { // Copy the target file. InputStream in = new FileInputStream(file); OutputStream out = new FileOutputStream(tmp); BioUtils.copy(in, out); out.flush(); out.close(); } raf = new RandomAccessFile(tmp, "rwd"); // Go to the desired offset. if (range.getIndex() == Range.INDEX_LAST) { if (raf.length() <= range.getSize()) { raf.seek(range.getSize()); } else { raf.seek(raf.length() - range.getSize()); } } else { raf.seek(range.getIndex()); } // Write the entity to the temporary file. if (request.isEntityAvailable()) { BioUtils.copy(request.getEntity().getStream(), raf); } } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to create the temporary file", ioe); response.setStatus(new Status( Status.SERVER_ERROR_INTERNAL, "Unable to create a temporary file")); error = true; } finally { try { if (raf != null) { raf.close(); } } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to close the temporary file", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); error = true; } } } else { FileOutputStream fos = null; try { tmp = File.createTempFile("restlet-upload", "bin"); if (request.isEntityAvailable()) { fos = new FileOutputStream(tmp); BioUtils.copy(request.getEntity().getStream(), fos); } } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to create the temporary file", ioe); response.setStatus(new Status( Status.SERVER_ERROR_INTERNAL, "Unable to create a temporary file")); error = true; } finally { try { if (fos != null) { fos.close(); } } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to close the temporary file", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); error = true; } } } if (error) { if (tmp.exists() && !isResumeUpload()) { BioUtils.delete(tmp); } return; } // Then delete the existing file if (tmp.exists() && BioUtils.delete(file)) { // Finally move the temporary file to the existing file // location boolean renameSuccessful = false; if (tmp.renameTo(file)) { if (request.getEntity() == null) { response.setStatus(Status.SUCCESS_NO_CONTENT); } else { response.setStatus(Status.SUCCESS_OK); } renameSuccessful = true; } else { // Many aspects of the behavior of the method "renameTo" // are inherently platform-dependent: the rename // operation might not be able to move a file from one // file system to another. if (tmp.exists()) { try { InputStream in = new FileInputStream(tmp); OutputStream out = new FileOutputStream(file); BioUtils.copy(in, out); out.close(); renameSuccessful = true; BioUtils.delete(tmp); } catch (Exception e) { renameSuccessful = false; } } if (!renameSuccessful) { getLogger() .log(Level.WARNING, "Unable to move the temporary file to replace the existing file"); response .setStatus(new Status( Status.SERVER_ERROR_INTERNAL, "Unable to move the temporary file to replace the existing file")); } } } else { getLogger().log(Level.WARNING, "Unable to delete the existing file"); response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL, "Unable to delete the existing file")); if (tmp.exists() && !isResumeUpload()) { BioUtils.delete(tmp); } } } else { // The file does not exist yet. File parent = file.getParentFile(); if ((parent != null) && !parent.exists()) { // Create the parent directories then the new file if (!parent.mkdirs()) { getLogger().log(Level.WARNING, "Unable to create the parent directory"); response.setStatus(new Status( Status.SERVER_ERROR_INTERNAL, "Unable to create the parent directory")); } } // Create the new file if (partialPut) { // This is a partial PUT RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "rwd"); // Support only one range. Range range = request.getRanges().get(0); // Go to the desired offset. if (range.getIndex() == Range.INDEX_LAST) { if (raf.length() <= range.getSize()) { raf.seek(range.getSize()); } else { raf.seek(raf.length() - range.getSize()); } } else { raf.seek(range.getIndex()); } // Write the entity to the file. if (request.isEntityAvailable()) { BioUtils.copy(request.getEntity().getStream(), raf); } } catch (FileNotFoundException fnfe) { getLogger().log(Level.WARNING, "Unable to create the new file", fnfe); response.setStatus(Status.SERVER_ERROR_INTERNAL, fnfe); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to create the new file", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); } finally { try { if (raf != null) { raf.close(); } } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to close the new file", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); } } } else { // This is simple PUT of the full entity FileOutputStream fos = null; try { if (file.createNewFile()) { if (request.getEntity() == null) { response.setStatus(Status.SUCCESS_NO_CONTENT); } else { fos = new FileOutputStream(file); BioUtils.copy(request.getEntity().getStream(), fos); response.setStatus(Status.SUCCESS_CREATED); } } else { getLogger().log(Level.WARNING, "Unable to create the new file"); response.setStatus(new Status( Status.SERVER_ERROR_INTERNAL, "Unable to create the new file")); } } catch (FileNotFoundException fnfe) { getLogger().log(Level.WARNING, "Unable to create the new file", fnfe); response.setStatus(Status.SERVER_ERROR_INTERNAL, fnfe); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to create the new file", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to close the new file", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); } } } } } } /** * Indicates if a failed upload can be resumed. This will prevent the * deletion of the temporary file created. Defaults to "false". * * @return True if a failed upload can be resumed, false otherwise. */ public boolean isResumeUpload() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "resumeUpload", "false")); } /** * Complete the given file name with the extension corresponding to the * given metadata. * * @param fileName * The file name to complete. * @param metadata * The metadata. */ private void updateFileExtension(StringBuilder fileName, Metadata metadata) { boolean defaultMetadata = true; if (getMetadataService() != null) { if (metadata instanceof Language) { Language language = (Language) metadata; defaultMetadata = language.equals(getMetadataService() .getDefaultLanguage()); } else if (metadata instanceof MediaType) { MediaType mediaType = (MediaType) metadata; defaultMetadata = mediaType.equals(getMetadataService() .getDefaultMediaType()); } else if (metadata instanceof CharacterSet) { CharacterSet characterSet = (CharacterSet) metadata; defaultMetadata = characterSet.equals(getMetadataService() .getDefaultCharacterSet()); } else if (metadata instanceof Encoding) { Encoding encoding = (Encoding) metadata; defaultMetadata = encoding.equals(getMetadataService() .getDefaultEncoding()); } } // We only add extension for metadata that differs from default ones if (!defaultMetadata) { String extension = getMetadataService().getExtension(metadata); if (extension != null) { fileName.append("." + extension); } else { if (metadata.getParent() != null) { updateFileExtension(fileName, metadata.getParent()); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/0000775000175000017500000000000011757206350023474 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/util/CookieSettingSeries.java0000664000175000017500000000416711757206350030271 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.List; import org.restlet.data.CookieSetting; import org.restlet.util.Series; /** * Cookie setting series. * * @author Jerome Louvel */ public class CookieSettingSeries extends Series { /** * Constructor. */ public CookieSettingSeries() { super(); } /** * Constructor. * * @param delegate * The delegate list. */ public CookieSettingSeries(List delegate) { super(delegate); } @Override public CookieSetting createEntry(String name, String value) { return new CookieSetting(name, value); } @Override public Series createSeries(List delegate) { if (delegate != null) { return new CookieSettingSeries(delegate); } return new CookieSettingSeries(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/AlphaNumericComparator.java0000664000175000017500000001116411757206350030742 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; /** * Optimized public-domain implementation of a Java alphanumeric sort. *

    * * This implementation uses a single comparison pass over the characters in a * CharSequence, and returns as soon as a differing character is found, unless * the difference occurs in a series of numeric characters, in which case that * series is followed to its end. Numeric series of equal length are compared * numerically, that is, according to the most significant (leftmost) differing * digit. Series of unequal length are compared by their length. *

    * * This implementation appears to be 2-5 times faster than alphanumeric * comparators based based on substring analysis, with a lighter memory * footprint. *

    * * This alphanumeric comparator has approximately 20%-50% the performance of the * lexical String.compareTo() operation. Character sequences without numeric * data are compared more quickly. *

    * * Dedicated to the public domain by the original author: * http://creativecommons.org/licenses/publicdomain/ * * @author Rob Heittman, Solertium * Corporation */ public class AlphaNumericComparator extends AlphabeticalComparator { private static final long serialVersionUID = 1L; @Override public int compare(final String uri0, final String uri1) { int ptr = 0; int msd = 0; int diff = 0; char a, b; final int llength = uri0.length(); final int rlength = uri1.length(); final int min; if (rlength < llength) { min = rlength; } else { min = llength; } boolean rAtEnd, rHasNoMoreDigits; while (ptr < min) { a = uri0.charAt(ptr); b = uri1.charAt(ptr); diff = a - b; if ((a > '9') || (b > '9') || (a < '0') || (b < '0')) { if (diff != 0) { return diff; } msd = 0; } else { if (msd == 0) { msd = diff; } rAtEnd = rlength - ptr < 2; if (llength - ptr < 2) { if (rAtEnd) { return msd; } if (!isNotDigit(a) && !isNotDigit(b)) return diff; return -1; } if (rAtEnd) { if (!isNotDigit(a) && !isNotDigit(b)) return diff; return -1; } rHasNoMoreDigits = isNotDigit(uri1.charAt(ptr + 1)); if (isNotDigit(uri0.charAt(ptr + 1))) { if (rHasNoMoreDigits && (msd != 0)) { return msd; } if (!rHasNoMoreDigits) { return -1; } } else { if (rHasNoMoreDigits) { return 1; } } } ptr++; } return llength - rlength; } /** * Indicates if the character is a digit. * * @param x * The character to test. * @return True if the character is a digit. */ protected boolean isNotDigit(final char x) { return (x > '9') || (x < '0'); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/Pool.java0000664000175000017500000000744711757206346025271 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * Generic object pool. * * @author Jerome Louvel * * @param */ public abstract class Pool { /** Store of reusable objects. */ private final Queue store; /** * Default constructor. */ public Pool() { this.store = createStore(); } /** * Constructor. Pre-creates the minimum number of objects if needed using * the {@link #preCreate(int)} method. * * @param initialSize * The initial number of objects in the pool. */ public Pool(int initialSize) { this(); preCreate(initialSize); } /** * Checks in an object into the pool. * * @param object * The object to check in. */ public void checkin(T object) { if (object != null) { clear(object); this.store.offer(object); } } /** * Checks out an object from the pool. Creates a new one if the pool is * empty. * * @return An object from the pool. */ public T checkout() { T result; if ((result = this.store.poll()) == null) { result = createObject(); } return result; } /** * Clears the store of reusable objects. */ public void clear() { getStore().clear(); } /** * Clears the given object when it is checked in the pool. Does nothing by * default. * * @param object * The object to clear. */ protected void clear(T object) { } /** * Creates a new reusable object. * * @return A new reusable object. */ protected abstract T createObject(); /** * Creates the store of reusable objects. * * @return The store of reusable objects. */ protected Queue createStore() { return new ConcurrentLinkedQueue(); } /** * Returns the store containing the reusable objects. * * @return The store containing the reusable objects. */ protected Queue getStore() { return store; } /** * Pre-creates the initial objects using the {@link #createObject()} method * and check them in the pool using the {@link #checkin(Object)} method. * * @param initialSize * The initial number of objects. */ public void preCreate(int initialSize) { for (int i = 0; i < initialSize; i++) { checkin(createObject()); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/SystemUtils.java0000664000175000017500000001030011757206346026643 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; /** * System utilities. * * @author Jerome Louvel */ public class SystemUtils { /** * Parses the "java.version" system property and returns the first digit of * the version number of the Java Runtime Environment (e.g. "1" for * "1.3.0"). * * @see Official * Java versioning * @return The major version number of the Java Runtime Environment. */ public static int getJavaMajorVersion() { int result; final String javaVersion = System.getProperty("java.version"); try { result = Integer.parseInt(javaVersion.substring(0, javaVersion .indexOf("."))); } catch (Exception e) { result = 0; } return result; } /** * Parses the "java.version" system property and returns the second digit of * the version number of the Java Runtime Environment (e.g. "3" for * "1.3.0"). * * @see Official * Java versioning * @return The minor version number of the Java Runtime Environment. */ public static int getJavaMinorVersion() { int result; final String javaVersion = System.getProperty("java.version"); try { result = Integer.parseInt(javaVersion.split("\\.")[1]); } catch (Exception e) { result = 0; } return result; } /** * Parses the "java.version" system property and returns the update release * number of the Java Runtime Environment (e.g. "10" for "1.3.0_10"). * * @see Official * Java versioning * @return The release number of the Java Runtime Environment or 0 if it * does not exist. */ public static int getJavaUpdateVersion() { int result; final String javaVersion = System.getProperty("java.version"); try { result = Integer.parseInt(javaVersion.substring(javaVersion .indexOf('_') + 1)); } catch (Exception e) { result = 0; } return result; } /** * Computes the hash code of a set of objects. Follows the algorithm * specified in List.hasCode(). * * @param objects * the objects to compute the hashCode * * @return The hash code of a set of objects. */ public static int hashCode(Object... objects) { int result = 1; if (objects != null) { for (final Object obj : objects) { result = 31 * result + (obj == null ? 0 : obj.hashCode()); } } return result; } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private SystemUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/EngineClassLoader.java0000664000175000017500000001253311757206346027672 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.Vector; import org.restlet.engine.Edition; import org.restlet.engine.Engine; /** * Flexible engine class loader. Uses the current class's class loader as its * parent. Can also check with the user class loader defined by * {@link Engine#getUserClassLoader()} or with * {@link Thread#getContextClassLoader()} or with {@link Class#forName(String)}. * * @author Jerome Louvel */ public class EngineClassLoader extends ClassLoader { /** The parent Restlet engine. */ private final Engine engine; /** * Constructor. */ public EngineClassLoader(Engine engine) { super(EngineClassLoader.class.getClassLoader()); this.engine = engine; } @Override protected Class findClass(String name) throws ClassNotFoundException { Class result = null; // First try the user class loader ClassLoader cl = getEngine().getUserClassLoader(); if (cl != null) { try { result = cl.loadClass(name); } catch (ClassNotFoundException cnfe) { // Ignore } } // Then try the current thread's class loader if (result == null) { cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { try { result = cl.loadClass(name); } catch (ClassNotFoundException cnfe) { // Ignore } } } // Finally try with this ultimate approach if (result == null) { try { result = Class.forName(name); } catch (ClassNotFoundException cnfe) { // Ignore } } // Otherwise throw an exception if (result == null) { throw new ClassNotFoundException(name); } return result; } @Override protected URL findResource(String name) { URL result = null; // First try the user class loader ClassLoader cl = getEngine().getUserClassLoader(); if (cl != null) { result = cl.getResource(name); } // Then try the current thread's class loader if (result == null) { cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { result = cl.getResource(name); } } return result; } @Override protected Enumeration findResources(String name) throws IOException { Enumeration result = null; // First try the user class loader ClassLoader cl = getEngine().getUserClassLoader(); if (cl != null) { result = cl.getResources(name); } // Then try the current thread's class loader if (result == null) { cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { result = cl.getResources(name); } } return result; } /** * Returns the parent Restlet engine. * * @return The parent Restlet engine. */ protected Engine getEngine() { return engine; } @Override public Enumeration getResources(String name) throws IOException { Enumeration allUrls = super.getResources(name); Vector result = new Vector(); if (allUrls != null) { try { URL url; while (allUrls.hasMoreElements()) { url = allUrls.nextElement(); if (result.indexOf(url) == -1) { result.add(url); } } } catch (NullPointerException e) { // At this time (june 2009) a NPE is thrown with Dalvik JVM. // Let's throw the NPE for the other editions. if (Edition.CURRENT != Edition.ANDROID) { throw e; } } } return result.elements(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/MapResolver.java0000664000175000017500000000351011757206350026575 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.Map; import org.restlet.util.Resolver; /** * Resolves variable values based on a map. * * @author Jerome Louvel */ public class MapResolver extends Resolver { /** The variables to use when formatting. */ private final Map map; /** * Constructor. * * @param map * The variables to use when formatting. */ public MapResolver(Map map) { this.map = map; } @Override public Object resolve(String variableName) { return this.map.get(variableName); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/InternetDateFormat.java0000664000175000017500000004015111757206350030077 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.ParsePosition; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class handles Internet date/time strings in accordance with RFC 3339. It * provides static methods to convert from various Java constructs (long, Date, * and Calendar) to RFC 3339 format strings and to parse these strings back into * the same Java constructs. *

    * In addition to the static utility methods, this class also wraps a Calendar * object allowing this class to be used as a value object in place of a Java * construct. *

    * Strings are parsed in accordance with the RFC 3339 format: * *

     * YYYY-MM-DD(T|t|\s)hh:mm:ss[.ddd][tzd]
     * 
    * * The tzd represents the time zone designator and is either an * upper or lower case 'Z' indicating UTC or a signed hh:mm offset. * * @author Frank Hellwig (frank@hellwig.org) */ public class InternetDateFormat extends DateFormat { private static volatile DecimalFormat df2 = new DecimalFormat("00"); private static volatile DecimalFormat df4 = new DecimalFormat("0000"); /** The Regex pattern to match. */ private static volatile Pattern pattern; private static final long serialVersionUID = 1L; /** * A time zone with zero offset and no DST. */ public static final TimeZone UTC = new SimpleTimeZone(0, "Z"); static { String reDate = "(\\d{4})-(\\d{2})-(\\d{2})"; String reTime = "(\\d{2}):(\\d{2}):(\\d{2})(\\.\\d+)?"; String reZone = "(?:([zZ])|(?:(\\+|\\-)(\\d{2}):(\\d{2})))"; String re = reDate + "[tT\\s]" + reTime + reZone; pattern = Pattern.compile(re); } /** * Returns the current date and time as an RFC 3339 date/time string using * the UTC (Z) time zone. * * @return an RFC 3339 date/time string (does not include milliseconds) */ public static String now() { return now(UTC); } /** * Returns the current date and time as an RFC 3339 date/time string using * the specified time zone. * * @param zone * the time zone to use * @return an RFC 3339 date/time string (does not include milliseconds) */ public static String now(TimeZone zone) { return toString(System.currentTimeMillis(), zone); } /** * Our private parse utility that parses the string, clears the calendar, * and then sets the fields. * * @param s * the string to parse * @param cal * the calendar object to populate * @throws IllegalArgumentException * if the string is not a valid RFC 3339 date/time string */ private static void parse(String s, Calendar cal) { Matcher m = pattern.matcher(s); if (!m.matches()) { throw new IllegalArgumentException("Invalid date/time: " + s); } cal.clear(); cal.set(Calendar.YEAR, Integer.parseInt(m.group(1))); cal.set(Calendar.MONTH, Integer.parseInt(m.group(2)) - 1); cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(m.group(3))); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(4))); cal.set(Calendar.MINUTE, Integer.parseInt(m.group(5))); cal.set(Calendar.SECOND, Integer.parseInt(m.group(6))); if (m.group(7) != null) { float fraction = Float.parseFloat(m.group(7)); cal.set(Calendar.MILLISECOND, (int) (fraction * 1000F)); } if (m.group(8) != null) { cal.setTimeZone(new SimpleTimeZone(0, "Z")); } else { int sign = m.group(9).equals("-") ? -1 : 1; int tzhour; tzhour = Integer.parseInt(m.group(10)); int tzminute = Integer.parseInt(m.group(11)); int offset = sign * ((tzhour * 60) + tzminute); String id = Integer.toString(offset); cal.setTimeZone(new SimpleTimeZone(offset * 60000, id)); } } /** * Parses an RFC 3339 date/time string to a Calendar object. * * @param s * the string to parse * @return the Calendar object * @throws IllegalArgumentException * if the string is not a valid RFC 3339 date/time string */ public static Calendar parseCalendar(String s) { Calendar cal = new GregorianCalendar(); parse(s, cal); return cal; } /** * Parses an RFC 3339 date/time string to a Date object. * * @param s * the string to parse * @return the Date object * @throws IllegalArgumentException * if the string is not a valid RFC 3339 date/time string */ public static Date parseDate(String s) { Calendar cal = new GregorianCalendar(); parse(s, cal); return cal.getTime(); } /** * Parses an RFC 3339 date/time string to a millisecond time value. * * @param s * the string to parse * @return the millisecond time value * @throws IllegalArgumentException * if the string is not a valid RFC 3339 date/time string */ public static long parseTime(String s) { Calendar cal = new GregorianCalendar(); parse(s, cal); return cal.getTimeInMillis(); } /** * Converts the specified Calendar object to an RFC 3339 date/time string. * Unlike the toString methods for Date and long, no additional variant of * this method taking a time zone is provided since the time zone is built * into the Calendar object. * * @param cal * the Calendar object * @return an RFC 3339 date/time string (does not include milliseconds) */ public static String toString(Calendar cal) { StringBuilder buf = new StringBuilder(); buf.append(df4.format(cal.get(Calendar.YEAR))); buf.append("-"); buf.append(df2.format(cal.get(Calendar.MONTH) + 1)); buf.append("-"); buf.append(df2.format(cal.get(Calendar.DAY_OF_MONTH))); buf.append("T"); buf.append(df2.format(cal.get(Calendar.HOUR_OF_DAY))); buf.append(":"); buf.append(df2.format(cal.get(Calendar.MINUTE))); buf.append(":"); buf.append(df2.format(cal.get(Calendar.SECOND))); int ms = cal.get(Calendar.MILLISECOND); if (ms != 0) { buf.append(".").append((int) (ms / 10F)); } int tzminute = (cal.get(Calendar.ZONE_OFFSET) + cal .get(Calendar.DST_OFFSET)) / 60000; if (tzminute == 0) { buf.append("Z"); } else { if (tzminute < 0) { tzminute = -tzminute; buf.append("-"); } else { buf.append("+"); } int tzhour = tzminute / 60; tzminute -= tzhour * 60; buf.append(df2.format(tzhour)); buf.append(":"); buf.append(df2.format(tzminute)); } return buf.toString(); } /** * Converts the specified Date object to an RFC 3339 date/time string using * the UTC (Z) time zone. * * @param date * the Date object * @return an RFC 3339 date/time string (does not include milliseconds) */ public static String toString(Date date) { return toString(date, UTC); } /** * Converts the specified Date object to an RFC 3339 date/time string using * the specified time zone. * * @param date * the Date object * @param zone * the time zone to use * @return an RFC 3339 date/time string (does not include milliseconds) */ public static String toString(Date date, TimeZone zone) { InternetDateFormat dt = new InternetDateFormat(date, zone); return dt.toString(); } /** * Converts the specified millisecond time value to an RFC 3339 date/time * string using the UTC (Z) time zone. * * @param time * the millisecond time value * @return an RFC 3339 date/time string (does not include milliseconds) */ public static String toString(long time) { return toString(time, UTC); } /** * Converts the specified millisecond time value to an RFC 3339 date/time * string using the specified time zone. * * @param time * the millisecond time value * @param zone * the time zone to use * @return an RFC 3339 date/time string (does not include milliseconds) */ public static String toString(long time, TimeZone zone) { InternetDateFormat dt = new InternetDateFormat(time, zone); return dt.toString(); } /** * Creates a new InternetDateFormat object from the specified Date object * using the UTC (Z) time zone. * * @param date * the Date object * @return the InternetDateFormat object */ public static InternetDateFormat valueOf(Date date) { return new InternetDateFormat(date); } /** * Creates a new InternetDateFormat object from the specified Date object * using the specified time zone. * * @param date * the Date object * @param zone * the time zone to use * @return the InternetDateFormat object */ public static InternetDateFormat valueOf(Date date, TimeZone zone) { return new InternetDateFormat(date, zone); } /** * Creates a new InternetDateFormat object from the specified millisecond * time value using the UTC (Z) time zone. * * @param time * the millisecond time value * @return the InternetDateFormat object */ public static InternetDateFormat valueOf(long time) { return new InternetDateFormat(time); } /** * Creates a new InternetDateFormat object from the specified millisecond * time value using the specified time zone. * * @param time * the millisecond time value * @param zone * the time zone to use * @return the InternetDateFormat object */ public static InternetDateFormat valueOf(long time, TimeZone zone) { return new InternetDateFormat(time, zone); } /** * Creates a new InternetDateFormat object by parsing an RFC 3339 date/time * string. * * @param s * the string to parse * @return the InternetDateFormat object * @throws IllegalArgumentException * if the string is not a valid RFC 3339 date/time string */ public static InternetDateFormat valueOf(String s) { return new InternetDateFormat(s); } /** * The Calendar object that allows this class to act as a value holder. */ private Calendar cal; /** * Creates a new InternetDateFormat object set to the current time using the * UTC (Z) time zone. */ public InternetDateFormat() { this(UTC); } /** * Creates a new InternetDateFormat object initialized from a Calendar * object. The specified calendar object is cloned thereby isolating this * InternetDateFormat object from any changes made to the specified calendar * object after calling this constructor. * * @param cal * the Calendar object */ public InternetDateFormat(Calendar cal) { this.cal = (Calendar) cal.clone(); } /** * Creates a new InternetDateFormat object initialized from a Date object * using the UTC (Z) time zone. * * @param date * the Date object */ public InternetDateFormat(Date date) { this(date, UTC); } /** * Creates a new InternetDateFormat object initialized from a Date object * using the specified time zone. * * @param date * the Date object * @param zone * the time zone to use */ public InternetDateFormat(Date date, TimeZone zone) { cal = new GregorianCalendar(zone); cal.setTime(date); } /** * Creates a new InternetDateFormat object initialized from a millisecond * time value using the UTC (Z) time zone. * * @param time * the millisecond time value */ public InternetDateFormat(long time) { this(time, UTC); } /** * Creates a new InternetDateFormat object initialized from a millisecond * time value using the specified time zone. * * @param time * the millisecond time value * @param zone * the time zone to use */ public InternetDateFormat(long time, TimeZone zone) { cal = new GregorianCalendar(zone); cal.setTimeInMillis(time); } /** * Creates a new InternetDateFormat object by parsing an RFC 3339 date/time * string. * * @param s * the string to parse * @throws IllegalArgumentException * if the string is not a valid RFC 3339 date/time string */ public InternetDateFormat(String s) { cal = parseCalendar(s); } /** * Creates a new InternetDateFormat object set to the current time using the * specified time zone. * * @param zone * the time zone to use */ public InternetDateFormat(TimeZone zone) { cal = new GregorianCalendar(zone); } @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { return toAppendTo.append(valueOf(date)); } /** * Gets the Calendar object wrapped by this InternetDateFormat object. * * @return the cloned Calendar object */ public Calendar getCalendar() { return (Calendar) cal.clone(); } /** * Gets the value of this InternetDateFormat object as a Date object. * * @return the Date object */ public Date getDate() { return cal.getTime(); } /** * Gets the value of this InternetDateFormat object as millisecond time * value. * * @return the millisecond time value */ public long getTime() { return cal.getTimeInMillis(); } @Override public Date parse(String source) throws ParseException { return parse(source, (ParsePosition) null); } @Override public Date parse(String source, ParsePosition pos) { return parseDate(source); } /** * Converts this InternetDateFormat object to an RFC 3339 date/time string. * * @return an RFC 3339 date/time string (does not include milliseconds) */ public String toString() { return toString(cal); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/Base64.java0000664000175000017500000002201211757206346025365 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.Arrays; import org.restlet.engine.io.BioUtils; /** * Minimal but fast Base64 codec. * * @author Ray Waldin (ray@waldin.net) */ public class Base64 { /** alphabet used for encoding bytes into base64 */ private static final char[] BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray(); /** * Decoding involves replacing each character with the character's value, or * position, from the above alphabet, and this table makes such lookups * quick and easy. Couldn't help myself with the corny name :) */ private static final byte[] DECODER_RING = new byte[128]; /** * Initializes the decoder ring. */ static { Arrays.fill(DECODER_RING, (byte) -1); int i = 0; for (final char c : BASE64_DIGITS) { DECODER_RING[c] = (byte) i++; } DECODER_RING['='] = 0; } private final static int byteAt(byte[] data, int block, int off) { return unsign(data[(block * 3) + off]); } /** * Decodes base64 characters into bytes. Newline characters found at block * boundaries will be ignored. * * @param chars * The characters array to decode. * @return The decoded byte array. */ public static byte[] decode(final char[] chars) { // prepare to ignore newline chars int newlineCount = 0; for (final char c : chars) { switch (c) { case '\r': case '\n': newlineCount++; break; default: } } final int len = chars.length - newlineCount; if (len % 4 != 0) { throw new IllegalArgumentException( "Base64.decode() requires input length to be a multiple of 4"); } int numBytes = ((len + 3) / 4) * 3; // fix up length relative to padding if (len > 1) { if (chars[chars.length - 2] == '=') { numBytes -= 2; } else if (chars[chars.length - 1] == '=') { numBytes--; } } final byte[] result = new byte[numBytes]; int newlineOffset = 0; // decode each block of 4 chars into 3 bytes for (int i = 0; i < (len + 3) / 4; ++i) { int charOffset = newlineOffset + (i * 4); final char c1 = chars[charOffset++]; final char c2 = chars[charOffset++]; final char c3 = chars[charOffset++]; final char c4 = chars[charOffset++]; if (!(validChar(c1) && validChar(c2) && validChar(c3) && validChar(c4))) { throw new IllegalArgumentException( "Invalid Base64 character in block: '" + c1 + c2 + c3 + c4 + "'"); } // pack final int x = DECODER_RING[c1] << 18 | DECODER_RING[c2] << 12 | (c3 == '=' ? 0 : DECODER_RING[c3] << 6) | (c4 == '=' ? 0 : DECODER_RING[c4]); // unpack int byteOffset = i * 3; result[byteOffset++] = (byte) (x >> 16); if (c3 != '=') { result[byteOffset++] = (byte) ((x >> 8) & 0xFF); if (c4 != '=') { result[byteOffset++] = (byte) (x & 0xFF); } } // skip newlines after block outer: while (chars.length > charOffset) { switch (chars[charOffset++]) { case '\r': case '\n': newlineOffset++; break; default: break outer; } } } return result; }; /** * Decodes a base64 string into bytes. Newline characters found at block * boundaries will be ignored. * * @param encodedString * The string to decode. * @return The decoded byte array. */ public static byte[] decode(String encodedString) { return decode(encodedString.toCharArray()); } /** * Encodes an entire byte array into a Base64 string, with optional newlines * after every 76 characters. * * @param bytes * The byte array to encode. * @param newlines * Indicates whether or not newlines are desired. * @return The encoded string. */ public static String encode(byte[] bytes, boolean newlines) { return encode(bytes, 0, bytes.length, newlines); } /** * Encodes specified bytes into a Base64 string, with optional newlines * after every 76 characters. * * @param bytes * The byte array to encode. * @param off * The starting offset. * @param len * The number of bytes to encode. * @param newlines * Indicates whether or not newlines are desired. * * @return The encoded string. */ public static String encode(byte[] bytes, int off, int len, boolean newlines) { final char[] output = new char[(((len + 2) / 3) * 4) + (newlines ? len / 43 : 0)]; int pos = 0; // encode each block of 3 bytes into 4 chars for (int i = 0; i < (len + 2) / 3; ++i) { int pad = 0; if (len + 1 < (i + 1) * 3) { // two trailing '='s pad = 2; } else if (len < (i + 1) * 3) { // one trailing '=' pad = 1; } // pack final int x = (byteAt(bytes, i, off) << 16) | (pad > 1 ? 0 : (byteAt(bytes, i, off + 1) << 8)) | (pad > 0 ? 0 : (byteAt(bytes, i, off + 2))); // unpack output[pos++] = BASE64_DIGITS[x >> 18]; output[pos++] = BASE64_DIGITS[(x >> 12) & 0x3F]; output[pos++] = pad > 1 ? '=' : BASE64_DIGITS[(x >> 6) & 0x3F]; output[pos++] = pad > 0 ? '=' : BASE64_DIGITS[x & 0x3F]; if (newlines && ((i + 1) % 19 == 0)) { output[pos++] = '\n'; } } return new String(output, 0, pos); } /** * Encodes an entire chars array into a Base64 string, with optional * newlines after every 76 characters. * * @param chars * The characters array to encode. * @param newlines * Indicates whether or not newlines are desired. * @return The encoded string. */ public static String encode(char[] chars, boolean newlines) { return encode(BioUtils.toByteArray(chars), newlines); } /** * Encodes an entire chars array into a Base64 string, with optional * newlines after every 76 characters. * * @param chars * The characters array to encode. * @param charset * The character set to use for the character to byte conversion. * @param newlines * Indicates whether or not newlines are desired. * @return The encoded string. */ public static String encode(char[] chars, String charset, boolean newlines) { return encode(BioUtils.toByteArray(chars, charset), newlines); } /** * Computes the unsigned value of a byte. * * @param b * The input byte. * @return The output unsigned value. */ private final static int unsign(byte b) { return b < 0 ? b + 256 : b; } /** * Indicates if the character is valid and can be decoded. * * @param c * The input character. * @return True if the character is valid. */ private final static boolean validChar(char c) { return (c < 128) && (DECODER_RING[c] != -1); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/package.html0000664000175000017500000000011511757206350025752 0ustar jamespagejamespage General utilities.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/util/ConnegUtils.java0000664000175000017500000000712511757206350026576 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.List; import org.restlet.data.ClientInfo; import org.restlet.data.Metadata; import org.restlet.data.Preference; import org.restlet.representation.Variant; import org.restlet.service.MetadataService; /** * Content negotiation utilities. * * @author Jerome Louvel */ public class ConnegUtils { /** * Returns the preferred metadata taking into account both metadata * supported by the server and client preferences. * * @param supported * The metadata supported by the server. * @param preferences * The client preferences. * @return The preferred metadata. */ public static T getPreferredMetadata( List supported, List> preferences) { T result = null; float maxQuality = 0; if (supported != null) { for (Preference pref : preferences) { for (T metadata : supported) { if (pref.getMetadata().isCompatible(metadata) && (pref.getQuality() > maxQuality)) { result = metadata; maxQuality = pref.getQuality(); } } } } return result; } /** * Returns the best variant representation for a given resource according * the the client preferences.
    * A default language is provided in case the variants don't match the * client preferences. * * @param clientInfo * The client preferences. * @param variants * The list of variants to compare. * @param metadataService * The metadata service. * @return The preferred variant. * @see Apache * content negotiation algorithm */ public static Variant getPreferredVariant(ClientInfo clientInfo, List variants, MetadataService metadataService) { return new Conneg(clientInfo, metadataService) .getPreferredVariant(variants); } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private ConnegUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/FormReader.java0000664000175000017500000003030211757206346026370 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Form reader. * * @author Jerome Louvel */ public class FormReader { /** The encoding to use, decoding is enabled, see {@link #decoding}. */ private volatile CharacterSet characterSet; /** Indicates if the parameters should be decoded. */ private volatile boolean decoding; /** The form stream. */ private volatile InputStream stream; /** The separator character used between parameters. */ private volatile char separator; /** * Constructor.
    * In case the representation does not define a character set, the UTF-8 * character set is used. * * @param representation * The web form content. * @throws IOException * if the stream of the representation could not be opened. */ public FormReader(Representation representation) throws IOException { this.decoding = true; this.stream = representation.getStream(); this.separator = '&'; if (representation.getCharacterSet() != null) { this.characterSet = representation.getCharacterSet(); } else { this.characterSet = CharacterSet.UTF_8; } } /** * Constructor. Will leave the parsed data encoded. * * @param parametersString * The parameters string. */ public FormReader(String parametersString, char separator) { this.decoding = false; this.stream = new ByteArrayInputStream(parametersString.getBytes()); this.characterSet = null; this.separator = separator; } /** * Constructor. * * @param parametersString * The parameters string. * @param characterSet * The supported character encoding. Set to null to leave the * data encoded. */ public FormReader(String parametersString, CharacterSet characterSet, char separator) { this.decoding = true; this.stream = new ByteArrayInputStream(parametersString.getBytes()); this.characterSet = characterSet; this.separator = separator; } /** * Adds the parameters into a given form. * * @param form * The target form. */ public void addParameters(Form form) { boolean readNext = true; Parameter param = null; if (this.stream != null) { // Let's read all form parameters try { while (readNext) { param = readNextParameter(); if (param != null) { // Add parsed parameter to the form form.add(param); } else { // Last parameter parsed readNext = false; } } } catch (IOException ioe) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to parse a form parameter. Skipping the remaining parameters.", ioe); } try { this.stream.close(); } catch (IOException ioe) { Context.getCurrentLogger().log(Level.WARNING, "Unable to close the form input stream", ioe); } } } /** * Reads all the parameters. * * @return The form read. * @throws IOException * If the parameters could not be read. */ public Form read() throws IOException { final Form result = new Form(); Parameter param = readNextParameter(); while (param != null) { result.add(param); param = readNextParameter(); } this.stream.close(); return result; } /** * Reads the first parameter with the given name. * * @param name * The parameter name to match. * @return The parameter value. * @throws IOException */ public Parameter readFirstParameter(String name) throws IOException { Parameter param = readNextParameter(); Parameter result = null; while ((param != null) && (result == null)) { if (param.getName().equals(name)) { result = param; } param = readNextParameter(); } this.stream.close(); return result; } /** * Reads the next parameter available or null. * * @return The next parameter available or null. * @throws IOException * If the next parameter could not be read. */ public Parameter readNextParameter() throws IOException { Parameter result = null; try { boolean readingName = true; boolean readingValue = false; final StringBuilder nameBuffer = new StringBuilder(); final StringBuilder valueBuffer = new StringBuilder(); int nextChar = 0; while ((result == null) && (nextChar != -1)) { nextChar = this.stream.read(); if (readingName) { if (nextChar == '=') { if (nameBuffer.length() > 0) { readingName = false; readingValue = true; } else { throw new IOException( "Empty parameter name detected. Please check your form data"); } } else if ((nextChar == this.separator) || (nextChar == -1)) { if (nameBuffer.length() > 0) { result = FormUtils.create(nameBuffer, null, this.decoding, this.characterSet); } else if (nextChar == -1) { // Do nothing return null preference } else { Context.getCurrentLogger() .fine("Empty parameter name detected. Please check your form data"); } } else { nameBuffer.append((char) nextChar); } } else if (readingValue) { if ((nextChar == this.separator) || (nextChar == -1)) { result = FormUtils.create(nameBuffer, valueBuffer, this.decoding, this.characterSet); } else { valueBuffer.append((char) nextChar); } } } } catch (UnsupportedEncodingException uee) { throw new IOException( "Unsupported encoding. Please contact the administrator"); } return result; } /** * Reads the parameters with the given name. If multiple values are found, a * list is returned created. * * @param name * The parameter name to match. * @return The parameter value or list of values. * @throws IOException * If the parameters could not be read. */ @SuppressWarnings("unchecked") public Object readParameter(String name) throws IOException { Parameter param = readNextParameter(); Object result = null; while (param != null) { if (param.getName().equals(name)) { if (result != null) { List values = null; if (result instanceof List) { // Multiple values already found for this parameter values = (List) result; } else { // Second value found for this parameter // Create a list of values values = new ArrayList(); values.add(result); result = values; } if (param.getValue() == null) { values.add(Series.EMPTY_VALUE); } else { values.add(param.getValue()); } } else { if (param.getValue() == null) { result = Series.EMPTY_VALUE; } else { result = param.getValue(); } } } param = readNextParameter(); } this.stream.close(); return result; } /** * Reads the parameters whose name is a key in the given map. If a matching * parameter is found, its value is put in the map. If multiple values are * found, a list is created and set in the map. * * @param parameters * The parameters map controlling the reading. * @throws IOException * If the parameters could not be read. */ @SuppressWarnings("unchecked") public void readParameters(Map parameters) throws IOException { Parameter param = readNextParameter(); Object currentValue = null; while (param != null) { if (parameters.containsKey(param.getName())) { currentValue = parameters.get(param.getName()); if (currentValue != null) { List values = null; if (currentValue instanceof List) { // Multiple values already found for this parameter values = (List) currentValue; } else { // Second value found for this parameter // Create a list of values values = new ArrayList(); values.add(currentValue); parameters.put(param.getName(), values); } if (param.getValue() == null) { values.add(Series.EMPTY_VALUE); } else { values.add(param.getValue()); } } else { if (param.getValue() == null) { parameters.put(param.getName(), Series.EMPTY_VALUE); } else { parameters.put(param.getName(), param.getValue()); } } } param = readNextParameter(); } this.stream.close(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/FormUtils.java0000664000175000017500000002535211757206346026277 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.representation.Representation; /** * Representation of a Web form containing submitted parameters. * * @author Jerome Louvel */ public class FormUtils { /** * Creates a parameter. * * @param name * The parameter name buffer. * @param value * The parameter value buffer (can be null). * @param decode * If true, the name and values are decoded with the given * {@link CharacterSet}, if false, than nothing is decoded. * @param characterSet * The supported character encoding. * @return The created parameter. */ public static Parameter create(CharSequence name, CharSequence value, boolean decode, CharacterSet characterSet) { Parameter result = null; if (name != null) { String nameStr; if (decode) { nameStr = Reference.decode(name.toString(), characterSet); } else { nameStr = name.toString(); } if (value != null) { String valueStr; if (decode) { valueStr = Reference.decode(value.toString(), characterSet); } else { valueStr = value.toString(); } result = new Parameter(nameStr, valueStr); } else { result = new Parameter(nameStr, null); } } return result; } /** * Reads the first parameter with the given name. * * @param post * The web form representation. * @param name * The parameter name to match. * @return The parameter. * @throws IOException */ public static Parameter getFirstParameter(Representation post, String name) throws IOException { if (!post.isAvailable()) { throw new IllegalStateException( "The Web form cannot be parsed as no fresh content is available. If this entity has been already read once, caching of the entity is required"); } return new FormReader(post).readFirstParameter(name); } /** * Reads the first parameter with the given name. * * @param query * The query string. * @param name * The parameter name to match. * @param characterSet * The supported character encoding. * @param separator * The separator character to append between parameters. * @return The parameter. * @throws IOException */ public static Parameter getFirstParameter(String query, String name, CharacterSet characterSet, char separator) throws IOException { return new FormReader(query, characterSet, separator) .readFirstParameter(name); } /** * Reads the parameters with the given name.
    * If multiple values are found, a list is returned created. * * @param form * The web form representation. * @param name * The parameter name to match. * @return The parameter value or list of values. * @throws IOException * If the parameters could not be read. */ public static Object getParameter(Representation form, String name) throws IOException { if (!form.isAvailable()) { throw new IllegalStateException( "The Web form cannot be parsed as no fresh content is available. If this entity has been already read once, caching of the entity is required"); } return new FormReader(form).readParameter(name); } /** * Reads the parameters with the given name.
    * If multiple values are found, a list is returned created. * * @param query * The query string. * @param name * The parameter name to match. * @param characterSet * The supported character encoding. * @param separator * The separator character to append between parameters. * @return The parameter value or list of values. * @throws IOException * If the parameters could not be read. */ public static Object getParameter(String query, String name, CharacterSet characterSet, char separator) throws IOException { return new FormReader(query, characterSet, separator) .readParameter(name); } /** * Reads the parameters whose name is a key in the given map.
    * If a matching parameter is found, its value is put in the map.
    * If multiple values are found, a list is created and set in the map. * * @param post * The web form representation. * @param parameters * The parameters map controlling the reading. * @throws IOException * If the parameters could not be read. */ public static void getParameters(Representation post, Map parameters) throws IOException { if (!post.isAvailable()) { throw new IllegalStateException( "The Web form cannot be parsed as no fresh content is available. If this entity has been already read once, caching of the entity is required"); } new FormReader(post).readParameters(parameters); } /** * Reads the parameters whose name is a key in the given map.
    * If a matching parameter is found, its value is put in the map.
    * If multiple values are found, a list is created and set in the map. * * @param parametersString * The query string. * @param parameters * The parameters map controlling the reading. * @param characterSet * The supported character encoding. * @param separator * The separator character to append between parameters. * @throws IOException * If the parameters could not be read. */ public static void getParameters(String parametersString, Map parameters, CharacterSet characterSet, char separator) throws IOException { new FormReader(parametersString, characterSet, separator) .readParameters(parameters); } /** * Indicates if the searched parameter is specified in the given media * range. * * @param searchedParam * The searched parameter. * @param mediaRange * The media range to inspect. * @return True if the searched parameter is specified in the given media * range. */ public static boolean isParameterFound(Parameter searchedParam, MediaType mediaRange) { boolean result = false; for (final Iterator iter = mediaRange.getParameters() .iterator(); !result && iter.hasNext();) { result = searchedParam.equals(iter.next()); } return result; } /** * Parses a post into a given form. * * @param form * The target form. * @param post * The posted form. */ public static void parse(Form form, Representation post) { if (post != null) { if (post.isAvailable()) { FormReader fr = null; try { fr = new FormReader(post); } catch (IOException ioe) { Context.getCurrentLogger().log(Level.WARNING, "Unable to create a form reader. Parsing aborted.", ioe); } if (fr != null) { fr.addParameters(form); } } else { throw new IllegalStateException( "The Web form cannot be parsed as no fresh content is available. If this entity has been already read once, caching of the entity is required"); } } } /** * Parses a parameters string into a given form. * * @param form * The target form. * @param parametersString * The parameters string. * @param characterSet * The supported character encoding. * @param decode * Indicates if the query parameters should be decoded using the * given character set. * @param separator * The separator character to append between parameters. */ public static void parse(Form form, String parametersString, CharacterSet characterSet, boolean decode, char separator) { if ((parametersString != null) && !parametersString.equals("")) { FormReader fr = null; if (decode) { fr = new FormReader(parametersString, characterSet, separator); } else { fr = new FormReader(parametersString, separator); } fr.addParameters(form); } } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private FormUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/ListUtils.java0000664000175000017500000000536511757206346026311 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.ArrayList; import java.util.List; /** * Emulate List functions missing from GWT port of List * * @author Rob Heittman */ public class ListUtils { /** * Unlike List.subList(), which returns a live view of a set of List * elements, this method returns a new copy of the list. List.subList() is * not available in GWT 1.5 and was removed on purpose. * * @param list * The source List * @param fromIndex * Starting index in the source List * @param toIndex * Ending index in the source List * @throws IndexOutOfBoundsException * Call exceeds the bounds of the source List * @throws IllegalArgumentException * fromIndex and toIndex are not in sequence * @return a copy of the selected range */ public static List copySubList(List list, int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > list.size()) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); ArrayList subList = new ArrayList(); for (int i = fromIndex; i <= toIndex; i++) { subList.add(list.get(i)); } return subList; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/CallResolver.java0000664000175000017500000003607211757206350026744 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.Date; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.Reference; import org.restlet.util.Resolver; /** * Resolves variable values based on a request and a response. * * @author Jerome Louvel */ public class CallResolver extends Resolver { /** The request to use as a model. */ private final Request request; /** The response to use as a model. */ private final Response response; /** * Constructor. * * @param request * The request to use as a model. * @param response * The response to use as a model. */ public CallResolver(Request request, Response response) { this.request = request; this.response = response; } /** * Returns the content corresponding to a reference property. * * @param partName * The variable sub-part name. * @param reference * The reference to use as a model. * @return The content corresponding to a reference property. */ private String getReferenceContent(String partName, Reference reference) { String result = null; if (reference != null) { if (partName.equals("a")) { result = reference.getAuthority(); } else if (partName.startsWith("b")) { result = getReferenceContent(partName.substring(1), reference .getBaseRef()); } else if (partName.equals("e")) { result = reference.getRelativePart(); } else if (partName.equals("f")) { result = reference.getFragment(); } else if (partName.equals("h")) { result = reference.getHostIdentifier(); } else if (partName.equals("i")) { result = reference.getIdentifier(); } else if (partName.equals("p")) { result = reference.getPath(); } else if (partName.equals("q")) { result = reference.getQuery(); } else if (partName.equals("r")) { result = reference.getRemainingPart(); } } return result; } @Override public Object resolve(String variableName) { Object result = null; // Check for a matching response attribute if (this.response != null && this.response.getAttributes().containsKey(variableName)) { result = this.response.getAttributes().get(variableName); } // Check for a matching request attribute if ((result == null) && (this.request != null) && this.request.getAttributes().containsKey(variableName)) { result = this.request.getAttributes().get(variableName); } // Check for a matching request or response property if (result == null) { if (this.request != null) { if (variableName.equals("c")) { result = Boolean.toString(this.request.isConfidential()); } else if (variableName.equals("cia")) { result = this.request.getClientInfo().getAddress(); } else if (variableName.equals("ciua")) { result = this.request.getClientInfo().getUpstreamAddress(); } else if (variableName.equals("cig")) { result = this.request.getClientInfo().getAgent(); } else if (variableName.equals("cri")) { ChallengeResponse cr = this.request.getChallengeResponse(); if (cr != null) { result = cr.getIdentifier(); } } else if (variableName.equals("crs")) { ChallengeResponse cr = this.request.getChallengeResponse(); if (cr != null && cr.getScheme() != null) { result = cr.getScheme().getTechnicalName(); } } else if (variableName.equals("d")) { result = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123.get(0)); } else if (variableName.equals("ecs")) { if ((this.request.getEntity() != null) && (this.request.getEntity().getCharacterSet() != null)) { result = this.request.getEntity().getCharacterSet() .getName(); } } else if (variableName.equals("ee")) { if ((this.request.getEntity() != null) && (!this.request.getEntity().getEncodings() .isEmpty())) { final StringBuilder value = new StringBuilder(); for (int i = 0; i < this.request.getEntity() .getEncodings().size(); i++) { if (i > 0) { value.append(", "); } value.append(this.request.getEntity() .getEncodings().get(i).getName()); } result = value.toString(); } } else if (variableName.equals("eed")) { if ((this.request.getEntity() != null) && (this.request.getEntity().getExpirationDate() != null)) { result = DateUtils.format(this.request.getEntity() .getExpirationDate(), DateUtils.FORMAT_RFC_1123 .get(0)); } } else if (variableName.equals("el")) { if ((this.request.getEntity() != null) && (!this.request.getEntity().getLanguages() .isEmpty())) { final StringBuilder value = new StringBuilder(); for (int i = 0; i < this.request.getEntity() .getLanguages().size(); i++) { if (i > 0) { value.append(", "); } value.append(this.request.getEntity() .getLanguages().get(i).getName()); } result = value.toString(); } } else if (variableName.equals("emd")) { if ((this.request.getEntity() != null) && (this.request.getEntity().getModificationDate() != null)) { result = DateUtils.format(this.request.getEntity() .getModificationDate(), DateUtils.FORMAT_RFC_1123.get(0)); } } else if (variableName.equals("emt")) { if ((this.request.getEntity() != null) && (this.request.getEntity().getMediaType() != null)) { result = this.request.getEntity().getMediaType() .getName(); } } else if (variableName.equals("es")) { if ((this.request.getEntity() != null) && (this.request.getEntity().getSize() != -1)) { result = Long.toString(this.request.getEntity() .getSize()); } } else if (variableName.equals("et")) { if ((this.request.getEntity() != null) && (this.request.getEntity().getTag() != null)) { result = this.request.getEntity().getTag().getName(); } } else if (variableName.startsWith("f")) { result = getReferenceContent(variableName.substring(1), this.request.getReferrerRef()); } else if (variableName.startsWith("h")) { result = getReferenceContent(variableName.substring(1), this.request.getHostRef()); } else if (variableName.equals("m")) { if (this.request.getMethod() != null) { result = this.request.getMethod().getName(); } } else if (variableName.startsWith("o")) { result = getReferenceContent(variableName.substring(1), this.request.getRootRef()); } else if (variableName.equals("p")) { if (this.request.getProtocol() != null) { result = this.request.getProtocol().getName(); } } else if (variableName.startsWith("r")) { result = getReferenceContent(variableName.substring(1), this.request.getResourceRef()); } } if ((result == null) && (this.response != null)) { if (variableName.equals("ECS")) { if ((this.response.getEntity() != null) && (this.response.getEntity().getCharacterSet() != null)) { result = this.response.getEntity().getCharacterSet() .getName(); } } else if (variableName.equals("EE")) { if ((this.response.getEntity() != null) && (!this.response.getEntity().getEncodings() .isEmpty())) { final StringBuilder value = new StringBuilder(); for (int i = 0; i < this.response.getEntity() .getEncodings().size(); i++) { if (i > 0) { value.append(", "); } value.append(this.response.getEntity() .getEncodings().get(i).getName()); } result = value.toString(); } } else if (variableName.equals("EED")) { if ((this.response.getEntity() != null) && (this.response.getEntity().getExpirationDate() != null)) { result = DateUtils.format(this.response.getEntity() .getExpirationDate(), DateUtils.FORMAT_RFC_1123 .get(0)); } } else if (variableName.equals("EL")) { if ((this.response.getEntity() != null) && (!this.response.getEntity().getLanguages() .isEmpty())) { final StringBuilder value = new StringBuilder(); for (int i = 0; i < this.response.getEntity() .getLanguages().size(); i++) { if (i > 0) { value.append(", "); } value.append(this.response.getEntity() .getLanguages().get(i).getName()); } result = value.toString(); } } else if (variableName.equals("EMD")) { if ((this.response.getEntity() != null) && (this.response.getEntity().getModificationDate() != null)) { result = DateUtils.format(this.response.getEntity() .getModificationDate(), DateUtils.FORMAT_RFC_1123.get(0)); } } else if (variableName.equals("EMT")) { if ((this.response.getEntity() != null) && (this.response.getEntity().getMediaType() != null)) { result = this.response.getEntity().getMediaType() .getName(); } } else if (variableName.equals("ES")) { if ((this.response.getEntity() != null) && (this.response.getEntity().getSize() != -1)) { result = Long.toString(this.response.getEntity() .getSize()); } } else if (variableName.equals("ET")) { if ((this.response.getEntity() != null) && (this.response.getEntity().getTag() != null)) { result = this.response.getEntity().getTag().getName(); } } else if (variableName.startsWith("R")) { result = getReferenceContent(variableName.substring(1), this.response.getLocationRef()); } else if (variableName.equals("S")) { if (this.response.getStatus() != null) { result = Integer.toString(this.response.getStatus() .getCode()); } } else if (variableName.equals("SIA")) { result = this.response.getServerInfo().getAddress(); } else if (variableName.equals("SIG")) { result = this.response.getServerInfo().getAgent(); } else if (variableName.equals("SIP")) { if (this.response.getServerInfo().getPort() != -1) { result = Integer.toString(this.response.getServerInfo() .getPort()); } } } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/ImmutableDate.java0000664000175000017500000001120211757206346027055 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.Date; import java.util.WeakHashMap; import org.restlet.engine.Edition; /** * Class acting as an immutable date class based on the {@link Date} class. * * Throws {@link UnsupportedOperationException} when mutable methods are * invoked. * * @author Piyush Purang (ppurang@gmail.com) * @see java.util.Date * @see Immutable Date */ final class ImmutableDate extends Date { private static final transient WeakHashMap CACHE = new WeakHashMap(); private static final long serialVersionUID = -5946186780670229206L; /** * Returns an ImmutableDate object wrapping the given date. * * @param date * object to be made immutable * @return an immutable date object */ public static ImmutableDate valueOf(Date date) { if (!CACHE.containsKey(date)) { CACHE.put(date, new ImmutableDate(date)); } return CACHE.get(date); } /** * Private constructor. A factory method is provided. * * @param date * date to be made immutable */ private ImmutableDate(Date date) { super(date.getTime()); } /** {@inheritDoc} */ @Override public Object clone() { throw new UnsupportedOperationException("ImmutableDate is immutable"); } /** * As an ImmutableDate is immutable, this method throws an * UnsupportedOperationException exception. */ @Override public void setDate(int arg0) { throw new UnsupportedOperationException("ImmutableDate is immutable"); } /** * As an ImmutableDate is immutable, this method throws an * UnsupportedOperationException exception. */ @Override public void setHours(int arg0) { throw new UnsupportedOperationException("ImmutableDate is immutable"); } /** * As an ImmutableDate is immutable, this method throws an * UnsupportedOperationException exception. */ @Override public void setMinutes(int arg0) { throw new UnsupportedOperationException("ImmutableDate is immutable"); } /** * As an ImmutableDate is immutable, this method throws an * UnsupportedOperationException exception. */ @Override public void setMonth(int arg0) { throw new UnsupportedOperationException("ImmutableDate is immutable"); } /** * As an ImmutableDate is immutable, this method throws an * UnsupportedOperationException exception. */ @Override public void setSeconds(int arg0) { throw new UnsupportedOperationException("ImmutableDate is immutable"); } /** * As an ImmutableDate is immutable, this method throws an * UnsupportedOperationException exception. */ @Override public void setTime(long arg0) { if (Edition.CURRENT == Edition.ANDROID) { super.setTime(arg0); } else { throw new UnsupportedOperationException( "ImmutableDate is immutable"); } } /** * As an ImmutableDate is immutable, this method throws an * UnsupportedOperationException exception. */ @Override public void setYear(int arg0) { throw new UnsupportedOperationException("ImmutableDate is immutable"); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/AlphabeticalComparator.java0000664000175000017500000000513011757206346030744 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.io.Serializable; import java.util.Comparator; import org.restlet.data.Reference; /** * Allows to sort the list of references set by the resource. * * @author Jerome Louvel */ public class AlphabeticalComparator implements Comparator, Serializable { private static final long serialVersionUID = 1L; /** * Compares two references. * * @param ref0 * The first reference. * @param ref1 * The second reference. * @return The comparison result. * @see Comparator */ public int compare(Reference ref0, Reference ref1) { final boolean bRep0Null = (ref0.getIdentifier() == null); final boolean bRep1Null = (ref1.getIdentifier() == null); if (bRep0Null && bRep1Null) { return 0; } if (bRep0Null) { return -1; } if (bRep1Null) { return 1; } return compare(ref0.toString(false, false), ref1.toString(false, false)); } /** * Compares two strings. * * @param str0 * The first string. * @param str1 * The second string. * @return The comparison result. * @see Comparator */ public int compare(final String str0, final String str1) { return str0.compareTo(str1); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/CookieSeries.java0000664000175000017500000000414511757206346026734 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.List; import org.restlet.Request; import org.restlet.data.Cookie; import org.restlet.util.Series; /** * Cookie series used internally by the {@link Request} class. * * @author Jerome Louvel */ public class CookieSeries extends Series { /** * Constructor. */ public CookieSeries() { super(); } /** * Constructor. * * @param delegate * The delegate list. */ public CookieSeries(List delegate) { super(delegate); } @Override public Cookie createEntry(String name, String value) { return new Cookie(name, value); } @Override public Series createSeries(List delegate) { if (delegate != null) { return new CookieSeries(delegate); } return new CookieSeries(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/DefaultSaxHandler.java0000664000175000017500000001444511757206346027712 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Context; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * A Utility class which extends the provided {@link DefaultHandler} and * implements the {@link org.w3c.dom.ls.LSResourceResolver} interface. All the * methods of this class do nothing besides generating log messages. * * @author Raif S. Naffah * @author Jerome Louvel */ public class DefaultSaxHandler extends DefaultHandler implements org.w3c.dom.ls.LSResourceResolver { /** * A class field set to {@code true} if the the JAXP debug property is * turned on; {@code false} otherwise. This is used to control the degree of * output generated in the logs. */ private static boolean debug; static { try { final String debugStr = System.getProperty("jaxp.debug"); debug = debugStr != null && !"false".equalsIgnoreCase(debugStr); } catch (SecurityException x) { debug = false; } } /** * Set to {@code true} if the current Context's logger is capable of * outputting messages at the CONFIG level; {@code false} otherwise. */ private volatile boolean loggable; /** The current context JDK {@link Logger} to use for message output. */ private volatile Logger logger; /** * Trivial constructor. */ public DefaultSaxHandler() { super(); logger = Context.getCurrentLogger(); loggable = logger.isLoggable(Level.CONFIG); } @Override public void error(SAXParseException x) throws SAXException { if (loggable) { final String msg = "[ERROR] - Unexpected exception while parsing " + "an instance of PUBLIC [" + x.getPublicId() + "], SYSTEM [" + x.getSystemId() + "] - line #" + x.getLineNumber() + ", column #" + x.getColumnNumber(); if (debug) { Context.getCurrentLogger().log(Level.CONFIG, msg, x); } else { logger.config(msg + ": " + x.getLocalizedMessage()); } } } @Override public void fatalError(SAXParseException x) throws SAXException { if (loggable) { final String msg = "[FATAL] - Unexpected exception while parsing " + "an instance of PUBLIC [" + x.getPublicId() + "], SYSTEM [" + x.getSystemId() + "] - line #" + x.getLineNumber() + ", column #" + x.getColumnNumber(); if (debug) { Context.getCurrentLogger().log(Level.CONFIG, msg, x); } else { logger.config(msg + ": " + x.getLocalizedMessage()); } } } @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { if (loggable) { logger.config("Resolve entity with PUBLIC [" + publicId + "], and SYSTEM [" + systemId + "]"); } return super.resolveEntity(publicId, systemId); } /** * Allow the application to resolve external resources. *

    * This implementation always returns a {@code null}. * * @param type * The type of the resource being resolved. * @param namespaceUri * The namespace of the resource being resolved. * @param publicId * The public identifier. * @param systemId * The system identifier. * @param baseUri * The absolute base URI of the resource being parsed. * @return Always {@code null}. */ public org.w3c.dom.ls.LSInput resolveResource(String type, String namespaceUri, String publicId, String systemId, String baseUri) { if (loggable) { logger.config("Resolve resource with type [" + type + "], namespace URI [" + namespaceUri + "], PUBLIC [" + publicId + "], SYSTEM [" + systemId + "], and base URI [" + baseUri + "]"); } return null; } @Override public void skippedEntity(String name) throws SAXException { super.skippedEntity(name); if (loggable) { logger.config("Skipped entity named [" + name + "]"); } } @Override public void warning(SAXParseException x) throws SAXException { if (loggable) { final String msg = "[WARN] - Unexpected exception while parsing " + "an instance of PUBLIC [" + x.getPublicId() + "], SYSTEM [" + x.getSystemId() + "] - line #" + x.getLineNumber() + ", column #" + x.getColumnNumber(); if (debug) { Context.getCurrentLogger().log(Level.CONFIG, msg, x); } else { logger.config(msg + ": " + x.getLocalizedMessage()); } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/StringUtils.java0000664000175000017500000001041011757206346026627 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; /** * String manipulation utilities. * * @author Jerome Louvel */ public class StringUtils { /** * Encodes the given String into a sequence of bytes using the Ascii * character set. * * @param string * The string to encode. * @return The String encoded with the Ascii character set as an array of * bytes. */ public static byte[] getAsciiBytes(String string) { if (string != null) { try { return string.getBytes("US-ASCII"); } catch (Exception e) { // Should not happen. return null; } } return null; } /** * Encodes the given String into a sequence of bytes using the Latin1 * character set. * * @param string * The string to encode. * @return The String encoded with the Latin1 character set as an array of * bytes. */ public static byte[] getLatin1Bytes(String string) { if (string != null) { try { return string.getBytes("ISO-8859-1"); } catch (Exception e) { // Should not happen. return null; } } return null; } /** * Strips a delimiter character from both ends of the source string. * * @param source * The source string to strip. * @param delimiter * The character to remove. * @return The stripped string. */ public static String strip(String source, char delimiter) { return strip(source, delimiter, true, true); } /** * Strips a delimiter character from a source string. * * @param source * The source string to strip. * @param delimiter * The character to remove. * @param start * Indicates if start of source should be stripped. * @param end * Indicates if end of source should be stripped. * @return The stripped source string. */ public static String strip(String source, char delimiter, boolean start, boolean end) { int beginIndex = 0; int endIndex = source.length(); boolean stripping = true; // Strip beginning while (stripping && (beginIndex < endIndex)) { if (source.charAt(beginIndex) == delimiter) { beginIndex++; } else { stripping = false; } } // Strip end stripping = true; while (stripping && (beginIndex < endIndex - 1)) { if (source.charAt(endIndex - 1) == delimiter) { endIndex--; } else { stripping = false; } } return source.substring(beginIndex, endIndex); } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private StringUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/DateUtils.java0000664000175000017500000002002611757206346026242 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; /** * Date manipulation utilities. * * @author Jerome Louvel */ public final class DateUtils { /** Obsoleted HTTP date format (ANSI C asctime() format). */ public static final List FORMAT_ASC_TIME = unmodifiableList("EEE MMM dd HH:mm:ss yyyy"); /** Obsoleted HTTP date format (RFC 1036). */ public static final List FORMAT_RFC_1036 = unmodifiableList("EEEE, dd-MMM-yy HH:mm:ss zzz"); /** Preferred HTTP date format (RFC 1123). */ public static final List FORMAT_RFC_1123 = unmodifiableList("EEE, dd MMM yyyy HH:mm:ss zzz"); /** W3C date format (RFC 3339). */ public static final List FORMAT_RFC_3339 = unmodifiableList("yyyy-MM-dd'T'HH:mm:ssz"); /** Common date format (RFC 822). */ public static final List FORMAT_RFC_822 = unmodifiableList( "EEE, dd MMM yy HH:mm:ss z", "EEE, dd MMM yy HH:mm z", "dd MMM yy HH:mm:ss z", "dd MMM yy HH:mm z"); /** Remember the often used GMT time zone. */ private static final java.util.TimeZone TIMEZONE_GMT = java.util.TimeZone .getTimeZone("GMT"); /** * Compares two date with a precision of one second. * * @param baseDate * The base date * @param afterDate * The date supposed to be after. * @return True if the afterDate is indeed after the baseDate. */ public static boolean after(final Date baseDate, final Date afterDate) { if ((baseDate == null) || (afterDate == null)) { throw new IllegalArgumentException( "Can't compare the dates, at least one of them is null"); } final long baseTime = baseDate.getTime() / 1000; final long afterTime = afterDate.getTime() / 1000; return baseTime < afterTime; } /** * Compares two date with a precision of one second. * * @param baseDate * The base date * @param beforeDate * The date supposed to be before. * @return True if the beforeDate is indeed before the baseDate. */ public static boolean before(final Date baseDate, final Date beforeDate) { if ((baseDate == null) || (beforeDate == null)) { throw new IllegalArgumentException( "Can't compare the dates, at least one of them is null"); } final long baseTime = baseDate.getTime() / 1000; final long beforeTime = beforeDate.getTime() / 1000; return beforeTime < baseTime; } /** * Compares two date with a precision of one second. * * @param baseDate * The base date * @param otherDate * The other date supposed to be equals. * @return True if both dates are equals. */ public static boolean equals(final Date baseDate, final Date otherDate) { if ((baseDate == null) || (otherDate == null)) { throw new IllegalArgumentException( "Can't compare the dates, at least one of them is null"); } final long baseTime = baseDate.getTime() / 1000; final long otherTime = otherDate.getTime() / 1000; return otherTime == baseTime; } /** * Formats a Date in the default HTTP format (RFC 1123). * * @param date * The date to format. * @return The formatted date. */ public static String format(final Date date) { return format(date, DateUtils.FORMAT_RFC_1123.get(0)); } /** * Formats a Date according to the first format in the array. * * @param date * The date to format. * @param format * The date format to use. * @return The formatted date. */ public static String format(final Date date, final String format) { if (date == null) { throw new IllegalArgumentException("Date is null"); } java.text.DateFormat formatter = null; if (FORMAT_RFC_3339.get(0).equals(format)) { formatter = new InternetDateFormat(TIMEZONE_GMT); } else { formatter = new java.text.SimpleDateFormat(format, java.util.Locale.US); formatter.setTimeZone(TIMEZONE_GMT); } return formatter.format(date); } /** * Parses a formatted date into a Date object using the default HTTP format * (RFC 1123). * * @param date * The date to parse. * @return The parsed date. */ public static Date parse(String date) { return parse(date, FORMAT_RFC_1123); } /** * Parses a formatted date into a Date object. * * @param date * The date to parse. * @param formats * The date formats to use sorted by completeness. * @return The parsed date. */ public static Date parse(String date, List formats) { Date result = null; if (date == null) { throw new IllegalArgumentException("Date is null"); } String format = null; int formatsSize = formats.size(); for (int i = 0; (result == null) && (i < formatsSize); i++) { format = formats.get(i); java.text.DateFormat parser = null; if (FORMAT_RFC_3339.get(0).equals(format)) { parser = new InternetDateFormat(TIMEZONE_GMT); } else { parser = new java.text.SimpleDateFormat(format, java.util.Locale.US); parser.setTimeZone(TIMEZONE_GMT); } try { result = parser.parse(date); } catch (Exception e) { // Ignores error as the next format may work better } } return result; } /** * Returns an immutable version of a given date. * * @param date * The modifiable date. * @return An immutable version of a given date. */ public static Date unmodifiable(Date date) { return (date == null) ? null : ImmutableDate.valueOf(date); } /** * Helper method to help initialize this class by providing unmodifiable * lists based on arrays. * * @param * Any valid java object * @param array * to be convereted into an unmodifiable list * @return unmodifiable list based on the provided array */ private static List unmodifiableList(final T... array) { return Collections.unmodifiableList(Arrays.asList(array)); } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instatiable and extensible. */ private DateUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/util/Conneg.java0000664000175000017500000003301511757206346025557 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.util; import java.util.ArrayList; import java.util.List; import org.restlet.data.CharacterSet; import org.restlet.data.ClientInfo; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Preference; import org.restlet.representation.Variant; import org.restlet.service.MetadataService; /** * Content negotiation algorithm. * * @author Jerome Louvel */ public class Conneg { /** The enriched list of character set preferences. */ private volatile List> characterSetPrefs; /** The client preferences. */ private volatile ClientInfo clientInfo; /** The enriched list of encoding preferences. */ private volatile List> encodingPrefs; /** The enriched list of language preferences. */ private volatile List> languagePrefs; /** The enriched list of media type preferences. */ private volatile List> mediaTypePrefs; /** The metadata service. */ private volatile MetadataService metadataService; /** * Constructor. * * @param clientInfo * @param metadataService */ public Conneg(ClientInfo clientInfo, MetadataService metadataService) { this.clientInfo = clientInfo; this.metadataService = metadataService; if (clientInfo != null) { // Get the enriched user preferences this.languagePrefs = getEnrichedPreferences(clientInfo .getAcceptedLanguages(), (metadataService == null) ? null : metadataService.getDefaultLanguage(), Language.ALL); this.mediaTypePrefs = getEnrichedPreferences(clientInfo .getAcceptedMediaTypes(), (metadataService == null) ? null : metadataService.getDefaultMediaType(), MediaType.ALL); this.characterSetPrefs = getEnrichedPreferences(clientInfo .getAcceptedCharacterSets(), (metadataService == null) ? null : metadataService .getDefaultCharacterSet(), CharacterSet.ALL); this.encodingPrefs = getEnrichedPreferences(clientInfo .getAcceptedEncodings(), (metadataService == null) ? null : metadataService.getDefaultEncoding(), Encoding.ALL); } } /** * Returns true if the metadata can be added. * * @param * @param metadata * The metadata to add. * @param undesired * The list of proscribed metadata. * @return True if the metadata can be added. */ private boolean canAdd(T metadata, List undesired) { boolean add = true; if (undesired != null) { for (T u : undesired) { if (u.equals(metadata)) { add = false; break; } } } return add; } /** * Returns the enriched list of character set preferences. * * @return The enriched list of character set preferences. */ protected List> getCharacterSetPrefs() { return characterSetPrefs; } /** * Returns the client preferences. * * @return The client preferences. */ protected ClientInfo getClientInfo() { return clientInfo; } /** * Returns the enriched list of encoding preferences. * * @return The enriched list of encoding preferences. */ protected List> getEncodingPrefs() { return encodingPrefs; } /** * Returns an enriched list of preferences. Contains the user preferences, * implied user parent preferences (quality between 0.005 and 0.006), * default preference (quality of 0.003), default parent preference (quality * of 0.002), all preference (quality of 0.001).
    *
    * This necessary to compensate the misconfiguration of many browsers which * don't expose all the metadata actually understood by end users. * * @param * @param userPreferences * The user preferences to enrich. * @param defaultValue * The default value. * @param allValue * The ALL value. * @return The enriched user preferences. */ @SuppressWarnings("unchecked") protected List> getEnrichedPreferences( List> userPreferences, T defaultValue, T allValue) { List> result = new ArrayList>(); // 0) List all undesired metadata List undesired = null; for (Preference pref : userPreferences) { if (pref.getQuality() == 0) { if (undesired == null) { undesired = new ArrayList(); } undesired.add(pref.getMetadata()); } } // 1) Add the user preferences result.addAll(userPreferences); // 2) Add the user parent preferences T parent; for (int i = 0; i < result.size(); i++) { Preference userPref = result.get(i); parent = (T) userPref.getMetadata().getParent(); // Add the parent, if it is not proscribed. if ((parent != null)) { if (canAdd(parent, undesired)) { result.add(new Preference(parent, 0.005f + (0.001f * userPref.getQuality()))); } } } // 3) Add the default preference if (defaultValue != null && canAdd(defaultValue, undesired)) { Preference defaultPref = new Preference(defaultValue, 0.003f); result.add(defaultPref); T defaultParent = (T) defaultValue.getParent(); if (defaultParent != null && canAdd(defaultParent, undesired)) { result.add(new Preference(defaultParent, 0.002f)); } } // 5) Add "all" preference for (int i = result.size() - 1; i >= 0; i--) { // Remove any existing preference if (result.get(i).getMetadata().equals(allValue)) { result.remove(i); } } result.add(new Preference(allValue, 0.001f)); // 6) Return the enriched preferences return result; } /** * Returns the enriched list of language preferences. * * @return The enriched list of language preferences. */ protected List> getLanguagePrefs() { return languagePrefs; } /** * Returns the enriched list of media type preferences. * * @return The enriched list of media type preferences. */ protected List> getMediaTypePrefs() { return mediaTypePrefs; } /** * Returns the metadata service. * * @return The metadata service. */ protected MetadataService getMetadataService() { return metadataService; } /** * Returns the best variant representation for a given resource according * the the client preferences.
    * A default language is provided in case the variants don't match the * client preferences. * * @param variants * The list of variants to compare. * @return The preferred variant. * @see Apache * content negotiation algorithm */ public Variant getPreferredVariant(List variants) { Variant result = null; if ((variants != null) && !variants.isEmpty()) { float bestScore = -1.0F; float current; // Compute the score of each variant for (Variant variant : variants) { current = scoreVariant(variant); if (current > bestScore) { bestScore = current; result = variant; } } } return result; } /** * Scores a character set relatively to enriched client preferences. * * @param characterSet * The character set to score. * @return The score. */ public float scoreCharacterSet(CharacterSet characterSet) { return scoreMetadata(characterSet, getCharacterSetPrefs()); } /** * Scores encodings relatively to enriched client preferences. * * @param encodings * The encodings to score. * @return The score. */ public float scoreEncodings(List encodings) { return scoreMetadata(encodings, getEncodingPrefs()); } /** * Scores languages relatively to enriched client preferences. * * @param languages * The languages to score. * @return The score. */ public float scoreLanguages(List languages) { return scoreMetadata(languages, getLanguagePrefs()); } /** * Scores a media type relatively to enriched client preferences. * * @param mediaType * The media type to score. * @return The score. */ public float scoreMediaType(MediaType mediaType) { return scoreMetadata(mediaType, getMediaTypePrefs()); } /** * Scores a list of metadata relatively to enriched client preferences. * * @param metadataList * The list of metadata to score. * @return The score. */ private float scoreMetadata(List metadataList, List> prefs) { float result = -1.0F; float current; if ((metadataList != null) && !metadataList.isEmpty()) { for (Preference pref : prefs) { for (T metadata : metadataList) { if (pref.getMetadata().includes(metadata)) { current = pref.getQuality(); } else { current = -1.0F; } if (current > result) { result = current; } } } } else { result = 0.0F; } return result; } /** * Scores a metadata relatively to enriched client preferences. * * @param metadata * The metadata to score. * @return The score. */ private float scoreMetadata(T metadata, List> prefs) { float result = -1.0F; float current; if (metadata != null) { for (Preference pref : prefs) { if (pref.getMetadata().includes(metadata)) { current = pref.getQuality(); } else { current = -1.0F; } if (current > result) { result = current; } } } else { result = 0.0F; } return result; } /** * Scores a variant relatively to enriched client preferences. * * @param variant * The variant to score. * @return The enriched client preferences. */ public float scoreVariant(Variant variant) { float result = -1.0F; float languageScore = scoreLanguages(variant.getLanguages()); if (languageScore != -1.0F) { float mediaTypeScore = scoreMediaType(variant.getMediaType()); if (mediaTypeScore != -1.0F) { float characterSetScore = scoreCharacterSet(variant .getCharacterSet()); if (characterSetScore != -1.0F) { float encodingScore = scoreEncodings(variant.getEncodings()); if (encodingScore != -1.0F) { // Return the weighted average score result = ((languageScore * 4.0F) + (mediaTypeScore * 3.0F) + (characterSetScore * 2.0F) + encodingScore) / 9.0F; } } } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/0000775000175000017500000000000011757206350023126 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/io/PipeStream.java0000664000175000017500000001057511757206346026057 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; // [excludes gwt] /** * Pipe stream that pipes output streams into input streams. Implementation * based on a shared synchronized queue. * * @author Jerome Louvel */ public class PipeStream { /** The queue timeout. */ private static final long QUEUE_TIMEOUT = 5; /** The supporting synchronized queue. */ private final BlockingQueue queue; /** Constructor. */ public PipeStream() { this.queue = new ArrayBlockingQueue(1024); } /** * Returns a new input stream that can read from the pipe. * * @return A new input stream that can read from the pipe. */ public InputStream getInputStream() { return new InputStream() { private boolean endReached = false; @Override public int read() throws IOException { try { if (this.endReached) { return -1; } final Integer value = queue.poll(QUEUE_TIMEOUT, TimeUnit.SECONDS); this.endReached = (value == -1); if (value == null) { throw new IOException( "Timeout while reading from the queue-based input stream"); } else { return value.intValue(); } } catch (InterruptedException ie) { throw new IOException( "Interruption occurred while writing in the queue"); } } }; } /** * Returns a new output stream that can write into the pipe. * * @return A new output stream that can write into the pipe. */ public OutputStream getOutputStream() { return new OutputStream() { @Override public void write(int b) throws IOException { try { if (!queue.offer(b & 0xff, QUEUE_TIMEOUT, TimeUnit.SECONDS)) { throw new IOException( "Timeout while writing to the queue-based output stream"); } } catch (InterruptedException ie) { throw new IOException( "Interruption occurred while writing in the queue"); } } @Override public void close() throws IOException { try { if (!queue.offer(-1, QUEUE_TIMEOUT, TimeUnit.SECONDS)) { throw new IOException( "Timeout while writing to the queue-based output stream"); } } catch (InterruptedException ie) { throw new IOException( "Interruption occurred while writing in the queue"); } } }; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/ReaderInputStream.java0000664000175000017500000001270111757206346027375 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetEncoder; import org.restlet.data.CharacterSet; // [excludes gwt] /** * Input stream based on a reader. The implementation relies on the NIO * {@link CharsetEncoder} class. * * @author Jerome Louvel */ public class ReaderInputStream extends InputStream { /** The NIO byte buffer. */ private final ByteBuffer byteBuffer; /** The NIO character buffer. */ private final CharBuffer charBuffer; /** The character set encoder. */ private final CharsetEncoder charsetEncoder; /** Indicates if the end of the wrapped reader has been reached. */ private volatile boolean endReached; /** The wrapped reader. */ private final BufferedReader reader; /** * Constructor. Uses the {@link CharacterSet#ISO_8859_1} character set by * default. * * @param reader * The reader to wrap as an input stream. * @throws IOException */ public ReaderInputStream(Reader reader) throws IOException { this(reader, CharacterSet.ISO_8859_1); } /** * Constructor. * * @param reader * The reader to wrap as an input stream. * @param characterSet * The character set to use for encoding. * @throws IOException */ public ReaderInputStream(Reader reader, CharacterSet characterSet) throws IOException { this.byteBuffer = ByteBuffer.allocate(1024); this.byteBuffer.flip(); this.charBuffer = CharBuffer.allocate(1024); this.charBuffer.flip(); this.charsetEncoder = (characterSet == null) ? CharacterSet.ISO_8859_1 .toCharset().newEncoder() : characterSet.toCharset() .newEncoder(); this.endReached = false; this.reader = (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader, IoUtils.BUFFER_SIZE); } @Override public int available() throws IOException { return this.byteBuffer.hasRemaining() ? this.byteBuffer.remaining() : 0; } /** * Closes the wrapped reader. */ @Override public void close() throws IOException { this.reader.close(); } @Override public int read() throws IOException { byte[] temp = new byte[1]; return (read(temp) == -1) ? -1 : temp[0] & 0xFF; } @Override public int read(byte[] b, int off, int len) throws IOException { int result = 0; boolean iterate = true; while (iterate) { // Do we need to refill the byte buffer? if (!this.byteBuffer.hasRemaining() && !this.endReached) { // Do we need to refill the char buffer? if (!this.charBuffer.hasRemaining()) { this.charBuffer.clear(); int read = this.reader.read(this.charBuffer); this.charBuffer.flip(); if (read == -1) { this.endReached = true; } } if ((len > 0) && this.charBuffer.hasRemaining()) { // Refill the byte buffer this.byteBuffer.clear(); this.charsetEncoder.encode(this.charBuffer, this.byteBuffer, this.endReached); this.byteBuffer.flip(); } } // Copies as much bytes as possible in the target array int readLength = Math.min(len, this.byteBuffer.remaining()); if (readLength > 0) { this.byteBuffer.get(b, off, readLength); off += readLength; len -= readLength; result += readLength; } // Can we iterate again? iterate = (len > 0) && (!this.endReached || this.byteBuffer.hasRemaining() || this.charBuffer .hasRemaining()); } if (this.endReached && (result == 0)) { result = -1; } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java0000664000175000017500000001337611757206346030235 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.WritableByteChannel; // [excludes gwt] /** * Output stream connected to a non-blocking writable channel. * * @author Jerome Louvel */ public class NbChannelOutputStream extends OutputStream { /** The internal byte buffer. */ private final ByteBuffer bb = ByteBuffer.allocate(IoUtils.BUFFER_SIZE); /** The channel to write to. */ private final WritableByteChannel channel; /** The selectable channel to write to. */ private final SelectableChannel selectableChannel; /** The selection key. */ private volatile SelectionKey selectionKey; /** The selector. */ private volatile Selector selector; /** * Constructor. * * @param channel * The wrapped channel. */ public NbChannelOutputStream(WritableByteChannel channel) { if (channel instanceof SelectableChannel) { this.selectableChannel = (SelectableChannel) channel; } else { this.selectableChannel = null; } this.channel = channel; this.selector = null; } /** * Effectively write the current byte buffer. * * @throws IOException */ private void doWrite() throws IOException { if ((this.channel != null) && (this.bb != null)) { try { int bytesWritten; int attempts = 0; while (this.bb.hasRemaining()) { bytesWritten = this.channel.write(this.bb); attempts++; if (bytesWritten < 0) { throw new EOFException( "Unexpected negative number of bytes written. End of file detected."); } else if (bytesWritten == 0) { if (this.selectableChannel != null) { if (this.selector == null) { this.selector = SelectorFactory.getSelector(); } if (this.selector == null) { if (attempts > 2) { throw new IOException( "Unable to obtain a selector. Selector factory returned null."); } } else { // Register a selector to write more this.selectionKey = this.selectableChannel .register(this.selector, SelectionKey.OP_WRITE); if (this.selector.select(NioUtils.NIO_TIMEOUT) == 0) { if (attempts > 2) { throw new IOException( "Unable to select the channel to write to it. Selection timed out."); } } else { attempts--; } } } } else { attempts = 0; } } } catch (IOException ioe) { throw new IOException( "Unable to write to the non-blocking channel. " + ioe.getLocalizedMessage()); } finally { this.bb.clear(); NioUtils.release(this.selector, this.selectionKey); } } else { throw new IOException( "Unable to write. Null byte buffer or channel detected."); } } @Override public void write(byte b[], int off, int len) throws IOException { for (int index = 0; index < len; index = index + IoUtils.BUFFER_SIZE) { int size = len - index > IoUtils.BUFFER_SIZE ? IoUtils.BUFFER_SIZE : len - index; this.bb.clear(); this.bb.put(b, index, size); this.bb.flip(); doWrite(); } } @Override public void write(int b) throws IOException { this.bb.clear(); this.bb.put((byte) b); this.bb.flip(); doWrite(); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/NioUtils.java0000664000175000017500000002437011757206346025552 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.Channel; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.WritableByteChannel; import java.util.logging.Level; import org.restlet.Context; import org.restlet.engine.Edition; import org.restlet.representation.Representation; // [excludes gwt] /** * Utility methods for NIO processing. * * @author Jerome Louvel */ public class NioUtils { /** The number of milliseconds after which NIO operation will time out. */ public static final int NIO_TIMEOUT = 60000; /** * Writes the representation to a byte channel. Optimizes using the file * channel transferTo method. * * @param fileChannel * The readable file channel. * @param writableChannel * A writable byte channel. */ public static void copy(FileChannel fileChannel, WritableByteChannel writableChannel) throws IOException { long position = 0; long count = fileChannel.size(); long written = 0; SelectableChannel selectableChannel = null; if (writableChannel instanceof SelectableChannel) { selectableChannel = (SelectableChannel) writableChannel; } while (count > 0) { NioUtils.waitForState(selectableChannel, SelectionKey.OP_WRITE); written = fileChannel.transferTo(position, count, writableChannel); position += written; count -= written; } } /** * Writes a NIO readable channel to a BIO output stream. * * @param readableChannel * The readable channel. * @param outputStream * The output stream. * @throws IOException */ public static void copy(ReadableByteChannel readableChannel, OutputStream outputStream) throws IOException { if ((readableChannel != null) && (outputStream != null)) { BioUtils.copy(new NbChannelInputStream(readableChannel), outputStream); } } /** * Writes a readable channel to a writable channel. * * @param readableChannel * The readable channel. * @param writableChannel * The writable channel. * @throws IOException */ public static void copy(ReadableByteChannel readableChannel, WritableByteChannel writableChannel) throws IOException { if ((readableChannel != null) && (writableChannel != null)) { BioUtils.copy(new NbChannelInputStream(readableChannel), new NbChannelOutputStream(writableChannel)); } } /** * Returns a readable byte channel based on a given input stream. If it is * supported by a file a read-only instance of FileChannel is returned. * * @param inputStream * The input stream to convert. * @return A readable byte channel. */ public static ReadableByteChannel getChannel(InputStream inputStream) { return (inputStream != null) ? Channels.newChannel(inputStream) : null; } /** * Returns a writable byte channel based on a given output stream. * * @param outputStream * The output stream. * @return A writable byte channel. */ public static WritableByteChannel getChannel(OutputStream outputStream) { return (outputStream != null) ? Channels.newChannel(outputStream) : null; } /** * Returns a readable byte channel based on the given representation's * content and its write(WritableByteChannel) method. Internally, it uses a * writer thread and a pipe channel. * * @param representation * the representation to get the {@link OutputStream} from. * @return A readable byte channel. * @throws IOException */ public static ReadableByteChannel getChannel( final Representation representation) throws IOException { ReadableByteChannel result = null; if (Edition.CURRENT != Edition.GAE) { final java.nio.channels.Pipe pipe = java.nio.channels.Pipe.open(); org.restlet.Application application = org.restlet.Application .getCurrent(); // Get a thread that will handle the task of continuously // writing the representation into the input side of the pipe Runnable task = new Runnable() { public void run() { try { WritableByteChannel wbc = pipe.sink(); representation.write(wbc); wbc.close(); } catch (IOException ioe) { Context.getCurrentLogger().log(Level.FINE, "Error while writing to the piped channel.", ioe); } } }; if (application != null && application.getTaskService() != null) { application.getTaskService().execute(task); } else { new Thread(task).start(); } result = pipe.source(); } else { Context.getCurrentLogger() .log(Level.WARNING, "The GAE edition is unable to return a channel for a representation given its write(WritableByteChannel) method."); } return result; } /** * Returns an input stream based on a given readable byte channel. * * @param readableChannel * The readable byte channel. * @return An input stream based on a given readable byte channel. */ public static InputStream getStream(ReadableByteChannel readableChannel) { InputStream result = null; if (readableChannel != null) { result = new NbChannelInputStream(readableChannel); } return result; } /** * Returns an output stream based on a given writable byte channel. * * @param writableChannel * The writable byte channel. * @return An output stream based on a given writable byte channel. */ public static OutputStream getStream(WritableByteChannel writableChannel) { return isBlocking(writableChannel) ? Channels .newOutputStream(writableChannel) : new NbChannelOutputStream( writableChannel); } /** * Indicates if the channel is in blocking mode. It returns false when the * channel is selectable and configured to be non blocking. * * @param channel * The channel to test. * @return True if the channel is in blocking mode. */ public static boolean isBlocking(Channel channel) { boolean result = true; if (channel instanceof SelectableChannel) { SelectableChannel selectableChannel = (SelectableChannel) channel; result = selectableChannel.isBlocking(); } return result; } /** * Release the selection key, working around for bug #6403933. * * @param selector * The associated selector. * @param selectionKey * The used selection key. * @throws IOException */ public static void release(Selector selector, SelectionKey selectionKey) throws IOException { if (selectionKey != null) { // The key you registered on the temporary selector selectionKey.cancel(); if (selector != null) { // Flush the canceled key selector.selectNow(); SelectorFactory.returnSelector(selector); } } } /** * Waits for the given channel to be ready for a specific operation. * * @param selectableChannel * The channel to monitor. * @param operations * The operations to be ready to do. * @throws IOException */ public static void waitForState(SelectableChannel selectableChannel, int operations) throws IOException { if (selectableChannel != null) { Selector selector = null; SelectionKey selectionKey = null; int selected = 0; try { selector = SelectorFactory.getSelector(); while (selected == 0) { selectionKey = selectableChannel.register(selector, operations); selected = selector.select(NIO_TIMEOUT); } } finally { NioUtils.release(selector, selectionKey); } } } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private NioUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/TraceOutputStream.java0000664000175000017500000000403011757206346027426 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Filter output stream that sends a copy of all data on the standard console. * * @author Jerome Louvel */ public class TraceOutputStream extends FilterOutputStream { /** * Constructor. * * @param out * The output stream to wrap. */ public TraceOutputStream(OutputStream out) { super(out); } @Override public void flush() throws IOException { super.flush(); synchronized (System.out) { System.out.flush(); } } @Override public void write(int b) throws IOException { super.write(b); synchronized (System.out) { System.out.write(b); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/NbChannelInputStream.java0000664000175000017500000001152711757206350030023 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; // [excludes gwt] /** * Input stream connected to a non-blocking readable channel. * * @author Jerome Louvel */ public class NbChannelInputStream extends InputStream { /** The internal byte buffer. */ private final ByteBuffer bb; /** The channel to read from. */ private final ReadableByteChannel channel; /** Indicates if further reads can be attempted. */ private volatile boolean endReached; /** The selectable channel to read from. */ private final SelectableChannel selectableChannel; /** * Constructor. * * @param channel * The channel to read from. */ public NbChannelInputStream(ReadableByteChannel channel) { this.channel = channel; if (channel instanceof SelectableChannel) { this.selectableChannel = (SelectableChannel) channel; } else { this.selectableChannel = null; } this.bb = ByteBuffer.allocate(IoUtils.BUFFER_SIZE); this.bb.flip(); this.endReached = false; } @Override public int read() throws IOException { int result = -1; if (!this.endReached) { if (!this.bb.hasRemaining()) { // Let's refill refill(); } if (!this.endReached) { // Let's return the next one result = this.bb.get() & 0xff; } } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { int result = -1; if (!this.endReached) { if (!this.bb.hasRemaining()) { // Let's try to refill refill(); } if (!this.endReached) { // Let's return the next ones result = Math.min(len, this.bb.remaining()); this.bb.get(b, off, result); } } return result; } /** * Reads the available bytes from the channel into the byte buffer. * * @return The number of bytes read or -1 if the end of channel has been * reached. * @throws IOException */ private int readChannel() throws IOException { int result = 0; this.bb.clear(); result = this.channel.read(this.bb); this.bb.flip(); return result; } /** * Refill the byte buffer by attempting to read the channel. * * @throws IOException */ private void refill() throws IOException { // No, let's try to read more Selector selector = null; SelectionKey selectionKey = null; try { int bytesRead = readChannel(); // If no bytes were read, try to register a select key to // get more if ((bytesRead == 0) && (selectableChannel != null)) { selector = SelectorFactory.getSelector(); if (selector != null) { selectionKey = this.selectableChannel.register(selector, SelectionKey.OP_READ); selector.select(NioUtils.NIO_TIMEOUT); } bytesRead = readChannel(); } else if (bytesRead == -1) { this.endReached = true; } } finally { NioUtils.release(selector, selectionKey); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/BioUtils.java0000664000175000017500000005035711757206346025542 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.Range; import org.restlet.engine.Edition; import org.restlet.representation.Representation; /** * Basic IO manipulation utilities. * * @author Jerome Louvel */ public final class BioUtils { /** Support for byte to hexa conversions. */ private static final char[] HEXDIGITS = "0123456789ABCDEF".toCharArray(); /** * Copies an input stream to an output stream. When the reading is done, the * input stream is closed. * * @param inputStream * The input stream. * @param outputStream * The output stream. * @throws IOException */ public static void copy(InputStream inputStream, java.io.OutputStream outputStream) throws IOException { int bytesRead; byte[] buffer = new byte[2048]; while ((bytesRead = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); } /** * Copies an input stream to a random access file. When the reading is done, * the input stream is closed. * * @param inputStream * The input stream. * @param randomAccessFile * The random access file. * @throws IOException */ public static void copy(InputStream inputStream, java.io.RandomAccessFile randomAccessFile) throws IOException { int bytesRead; byte[] buffer = new byte[2048]; while ((bytesRead = inputStream.read(buffer)) > 0) { randomAccessFile.write(buffer, 0, bytesRead); } inputStream.close(); } /** * Copies characters from a reader to a writer. When the reading is done, * the reader is closed. * * @param reader * The reader. * @param writer * The writer. * @throws IOException */ public static void copy(Reader reader, java.io.Writer writer) throws IOException { int charsRead; char[] buffer = new char[2048]; while ((charsRead = reader.read(buffer)) > 0) { writer.write(buffer, 0, charsRead); } writer.flush(); reader.close(); } /** * Deletes an individual file or an empty directory. * * @param file * The individual file or directory to delete. * @return True if the deletion was successful. */ public static boolean delete(java.io.File file) { return delete(file, false); } /** * Deletes an individual file or a directory. A recursive deletion can be * forced as well. Under Windows operating systems, the garbage collector * will be invoked once before attempting to delete in order to prevent * locking issues. * * @param file * The individual file or directory to delete. * @param recursive * Indicates if directory with content should be deleted * recursively as well. * @return True if the deletion was successful or if the file or directory * didn't exist. */ public static boolean delete(java.io.File file, boolean recursive) { String osName = System.getProperty("os.name").toLowerCase(); return delete(file, recursive, osName.startsWith("windows")); } /** * Deletes an individual file or a directory. A recursive deletion can be * forced as well. The garbage collector can be run once before attempting * to delete, to workaround lock issues under Windows operating systems. * * @param file * The individual file or directory to delete. * @param recursive * Indicates if directory with content should be deleted * recursively as well. * @param garbageCollect * Indicates if the garbage collector should be run. * @return True if the deletion was successful or if the file or directory * didn't exist. */ public static boolean delete(java.io.File file, boolean recursive, boolean garbageCollect) { boolean result = true; boolean runGC = garbageCollect; if (file.exists()) { if (file.isDirectory()) { java.io.File[] entries = file.listFiles(); // Check if the directory is empty if (entries.length > 0) { if (recursive) { for (int i = 0; result && (i < entries.length); i++) { if (runGC) { System.gc(); runGC = false; } result = delete(entries[i], true, false); } } else { result = false; } } } if (runGC) { System.gc(); runGC = false; } result = result && file.delete(); } return result; } /** * Exhaust the content of the representation by reading it and silently * discarding anything read. * * @param input * The input stream to exhaust. * @return The number of bytes consumed or -1 if unknown. */ public static long exhaust(InputStream input) throws IOException { long result = -1L; if (input != null) { byte[] buf = new byte[2048]; int read = input.read(buf); result = (read == -1) ? -1 : 0; while (read != -1) { result += read; read = input.read(buf); } } return result; } /** * Returns the size effectively available. This returns the same value as * {@link Representation#getSize()} if no range is defined, otherwise it * returns the size of the range using {@link Range#getSize()}. * * @param representation * The representation to evaluate. * @return The available size. */ public static long getAvailableSize(Representation representation) { if (representation.getRange() == null) { return representation.getSize(); } else if (representation.getRange().getSize() != Range.SIZE_MAX) { return representation.getRange().getSize(); } else if (representation.getSize() != Representation.UNKNOWN_SIZE) { if (representation.getRange().getIndex() != Range.INDEX_LAST) { return (representation.getSize() == -1) ? -1 : (representation .getSize() - representation.getRange().getIndex()); } return representation.getSize(); } return Representation.UNKNOWN_SIZE; } /** * Returns a reader from an input stream and a character set. * * @param stream * The input stream. * @param characterSet * The character set. May be null. * @return The equivalent reader. * @throws UnsupportedEncodingException * if a character set is given, but not supported */ public static Reader getReader(InputStream stream, CharacterSet characterSet) throws UnsupportedEncodingException { if (characterSet != null) { return new InputStreamReader(stream, characterSet.getName()); } return new InputStreamReader(stream); } /** * Returns a reader from a writer representation.Internally, it uses a * writer thread and a pipe stream. * * @param representation * The representation to read from. * @return The character reader. * @throws IOException */ public static Reader getReader( final org.restlet.representation.WriterRepresentation representation) throws IOException { Reader result = null; if (Edition.CURRENT != Edition.GAE) { final java.io.PipedWriter pipedWriter = new java.io.PipedWriter(); java.io.PipedReader pipedReader = new java.io.PipedReader( pipedWriter); org.restlet.Application application = org.restlet.Application .getCurrent(); // Gets a thread that will handle the task of continuously // writing the representation into the input side of the pipe Runnable task = new Runnable() { public void run() { try { representation.write(pipedWriter); pipedWriter.flush(); pipedWriter.close(); } catch (IOException ioe) { Context.getCurrentLogger() .log(Level.FINE, "Error while writing to the piped reader.", ioe); } } }; if (application != null && application.getTaskService() != null) { application.getTaskService().execute(task); } else { new Thread(task).start(); } result = pipedReader; } else { Context.getCurrentLogger() .log(Level.WARNING, "The GAE edition is unable to return a reader for a writer representation."); } return result; } /** * Returns an output stream based on a given writer. * * @param writer * The writer. * @return the output stream of the writer */ public static java.io.OutputStream getStream(java.io.Writer writer) { return new WriterOutputStream(writer); } /** * Returns an input stream based on a given character reader. * * @param reader * The character reader. * @param characterSet * The stream character set. * @return An input stream based on a given character reader. */ public static InputStream getStream(Reader reader, CharacterSet characterSet) { InputStream result = null; try { result = new ReaderInputStream(reader, characterSet); } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to create the reader input stream", e); } return result; } /** * Returns an input stream based on the given representation's content and * its write(OutputStream) method. Internally, it uses a writer thread and a * pipe stream. * * @param representation * the representation to get the {@link java.io.OutputStream} * from. * @return A stream with the representation's content. */ public static InputStream getStream(final Representation representation) { InputStream result = null; if (Edition.CURRENT != Edition.GAE) { if (representation == null) { return null; } final PipeStream pipe = new PipeStream(); org.restlet.Application application = org.restlet.Application .getCurrent(); // Gets a thread that will handle the task of continuously // writing the representation into the input side of the pipe Runnable task = new Runnable() { public void run() { try { java.io.OutputStream os = pipe.getOutputStream(); representation.write(os); os.flush(); os.close(); } catch (IOException ioe) { Context.getCurrentLogger() .log(Level.FINE, "Error while writing to the piped input stream.", ioe); } } }; if (application != null && application.getTaskService() != null) { application.getTaskService().execute(task); } else { new Thread(task).start(); } result = pipe.getInputStream(); } else { Context.getCurrentLogger() .log(Level.WARNING, "The GAE edition is unable to get an InputStream out of an OutputRepresentation."); } return result; } /** * Converts the representation to a string value. Be careful when using this * method as the conversion of large content to a string fully stored in * memory can result in OutOfMemoryErrors being thrown. * * @param representation * The representation to convert. * @return The representation as a string value. */ public static String getText(Representation representation) throws IOException { String result = null; if (representation.isAvailable()) { if (representation.getSize() == 0) { result = ""; } else { java.io.StringWriter sw = new java.io.StringWriter(); representation.write(sw); sw.flush(); result = sw.toString(); } } return result; } /** * Converts a char array into a byte array using the default character set. * * @param chars * The source characters. * @return The result bytes. */ public static byte[] toByteArray(char[] chars) { return toByteArray(chars, java.nio.charset.Charset.defaultCharset() .name()); } /** * Converts a char array into a byte array using the default character set. * * @param chars * The source characters. * @param charsetName * The character set to use. * @return The result bytes. */ public static byte[] toByteArray(char[] chars, String charsetName) { java.nio.CharBuffer cb = java.nio.CharBuffer.wrap(chars); java.nio.ByteBuffer bb = java.nio.charset.Charset.forName(charsetName) .encode(cb); byte[] r = new byte[bb.remaining()]; bb.get(r); return r; } /** * Converts a byte array into a character array using the default character * set. * * @param bytes * The source bytes. * @return The result characters. */ public static char[] toCharArray(byte[] bytes) { return toCharArray(bytes, java.nio.charset.Charset.defaultCharset() .name()); } /** * Converts a byte array into a character array using the default character * set. * * @param bytes * The source bytes. * @param charsetName * The character set to use. * @return The result characters. */ public static char[] toCharArray(byte[] bytes, String charsetName) { java.nio.ByteBuffer bb = java.nio.ByteBuffer.wrap(bytes); java.nio.CharBuffer cb = java.nio.charset.Charset.forName(charsetName) .decode(bb); char[] r = new char[cb.remaining()]; cb.get(r); return r; } /** * Converts a byte array into an hexadecimal string. * * @param byteArray * The byte array to convert. * @return The hexadecimal string. */ public static String toHexString(byte[] byteArray) { final char[] hexChars = new char[2 * byteArray.length]; int i = 0; for (final byte b : byteArray) { hexChars[i++] = HEXDIGITS[(b >> 4) & 0xF]; hexChars[i++] = HEXDIGITS[b & 0xF]; } return new String(hexChars); } /** * Converts an input stream to a string.
    * As this method uses the InputstreamReader class, the default character * set is used for decoding the input stream. * * @see InputStreamReader class * @see #toString(InputStream, CharacterSet) * @param inputStream * The input stream. * @return The converted string. */ public static String toString(InputStream inputStream) { return toString(inputStream, null); } /** * Converts an input stream to a string using the specified character set * for decoding the input stream. Once read, the input stream is closed. * * @see InputStreamReader class * @param inputStream * The input stream. * @param characterSet * The character set * @return The converted string. */ public static String toString(InputStream inputStream, CharacterSet characterSet) { String result = null; if (inputStream != null) { try { if (characterSet != null) { result = toString(new InputStreamReader(inputStream, characterSet.getName())); } else { result = toString(new InputStreamReader(inputStream)); } inputStream.close(); } catch (Exception e) { // Returns an empty string } } return result; } /** * Converts a reader to a string. * * @see InputStreamReader * class * @param reader * The characters reader. * @return The converted string. */ public static String toString(Reader reader) { String result = null; if (reader != null) { try { StringBuilder sb = new StringBuilder(); BufferedReader br = (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader, IoUtils.getBufferSize()); char[] buffer = new char[2048]; int charsRead = br.read(buffer); while (charsRead != -1) { sb.append(buffer, 0, charsRead); charsRead = br.read(buffer); } br.close(); result = sb.toString(); } catch (Exception e) { // Returns an empty string } } return result; } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private BioUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/package.html0000664000175000017500000000012311757206350025403 0ustar jamespagejamespage Supports input and output work.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/io/WriterOutputStream.java0000664000175000017500000000406411757206346027653 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; // [excludes gwt] /** * Outputstream wrapping a character writer. * * @author Kevin Conaway */ public class WriterOutputStream extends OutputStream { /** The wrapped writer. */ private final Writer writer; /** * Constructor. * * @param writer * The wrapped writer. */ public WriterOutputStream(Writer writer) { this.writer = writer; } @Override public void close() throws IOException { super.close(); this.writer.close(); } @Override public void flush() throws IOException { super.flush(); this.writer.flush(); } @Override public void write(int b) throws IOException { this.writer.write(b); } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/IoUtils.java0000664000175000017500000000443511757206350025367 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.BufferedReader; /** * IO manipulation utilities. * * @author Thierry Boileau */ public class IoUtils { /** The buffer size. */ public static final int BUFFER_SIZE = 8192; /** * Returns the size to use when instantiating buffered items such as * instances of the {@link BufferedReader} class. It looks for the System * property "org.restlet.engine.io.buffer.size" and if not defined, uses the * {@link #BUFFER_SIZE}. * * @return The size to use when instantiating buffered items. */ public static int getBufferSize() { int result = BUFFER_SIZE; try { result = Integer.parseInt(System .getProperty("org.restlet.engine.io.buffer.size")); } catch (NumberFormatException nfe) { result = BUFFER_SIZE; } return result; } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private IoUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/SelectorFactory.java0000664000175000017500000000714711757206346027117 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.IOException; import java.nio.channels.Selector; import java.util.EmptyStackException; import java.util.Stack; // [excludes gwt] /** * Factory used to dispatch/share Selector. * * @author Jean-Francois Arcand */ public class SelectorFactory { /** The maximum number of Selector to create. */ public static final int MAX_SELECTORS = 20; /** The number of attempts to find an available selector. */ public static final int MAX_ATTEMPTS = 2; /** Cache of Selector. */ private static final Stack SELECTORS = new Stack(); /** The timeout before we exit. */ public static final long TIMEOUT = 5000; /** Creates the Selector. */ static { try { for (int i = 0; i < MAX_SELECTORS; i++) { SELECTORS.add(Selector.open()); } } catch (IOException ex) { // do nothing. } } /** * Get an exclusive Selector. * * @return An exclusive Selector. */ public final static Selector getSelector() { synchronized (SELECTORS) { Selector selector = null; try { if (SELECTORS.size() != 0) { selector = SELECTORS.pop(); } } catch (EmptyStackException ex) { } int attempts = 0; try { while ((selector == null) && (attempts < MAX_ATTEMPTS)) { SELECTORS.wait(TIMEOUT); try { if (SELECTORS.size() != 0) { selector = SELECTORS.pop(); } } catch (EmptyStackException ex) { break; } attempts++; } } catch (InterruptedException ex) { } return selector; } } /** * Returns the Selector to the cache. * * @param selector * The Selector to return. */ public final static void returnSelector(Selector selector) { synchronized (SELECTORS) { SELECTORS.push(selector); if (SELECTORS.size() == 1) { SELECTORS.notify(); } } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/io/TraceInputStream.java0000664000175000017500000000470611757206346027237 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.io; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * Filter input stream that sends a copy of all data on the standard console. * * @author Jerome Louvel */ public class TraceInputStream extends FilterInputStream { /** * Constructor. * * @param in * The input stream to wrap. */ public TraceInputStream(InputStream in) { super(in); } @Override public int read() throws IOException { int result = super.read(); synchronized (System.out) { System.out.write(result); } return result; } @Override public int read(byte[] b) throws IOException { int result = super.read(b); if (result != -1) { synchronized (System.out) { System.out.write(b, 0, result); } } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { int result = super.read(b, off, len); if (result != -1) { synchronized (System.out) { System.out.write(b, off, result); } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/security/0000775000175000017500000000000011757206350024366 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/engine/security/DefaultSslContextFactory.java0000664000175000017500000004650011757206346032206 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.security; import java.io.FileInputStream; import java.security.KeyStore; import java.security.SecureRandom; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import org.restlet.data.Parameter; import org.restlet.util.Series; /** * This SslContextFactory makes it possible to configure most basic options when * building an SSLContext. *

    * In short, two instances of KeyStore are used when configuring an SSLContext: * the keystore (which contains the public and private keys and certificates to * be used locally) and the trust store (which generally holds the CA * certificates to be trusted when connecting to a remote host). Both keystore * and trust store are KeyStores. When not explicitly set using the setters of * this class, the values will default to the default system properties, * following the behavior described in the JSSE reference guide. *

    *

    * There is more information in the JSSE Reference Guide. *

    * * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) * @see SSLContext * @see KeyStore */ public class DefaultSslContextFactory extends SslContextFactory { /** * Name of the KeyManager algorithm. */ private volatile String keyManagerAlgorithm = System.getProperty( "ssl.KeyManagerFactory.algorithm", KeyManagerFactory .getDefaultAlgorithm()); /** * Password for the key in the keystore (as a String). */ private volatile char[] keyStoreKeyPassword = (System.getProperty( "javax.net.ssl.keyPassword", System .getProperty("javax.net.ssl.keyStorePassword")) != null) ? System .getProperty("javax.net.ssl.keyPassword", System.getProperty("javax.net.ssl.keyStorePassword")) .toCharArray() : null; /** * Password for the keystore (as a String). */ private volatile char[] keyStorePassword = (System .getProperty("javax.net.ssl.keyStorePassword") != null) ? System .getProperty("javax.net.ssl.keyStorePassword").toCharArray() : null; /** * Path to the KeyStore file. */ private volatile String keyStorePath = System .getProperty("javax.net.ssl.keyStore"); /** * Name of the keystore provider. */ private volatile String keyStoreProvider = System .getProperty("javax.net.ssl.keyStoreProvider"); /** * KeyStore type of the keystore. */ private volatile String keyStoreType = System .getProperty("javax.net.ssl.keyStoreType"); /** * Name of the SecureRandom algorithm. */ private volatile String secureRandomAlgorithm = null; /** * Name of the protocol to use when creating the SSLContext. */ private volatile String secureSocketProtocol = "TLS"; /** * Name of the TrustManager algorithm. */ private volatile String trustManagerAlgorithm = System.getProperty( "ssl.TrustManagerFactory.algorithm", TrustManagerFactory .getDefaultAlgorithm()); /** * Password for the trust store keystore. */ private volatile char[] trustStorePassword = (System .getProperty("javax.net.ssl.trustStorePassword") != null) ? System .getProperty("javax.net.ssl.trustStorePassword").toCharArray() : null; /** * Path to the trust store (keystore) file. */ private volatile String trustStorePath = System .getProperty("javax.net.ssl.trustStore"); /** * Name of the trust store (keystore) provider. */ private volatile String trustStoreProvider = System .getProperty("javax.net.ssl.trustStoreProvider"); /** * KeyStore type of the trust store. */ private volatile String trustStoreType = System .getProperty("javax.net.ssl.trustStoreType"); /** * This class is likely to contain sensitive information; cloning is * therefore not allowed. */ @Override protected final DefaultSslContextFactory clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } /** * Creates a configured and initialised SSLContext from the values set via * the various setters of this class. If keyStorePath, * keyStoreProvider, keyStoreType are all * null, the SSLContext will be initialised with a * null array of KeyManagers. Similarly, if * trustStorePath, trustStoreProvider, * trustStoreType are all null, a * null array of TrustManagers will be used. * * @see SSLContext#init(javax.net.ssl.KeyManager[], * javax.net.ssl.TrustManager[], SecureRandom) */ @Override public SSLContext createSslContext() throws Exception { KeyManagerFactory kmf = null; if ((this.keyStorePath != null) || (this.keyStoreProvider != null) || (this.keyStoreType != null)) { /* * Loads the key store. */ final KeyStore keyStore = (this.keyStoreProvider != null) ? KeyStore .getInstance( (this.keyStoreType != null) ? this.keyStoreType : KeyStore.getDefaultType(), this.keyStoreProvider) : KeyStore .getInstance((this.keyStoreType != null) ? this.keyStoreType : KeyStore.getDefaultType()); FileInputStream keyStoreInputStream = null; try { keyStoreInputStream = ((this.keyStorePath != null) && (!"NONE" .equals(this.keyStorePath))) ? new FileInputStream( this.keyStorePath) : null; keyStore.load(keyStoreInputStream, this.keyStorePassword); } finally { if (keyStoreInputStream != null) { keyStoreInputStream.close(); } } /* * Creates the key-manager factory. */ kmf = KeyManagerFactory.getInstance(this.keyManagerAlgorithm); kmf.init(keyStore, this.keyStoreKeyPassword); } TrustManagerFactory tmf = null; if ((this.trustStorePath != null) || (this.trustStoreProvider != null) || (this.trustStoreType != null)) { /* * Loads the trust store. */ final KeyStore trustStore = (this.trustStoreProvider != null) ? KeyStore .getInstance( (this.trustStoreType != null) ? this.trustStoreType : KeyStore.getDefaultType(), this.trustStoreProvider) : KeyStore .getInstance((this.trustStoreType != null) ? this.trustStoreType : KeyStore.getDefaultType()); FileInputStream trustStoreInputStream = null; try { trustStoreInputStream = ((this.trustStorePath != null) && (!"NONE" .equals(this.trustStorePath))) ? new FileInputStream( this.trustStorePath) : null; trustStore.load(trustStoreInputStream, this.trustStorePassword); } finally { if (trustStoreInputStream != null) { trustStoreInputStream.close(); } } /* * Creates the trust-manager factory. */ tmf = TrustManagerFactory.getInstance(this.trustManagerAlgorithm); tmf.init(trustStore); } /* * Creates the SSLContext. */ final SSLContext sslContext = SSLContext .getInstance(this.secureSocketProtocol); SecureRandom sr = null; if (this.secureRandomAlgorithm != null) { sr = SecureRandom.getInstance(this.secureRandomAlgorithm); } sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, sr); return sslContext; } /** * Returns the secure socket protocol name, "TLS" by default. * * @return The secure socket protocol. */ public String getSecureSocketProtocol() { return this.secureSocketProtocol; } /** * Sets the following options according to parameters that may have been set * up directly in the HttpsServerHelper parameters. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Setter of this classParameter nameValue typeDefault valueDescription
    setKeyStorePathkeystorePathString${user.home}/.keystoreSSL keystore path.
    setKeyStorePasswordkeystorePasswordStringSSL keystore password.
    setKeyStoreTypekeystoreTypeStringJKSSSL keystore type
    setKeyStoreKeyPasswordkeyPasswordStringSSL key password.
    setKeyManagerAlgorithmcertAlgorithmStringSunX509SSL certificate algorithm.
    setSecureSocketProtocolsslProtocolStringTLSSSL protocol.
    * * @param helperParameters * Typically, the parameters that would have been obtained from * HttpsServerHelper.getParameters() * */ @Override public void init(Series helperParameters) { setKeyStorePath(helperParameters.getFirstValue("keystorePath", System .getProperty("javax.net.ssl.keyStore"))); setKeyStorePassword(helperParameters.getFirstValue("keystorePassword", System.getProperty("javax.net.ssl.keyStorePassword", ""))); setKeyStoreType(helperParameters.getFirstValue("keystoreType", System .getProperty("javax.net.ssl.keyStoreType"))); setKeyStoreKeyPassword(helperParameters.getFirstValue("keyPassword", System.getProperty("javax.net.ssl.keyPassword"))); if (this.keyStoreKeyPassword == null) { this.keyStoreKeyPassword = this.keyStorePassword; } setTrustStorePath(helperParameters.getFirstValue("truststorePath", System.getProperty("javax.net.ssl.trustStore"))); setTrustStorePassword(helperParameters.getFirstValue( "truststorePassword", System .getProperty("javax.net.ssl.trustStorePassword"))); setTrustStoreType(helperParameters.getFirstValue("truststoreType", System.getProperty("javax.net.ssl.trustStoreType"))); setKeyManagerAlgorithm(helperParameters.getFirstValue("certAlgorithm", "SunX509")); setSecureSocketProtocol(helperParameters.getFirstValue("sslProtocol", "TLS")); } /** * Sets the KeyManager algorithm. The default value is that of the * ssl.KeyManagerFactory.algorithm system property, or * "SunX509" if the system property has not been set up. * * @param keyManagerAlgorithm * The KeyManager algorithm. */ public void setKeyManagerAlgorithm(String keyManagerAlgorithm) { this.keyManagerAlgorithm = keyManagerAlgorithm; } /** * Sets the password of the key in the keystore. The default value is that * of the javax.net.ssl.keyPassword system property, falling back to * javax.net.ssl.keyStorePassword. This system property name is not * standard. * * @param keyStoreKeyPassword * The password of the key in the keystore. */ public final void setKeyStoreKeyPassword(char[] keyStoreKeyPassword) { this.keyStoreKeyPassword = keyStoreKeyPassword; } /** * Sets the password of the key in the keystore. The default value is that * of the javax.net.ssl.keyPassword system property, falling back to * javax.net.ssl.keyStorePassword. This system property name is not * standard. * * @param keyStoreKeyPassword * The password of the key in the keystore. */ public final void setKeyStoreKeyPassword(String keyStoreKeyPassword) { this.keyStoreKeyPassword = (keyStoreKeyPassword != null) ? keyStoreKeyPassword .toCharArray() : null; } /** * Sets the keystore password. The default value is that of the * javax.net.ssl.keyStorePassword system property. * * @param keyStorePassword * Sets the keystore password. */ public final void setKeyStorePassword(char[] keyStorePassword) { this.keyStorePassword = keyStorePassword; } /** * Sets the keystore password. The default value is that of the * javax.net.ssl.keyStorePassword system property. * * @param keyStorePassword * Sets the keystore password. */ public final void setKeyStorePassword(String keyStorePassword) { this.keyStorePassword = (keyStorePassword != null) ? keyStorePassword .toCharArray() : null; } /** * Sets the path to the keystore file. The default value is that of the * javax.net.ssl.keyStore system property. * * @param keyStorePath * The path to the keystore file. */ public final void setKeyStorePath(String keyStorePath) { this.keyStorePath = keyStorePath; } /** * Sets the name of the keystore provider. The default value is that of the * javax.net.ssl.keyStoreProvider system property. * * @param keyStoreProvider * The name of the keystore provider. */ public void setKeyStoreProvider(String keyStoreProvider) { this.keyStoreProvider = keyStoreProvider; } /** * Sets the KeyStore type of the keystore. The default value is that of the * javax.net.ssl.keyStoreType system property. * * @param keyStoreType * The KeyStore type of the keystore. */ public final void setKeyStoreType(String keyStoreType) { this.keyStoreType = keyStoreType; } /** * Sets the SecureRandom algorithm. The default value is null, in * which case the default SecureRandom would be used. * * @param secureRandomAlgorithm * The SecureRandom algorithm. */ public void setSecureRandomAlgorithm(String secureRandomAlgorithm) { this.secureRandomAlgorithm = secureRandomAlgorithm; } /** * Sets the secure socket protocol name, "TLS" by default. Typically, this * will be either "TLS" or "SSLv3". This is the name used when instantiating * the SSLContext. * * @param secureSocketProtocol * Name of the secure socket protocol to use. */ public void setSecureSocketProtocol(String secureSocketProtocol) { this.secureSocketProtocol = secureSocketProtocol; } /** * Sets the TrustManager algorithm. The default value is that of the * ssl.TrustManagerFactory.algorithm system property, or * "SunX509" if the system property has not been set up. * * @param trustManagerAlgorithm * The TrustManager algorithm. */ public void setTrustManagerAlgorithm(String trustManagerAlgorithm) { this.trustManagerAlgorithm = trustManagerAlgorithm; } /** * Sets the password of the trust store KeyStore. The default value is that * of the javax.net.ssl.trustStorePassword system property. * * @param trustStorePassword * The password of the trust store KeyStore. */ public final void setTrustStorePassword(char[] trustStorePassword) { this.trustStorePassword = trustStorePassword; } /** * Sets the password of the trust store KeyStore. The default value is that * of the javax.net.ssl.trustStorePassword system property. * * @param trustStorePassword * The password of the trust store KeyStore. */ public final void setTrustStorePassword(String trustStorePassword) { this.trustStorePassword = (trustStorePassword != null) ? trustStorePassword .toCharArray() : null; } /** * Sets the path to the trust store KeyStore. The default value is that of * the javax.net.ssl.trustStore system property. * * @param trustStorePath * The trustStorePath to set */ public final void setTrustStorePath(String trustStorePath) { this.trustStorePath = trustStorePath; } /** * Sets the name of the trust store provider. The default value is that of * the javax.net.ssl.trustStoreProvider system property. * * @param trustStoreProvider * The name of the trust store provider. */ public final void setTrustStoreProvider(String trustStoreProvider) { this.trustStoreProvider = trustStoreProvider; } /** * Sets the KeyStore type of the trust store. The default value is that of * the javax.net.ssl.trustStoreType system property. * * @param trustStoreType * The KeyStore type of the trust store. */ public final void setTrustStoreType(String trustStoreType) { this.trustStoreType = trustStoreType; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/security/SmtpPlainHelper.java0000664000175000017500000000537711757206346030321 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.security; import java.io.CharArrayWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.restlet.Request; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Parameter; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.util.Base64; import org.restlet.util.Series; /** * Implements the SMTP PLAIN authentication. * * @author Jerome Louvel */ public class SmtpPlainHelper extends AuthenticatorHelper { /** * Constructor. */ public SmtpPlainHelper() { super(ChallengeScheme.SMTP_PLAIN, true, false); } @Override public void formatRawResponse(ChallengeWriter cw, ChallengeResponse challenge, Request request, Series httpHeaders) { try { final CharArrayWriter credentials = new CharArrayWriter(); credentials.write("^@"); credentials.write(challenge.getIdentifier()); credentials.write("^@"); credentials.write(challenge.getSecret()); cw.append(Base64.encode(credentials.toCharArray(), "US-ASCII", false)); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Unsupported encoding, unable to encode credentials"); } catch (IOException e) { throw new RuntimeException( "Unexpected exception, unable to encode credentials", e); } } } restlet-2.0.14/org.restlet/src/org/restlet/engine/security/RoleMapping.java0000664000175000017500000000450511757206350027452 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.security; import org.restlet.security.Group; import org.restlet.security.Role; import org.restlet.security.User; /** * Mapping from an organization or a user or a group to a role. * * @author Jerome Louvel */ public class RoleMapping { /** * The source of the mapping. It must be an instance of one of these * classes: {@link User} or {@link Group}. */ private volatile Object source; /** The target role of the mapping. */ private volatile Role target; /** * Default constructor. */ public RoleMapping() { this(null, null); } /** * Constructor. * * @param source * @param target */ public RoleMapping(Object source, Role target) { super(); this.source = source; this.target = target; } public Object getSource() { return source; } public Role getTarget() { return target; } public void setSource(Object source) { this.source = source; } public void setTarget(Role target) { this.target = target; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/security/package.html0000664000175000017500000000011511757206350026644 0ustar jamespagejamespage Supports security.

    @since Restlet 2.0 restlet-2.0.14/org.restlet/src/org/restlet/engine/security/SslContextFactory.java0000664000175000017500000000446111757206346030701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.security; import javax.net.ssl.SSLContext; import org.restlet.data.Parameter; import org.restlet.util.Series; /** * This is an abstract factory that produces configured and initialised * instances of SSLContext. Concrete implementations of SslContextFactory must * implement {@link #createSslContext()}, which should typically consist of: * *

     *    SSLContext sslContext = SSLContext.getInstance(...);
     *    ...
     *    sslContext.init(..., ..., ...);
     *    return sslContext;
     * 
    * * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) * @see SSLContext */ public abstract class SslContextFactory { /** * Creates a configured and initialized SSLContext. * * @return A configured and initialized SSLContext. * @throws Exception */ public abstract SSLContext createSslContext() throws Exception; /** * Initialize the factory with the given connector parameters. * * @param parameters * The connector parameters. */ public abstract void init(Series parameters); } restlet-2.0.14/org.restlet/src/org/restlet/engine/security/AuthenticatorUtils.java0000664000175000017500000004234311757206350031072 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.security; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.AuthenticationInfo; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.engine.Engine; import org.restlet.engine.http.header.ChallengeRequestReader; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.header.ParameterReader; import org.restlet.security.Guard; import org.restlet.util.Series; /** * Authentication utilities. * * @author Jerome Louvel * @author Ray Waldin (ray@waldin.net) */ @SuppressWarnings("deprecation") public class AuthenticatorUtils { /** * Indicates if any of the objects is null. * * @param objects * The objects to test. * @return True if any of the objects is null. */ public static boolean anyNull(Object... objects) { for (final Object o : objects) { if (o == null) { return true; } } return false; } /** * Indicates if the request is properly authenticated. By default, this * delegates credentials checking to checkSecret(). * * @param request * The request to authenticate. * @param guard * The associated guard to callback. * @return -1 if the given credentials were invalid, 0 if no credentials * were found and 1 otherwise. * @see Guard#checkSecret(Request, String, char[]) * @deprecated See new org.restlet.security package. */ @Deprecated public static int authenticate(Request request, Guard guard) { int result = Guard.AUTHENTICATION_MISSING; if (guard.getScheme() != null) { // An authentication scheme has been defined, // the request must be authenticated final ChallengeResponse cr = request.getChallengeResponse(); if (cr != null) { if (guard.getScheme().equals(cr.getScheme())) { final AuthenticatorHelper helper = Engine.getInstance() .findHelper(cr.getScheme(), false, true); if (helper != null) { result = helper.authenticate(cr, request, guard); } else { throw new IllegalArgumentException("Challenge scheme " + guard.getScheme() + " not supported by the Restlet engine."); } } else { // The challenge schemes are incompatible, we need to // challenge the client } } else { // No challenge response found, we need to challenge the client } } if (request.getChallengeResponse() != null) { // Update the challenge response accordingly request.getChallengeResponse().setAuthenticated( result == Guard.AUTHENTICATION_VALID); } // Update the client info accordingly request.getClientInfo().setAuthenticated( result == Guard.AUTHENTICATION_VALID); return result; } /** * Challenges the client by adding a challenge request to the response and * by setting the status to CLIENT_ERROR_UNAUTHORIZED. * * @param response * The response to update. * @param stale * Indicates if the new challenge is due to a stale response. * @param guard * The associated guard to callback. * @deprecated See new org.restlet.security package. */ @Deprecated public static void challenge(Response response, boolean stale, Guard guard) { final AuthenticatorHelper helper = Engine.getInstance().findHelper( guard.getScheme(), false, true); if (helper != null) { helper.challenge(response, stale, guard); } else { throw new IllegalArgumentException("Challenge scheme " + guard.getScheme() + " not supported by the Restlet engine."); } } /** * Formats an authentication information as a HTTP header value. The header * is {@link HeaderConstants#HEADER_AUTHENTICATION_INFO}. * * @param info * The authentication information to format. * @return The {@link HeaderConstants#HEADER_AUTHENTICATION_INFO} header * value. */ public static String formatAuthenticationInfo(AuthenticationInfo info) { ChallengeWriter cw = new ChallengeWriter(); boolean firstParameter = true; if (info != null) { if (info.getNextServerNonce() != null && info.getNextServerNonce().length() > 0) { cw.setFirstChallengeParameter(firstParameter); cw.appendQuotedChallengeParameter("nextnonce", info.getNextServerNonce()); firstParameter = false; } if (info.getQuality() != null && info.getQuality().length() > 0) { cw.setFirstChallengeParameter(firstParameter); cw.appendChallengeParameter("qop", info.getQuality()); firstParameter = false; if (info.getNonceCount() > 0) { cw.appendChallengeParameter("nc", formatNonceCount(info.getNonceCount())); } } if (info.getResponseDigest() != null && info.getResponseDigest().length() > 0) { cw.setFirstChallengeParameter(firstParameter); cw.appendQuotedChallengeParameter("rspauth", info.getResponseDigest()); firstParameter = false; } if (info.getClientNonce() != null && info.getClientNonce().length() > 0) { cw.setFirstChallengeParameter(firstParameter); cw.appendChallengeParameter("cnonce", info.getClientNonce()); firstParameter = false; } } return cw.toString(); } /** * Formats a given nonce count as a HTTP header value. The header is * {@link HeaderConstants#HEADER_AUTHENTICATION_INFO}. * * @param nonceCount * The given nonce count. * @return The formatted value of the given nonce count. */ public static String formatNonceCount(int nonceCount) { StringBuilder result = new StringBuilder( Integer.toHexString(nonceCount)); while (result.length() < 8) { result.insert(0, '0'); } return result.toString(); } /** * Formats a challenge request as a HTTP header value. The header is * {@link HeaderConstants#HEADER_WWW_AUTHENTICATE}. * * @param challenge * The challenge request to format. * @param response * The parent response. * @param httpHeaders * The current response HTTP headers. * @return The {@link HeaderConstants#HEADER_WWW_AUTHENTICATE} header value. */ public static String formatRequest(ChallengeRequest challenge, Response response, Series httpHeaders) { String result = null; if (challenge != null) { AuthenticatorHelper helper = Engine.getInstance().findHelper( challenge.getScheme(), false, true); if (helper != null) { try { result = helper.formatRequest(challenge, response, httpHeaders); } catch (IOException e) { Context.getCurrentLogger().log( Level.WARNING, "Unable to format the challenge request: " + challenge, e); } } else { result = "?"; Context.getCurrentLogger().warning( "Challenge scheme " + challenge.getScheme() + " not supported by the Restlet engine."); } } return result; } /** * Formats a challenge response as a HTTP header value. The header is * {@link HeaderConstants#HEADER_AUTHORIZATION}. * * @param challenge * The challenge response to format. * @param request * The parent request. * @param httpHeaders * The current request HTTP headers. * @return The {@link HeaderConstants#HEADER_AUTHORIZATION} header value. * @throws IOException */ public static String formatResponse(ChallengeResponse challenge, Request request, Series httpHeaders) { String result = null; AuthenticatorHelper helper = Engine.getInstance().findHelper( challenge.getScheme(), true, false); if (helper != null) { result = helper.formatResponse(challenge, request, httpHeaders); } else { result = "?"; Context.getCurrentLogger().warning( "Challenge scheme " + challenge.getScheme() + " not supported by the Restlet engine."); } return result; } /** * Parses the "Authentication-Info" header. * * @param header * The header value to parse. * @return The equivalent {@link AuthenticationInfo} instance. * @throws IOException */ public static AuthenticationInfo parseAuthenticationInfo(String header) { AuthenticationInfo result = null; ParameterReader hr = new ParameterReader(header); try { String nextNonce = null; String qop = null; String responseAuth = null; String cnonce = null; int nonceCount = 0; Parameter param = hr.readValue(); while (param != null) { try { if ("nextnonce".equals(param.getName())) { nextNonce = param.getValue(); } else if ("qop".equals(param.getName())) { qop = param.getValue(); } else if ("rspauth".equals(param.getName())) { responseAuth = param.getValue(); } else if ("cnonce".equals(param.getName())) { cnonce = param.getValue(); } else if ("nc".equals(param.getName())) { nonceCount = Integer.parseInt(param.getValue(), 16); } if (hr.skipValueSeparator()) { param = hr.readValue(); } else { param = null; } } catch (Exception e) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to parse the authentication info header parameter", e); } } result = new AuthenticationInfo(nextNonce, nonceCount, cnonce, qop, responseAuth); } catch (IOException e) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to parse the authentication info header: " + header, e); } return result; } /** * Parses an authenticate header into a list of challenge request. The * header is {@link HeaderConstants#HEADER_WWW_AUTHENTICATE}. * * @param header * The HTTP header value to parse. * @param httpHeaders * The current response HTTP headers. * @return The list of parsed challenge request. */ public static List parseRequest(Response response, String header, Series httpHeaders) { List result = new ArrayList(); if (header != null) { result = new ChallengeRequestReader(header).readValues(); for (ChallengeRequest cr : result) { // Give a chance to the authenticator helper to do further // parsing AuthenticatorHelper helper = Engine.getInstance().findHelper( cr.getScheme(), true, false); if (helper != null) { helper.parseRequest(cr, response, httpHeaders); } else { Context.getCurrentLogger().warning( "Couldn't find any helper support the " + cr.getScheme() + " challenge scheme."); } } } return result; } /** * Parses an authorization header into a challenge response. The header is * {@link HeaderConstants#HEADER_AUTHORIZATION}. * * @param request * The parent request. * @param header * The authorization header. * @param httpHeaders * The current request HTTP headers. * @return The parsed challenge response. */ public static ChallengeResponse parseResponse(Request request, String header, Series httpHeaders) { ChallengeResponse result = null; if (header != null) { int space = header.indexOf(' '); if (space != -1) { String scheme = header.substring(0, space); String rawValue = header.substring(space + 1); result = new ChallengeResponse(new ChallengeScheme("HTTP_" + scheme, scheme)); result.setRawValue(rawValue); } } if (result != null) { // Give a chance to the authenticator helper to do further parsing AuthenticatorHelper helper = Engine.getInstance().findHelper( result.getScheme(), true, false); if (helper != null) { helper.parseResponse(result, request, httpHeaders); } else { Context.getCurrentLogger().warning( "Couldn't find any helper support the " + result.getScheme() + " challenge scheme."); } } return result; } /** * Updates a ChallengeResponse object according to given request and * response. * * @param challengeResponse * The challengeResponse to update. * @param request * The request. * @param response * The response. */ public static void update(ChallengeResponse challengeResponse, Request request, Response response) { ChallengeRequest challengeRequest = null; for (ChallengeRequest c : response.getChallengeRequests()) { if (challengeResponse.getScheme().equals(c.getScheme())) { challengeRequest = c; break; } } String realm = null; String nonce = null; if (challengeRequest != null) { realm = challengeRequest.getRealm(); nonce = challengeRequest.getServerNonce(); challengeResponse.setOpaque(challengeRequest.getOpaque()); } challengeResponse.setRealm(realm); challengeResponse.setServerNonce(nonce); challengeResponse.setDigestRef(new Reference(request.getResourceRef() .getPath())); } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private AuthenticatorUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/security/SslUtils.java0000664000175000017500000002274011757206346027025 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.security; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import org.restlet.Context; import org.restlet.engine.RestletHelper; /** * Various HTTPS utilities. * * @author Jerome Louvel */ public class SslUtils { /** Cache of SSL key sizes for various cipher suites. */ private final static ConcurrentMap keySizesCache = new ConcurrentHashMap(); /** * Extract the SSL key size of a given cipher suite. * * @param sslCipherSuite * The SSL cipher suite. * @return The SSL key size. */ public static Integer extractKeySize(String sslCipherSuite) { Integer keySize = keySizesCache.get(sslCipherSuite); if (keySize == null) { final int encAlgorithmIndex = sslCipherSuite.indexOf("WITH_"); if (encAlgorithmIndex >= 0) { final String encAlgorithm = sslCipherSuite .substring(encAlgorithmIndex + 5); /* * (Encryption algorithms and key sizes, quoted from RFC 2246) * * Key Expanded Effective IV Block Cipher Type Material Key * Material Key Bits Size Size * * NULL Stream 0 0 0 0 N/A IDEA_CBC Block 16 16 128 8 8 * RC2_CBC_40 Block 5 16 40 8 8 RC4_40 Stream 5 16 40 0 N/A * RC4_128 Stream 16 16 128 0 N/A DES40_CBC Block 5 8 40 8 8 * DES_CBC Block 8 8 56 8 8 3DES_EDE_CBC Block 24 24 168 8 8 */ if (encAlgorithm != null) { if (encAlgorithm.startsWith("NULL_")) { keySize = Integer.valueOf(0); } else if (encAlgorithm.startsWith("IDEA_CBC_")) { keySize = Integer.valueOf(128); } else if (encAlgorithm.startsWith("RC2_CBC_40_")) { keySize = Integer.valueOf(40); } else if (encAlgorithm.startsWith("RC4_40_")) { keySize = Integer.valueOf(40); } else if (encAlgorithm.startsWith("RC4_128_")) { keySize = Integer.valueOf(128); } else if (encAlgorithm.startsWith("DES40_CBC_")) { keySize = Integer.valueOf(40); } else if (encAlgorithm.startsWith("DES_CBC_")) { keySize = Integer.valueOf(56); } else if (encAlgorithm.startsWith("3DES_EDE_CBC_")) { keySize = Integer.valueOf(168); } else { final StringTokenizer st = new StringTokenizer( encAlgorithm, "_"); while (st.hasMoreTokens()) { try { keySize = Integer.valueOf(st.nextToken()); break; } catch (NumberFormatException e) { // Tokens that are not integers are ignored. } } } if (keySize != null) { keySizesCache.put(sslCipherSuite, keySize); } } } } return keySize; } /** * Returns the list of disabled cipher suites. * * @param helper * The helper to use. * @return The list of disabled cipher suites. */ public static String[] getDisabledCipherSuites(RestletHelper helper) { List disabledCipherSuites = new ArrayList(); String[] disabledCipherSuitesParams = helper.getHelpedParameters() .getValuesArray("disabledCipherSuites"); for (String disabledCipherSuitesParam : disabledCipherSuitesParams) { StringTokenizer st = new StringTokenizer(disabledCipherSuitesParam); while (st.hasMoreElements()) { disabledCipherSuites.add(st.nextToken()); } } return disabledCipherSuites.size() > 0 ? disabledCipherSuites .toArray(new String[0]) : null; } /** * Returns the list of enabled cipher suites. * * @param helper * The helper to use. * @return The list of enabled cipher suites. */ public static String[] getEnabledCipherSuites(RestletHelper helper) { List enabledCipherSuites = new ArrayList(); String[] enabledCipherSuitesParams = helper.getHelpedParameters() .getValuesArray("enabledCipherSuites"); for (String enabledCipherSuitesParam : enabledCipherSuitesParams) { StringTokenizer st = new StringTokenizer(enabledCipherSuitesParam); while (st.hasMoreElements()) { enabledCipherSuites.add(st.nextToken()); } } return enabledCipherSuites.size() > 0 ? enabledCipherSuites .toArray(new String[0]) : null; } /** * Returns the SSL context factory. It first look for a "sslContextFactory" * attribute (instance), then for a "sslContextFactory" parameter (class * name to instantiate). * * @param helper * The helper to use. * * @return The SSL context factory. */ public static SslContextFactory getSslContextFactory(RestletHelper helper) { SslContextFactory result = (SslContextFactory) ((helper.getContext() == null) ? null : helper.getContext().getAttributes().get("sslContextFactory")); if (result == null) { String[] sslContextFactoryNames = helper.getHelpedParameters() .getValuesArray("sslContextFactory"); if (sslContextFactoryNames != null) { for (String sslContextFactoryName : sslContextFactoryNames) { try { Class sslContextFactoryClass = Class .forName(sslContextFactoryName).asSubclass( SslContextFactory.class); result = sslContextFactoryClass.newInstance(); result.init(helper.getHelpedParameters()); } catch (ClassNotFoundException e) { Context.getCurrentLogger().log( Level.WARNING, "Unable to find SslContextFactory class: " + sslContextFactoryName, e); } catch (ClassCastException e) { Context .getCurrentLogger() .log( Level.WARNING, "Class " + sslContextFactoryName + " does not implement SslContextFactory.", e); } catch (InstantiationException e) { Context.getCurrentLogger().log( Level.WARNING, "Could not instantiate class " + sslContextFactoryName + " with default constructor.", e); } catch (IllegalAccessException e) { Context.getCurrentLogger().log( Level.WARNING, "Illegal access when instantiating class " + sslContextFactoryName + ".", e); } } } } if (result == null) { result = new DefaultSslContextFactory(); result.init(helper.getHelpedParameters()); } return result; } /** * Private constructor to ensure that the class acts as a true utility class * i.e. it isn't instantiable and extensible. */ private SslUtils() { } } restlet-2.0.14/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java0000664000175000017500000002724411757206346031221 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine.security; import java.io.IOException; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Digest; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.engine.Helper; import org.restlet.engine.http.header.ChallengeWriter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.security.Guard; import org.restlet.util.Series; /** * Base class for authentication helpers. * * @author Jerome Louvel */ @SuppressWarnings("deprecation") public abstract class AuthenticatorHelper extends Helper { /** The supported challenge scheme. */ private volatile ChallengeScheme challengeScheme; /** Indicates if client side authentication is supported. */ private volatile boolean clientSide; /** Indicates if server side authentication is supported. */ private volatile boolean serverSide; /** * Constructor. * * @param challengeScheme * The supported challenge scheme. * @param clientSide * Indicates if client side authentication is supported. * @param serverSide * Indicates if server side authentication is supported. */ public AuthenticatorHelper(ChallengeScheme challengeScheme, boolean clientSide, boolean serverSide) { this.challengeScheme = challengeScheme; this.clientSide = clientSide; this.serverSide = serverSide; } /** * Indicates if the call is properly authenticated. You are guaranteed that * the request has a challenge response with a scheme matching the one * supported by the plugin. * * @param cr * The challenge response in the request. * @param request * The request to authenticate. * @param guard * The associated guard to callback. * @return -1 if the given credentials were invalid, 0 if no credentials * were found and 1 otherwise. * @see Guard#checkSecret(Request, String, char[]) * @deprecated See new org.restlet.security package. */ @Deprecated public int authenticate(ChallengeResponse cr, Request request, Guard guard) { int result = Guard.AUTHENTICATION_MISSING; // The challenge schemes are compatible final String identifier = cr.getIdentifier(); final char[] secret = cr.getSecret(); // Check the credentials if ((identifier != null) && (secret != null)) { result = guard.checkSecret(request, identifier, secret) ? Guard.AUTHENTICATION_VALID : Guard.AUTHENTICATION_INVALID; } return result; } /** * Challenges the client by adding a challenge request to the response and * by setting the status to CLIENT_ERROR_UNAUTHORIZED. * * @param response * The response to update. * @param stale * Indicates if the new challenge is due to a stale response. * @param guard * The associated guard to callback. * @deprecated See new org.restlet.security package. */ @Deprecated public void challenge(Response response, boolean stale, Guard guard) { response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); response.getChallengeRequests().add( new ChallengeRequest(guard.getScheme(), guard.getRealm())); } /** * Formats a challenge request as raw credentials. * * @param cw * The header writer to update. * @param challenge * The challenge request to format. * @param response * The parent response. * @param httpHeaders * The current request HTTP headers. */ public void formatRawRequest(ChallengeWriter cw, ChallengeRequest challenge, Response response, Series httpHeaders) throws IOException { } /** * Formats a challenge response as raw credentials. * * @param cw * The header writer to update. * @param challenge * The challenge response to format. * @param request * The parent request. * @param httpHeaders * The current request HTTP headers. */ public void formatRawResponse(ChallengeWriter cw, ChallengeResponse challenge, Request request, Series httpHeaders) { } /** * Formats a challenge request as a HTTP header value. The header is * {@link HeaderConstants#HEADER_WWW_AUTHENTICATE}. The default * implementation relies on * {@link #formatRawRequest(ChallengeWriter, ChallengeRequest, Response, Series)} * to append all parameters from {@link ChallengeRequest#getParameters()}. * * @param challenge * The challenge request to format. * @param response * The parent response. * @param httpHeaders * The current response HTTP headers. * @return The {@link HeaderConstants#HEADER_WWW_AUTHENTICATE} header value. * @throws IOException */ public String formatRequest(ChallengeRequest challenge, Response response, Series httpHeaders) throws IOException { ChallengeWriter cw = new ChallengeWriter(); cw.append(challenge.getScheme().getTechnicalName()).appendSpace(); if (challenge.getRawValue() != null) { cw.append(challenge.getRawValue()); } else { formatRawRequest(cw, challenge, response, httpHeaders); } return cw.toString(); } /** * Formats a challenge response as a HTTP header value. The header is * {@link HeaderConstants#HEADER_AUTHORIZATION}. The default implementation * relies on * {@link #formatRawResponse(ChallengeWriter, ChallengeResponse, Request, Series)} * unless some custom credentials are provided via * * @link ChallengeResponse#getCredentials()}. * * @param challenge * The challenge response to format. * @param request * The parent request. * @param httpHeaders * The current request HTTP headers. * @return The {@link HeaderConstants#HEADER_AUTHORIZATION} header value. */ public String formatResponse(ChallengeResponse challenge, Request request, Series httpHeaders) { ChallengeWriter hb = new ChallengeWriter(); hb.append(challenge.getScheme().getTechnicalName()).appendSpace(); if (challenge.getRawValue() != null) { hb.append(challenge.getRawValue()); } else { formatRawResponse(hb, challenge, request, httpHeaders); } return hb.toString(); } /** * Formats the secret of a challenge response. By default, it returns the * given password. * * @param challengeResponse * The challenge response. * @param request * The request if available. * @param response * The response if available. * @param identifier * The identifier. * @param baseSecret * The base secret used to compute the secret. * @param baseSecretAlgorithm * The digest algorithm of the base secret (@see {@link Digest} * class). * @return The formatted secret of a challenge response. */ public char[] formatSecret(ChallengeResponse challengeResponse, Request request, Response response, String identifier, char[] baseSecret, String baseSecretAlgorithm) { if (baseSecret != null) { return baseSecret; } return null; } /** * Returns the supported challenge scheme. * * @return The supported challenge scheme. */ public ChallengeScheme getChallengeScheme() { return this.challengeScheme; } /** * Returns the context's logger. * * @return The context's logger. */ public Logger getLogger() { return Context.getCurrentLogger(); } /** * Indicates if client side authentication is supported. * * @return True if client side authentication is supported. */ public boolean isClientSide() { return this.clientSide; } /** * Indicates if server side authentication is supported. * * @return True if server side authentication is supported. */ public boolean isServerSide() { return this.serverSide; } /** * Parses an authenticate header into a challenge request. The header is * {@link HeaderConstants#HEADER_WWW_AUTHENTICATE}. * * @param challenge * The challenge request to update. * @param response * The parent response. * @param httpHeaders * The current response HTTP headers. */ public void parseRequest(ChallengeRequest challenge, Response response, Series httpHeaders) { } /** * Parses an authorization header into a challenge response. The header is * {@link HeaderConstants#HEADER_AUTHORIZATION}. * * @param challenge * The challenge response to update. * @param request * The parent request. * @param httpHeaders * The current request HTTP headers. */ public void parseResponse(ChallengeResponse challenge, Request request, Series httpHeaders) { } /** * Sets the supported challenge scheme. * * @param challengeScheme * The supported challenge scheme. */ public void setChallengeScheme(ChallengeScheme challengeScheme) { this.challengeScheme = challengeScheme; } /** * Indicates if client side authentication is supported. * * @param clientSide * True if client side authentication is supported. */ public void setClientSide(boolean clientSide) { this.clientSide = clientSide; } /** * Indicates if server side authentication is supported. * * @param serverSide * True if server side authentication is supported. */ public void setServerSide(boolean serverSide) { this.serverSide = serverSide; } } restlet-2.0.14/org.restlet/src/org/restlet/engine/Helper.java0000664000175000017500000000256511757206346024616 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; /** * Abstract marker class parent of all engine helpers. * * @author Jerome Louvel */ public abstract class Helper { } restlet-2.0.14/org.restlet/src/org/restlet/engine/ClientHelper.java0000664000175000017500000000340311757206346025745 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.engine; import org.restlet.Client; /** * Client connector helper. * * @author Jerome Louvel */ public class ClientHelper extends ConnectorHelper { /** * Constructor. * * @param client * The client to help. */ public ClientHelper(Client client) { super(client); } /** * Returns the connection timeout. * * @return The connection timeout. */ public int getConnectTimeout() { return getHelped().getConnectTimeout(); } } restlet-2.0.14/org.restlet/src/org/restlet/routing/0000775000175000017500000000000011757206350022741 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/routing/Route.java0000664000175000017500000004433511757206346024720 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.regex.Pattern; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Cookie; import org.restlet.data.Form; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Filter scoring the affinity of calls with the attached Restlet. The score is * used by an associated Router in order to determine the most appropriate * Restlet for a given call. The routing is based on a reference template. It * also supports the extraction of some attributes from a call.
    *
    * Multiple extractions can be defined, based on the query string of the * resource reference, on the request form (ex: posted from a browser) or on * cookies.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see org.restlet.routing.Template * @author Jerome Louvel * @deprecated Use {@link TemplateRoute} instead. */ @Deprecated public class Route extends TemplateRoute { /** Internal class holding extraction information. */ private static final class ExtractInfo { /** Target attribute name. */ protected volatile String attribute; /** Indicates how to handle repeating values. */ protected volatile boolean first; /** Name of the parameter to look for. */ protected volatile String parameter; /** * Constructor. * * @param attribute * Target attribute name. * @param parameter * Name of the parameter to look for. * @param first * Indicates how to handle repeating values. */ public ExtractInfo(String attribute, String parameter, boolean first) { this.attribute = attribute; this.parameter = parameter; this.first = first; } } /** Internal class holding validation information. */ private static final class ValidateInfo { /** Name of the attribute to look for. */ protected volatile String attribute; /** Format of the attribute value, using Regex pattern syntax. */ protected volatile String format; /** Indicates if the attribute presence is required. */ protected volatile boolean required; /** * Constructor. * * @param attribute * Name of the attribute to look for. * @param required * Indicates if the attribute presence is required. * @param format * Format of the attribute value, using Regex pattern syntax. */ public ValidateInfo(String attribute, boolean required, String format) { this.attribute = attribute; this.required = required; this.format = format; } } /** The list of cookies to extract. */ private volatile List cookieExtracts; /** The list of request entity parameters to extract. */ private volatile List entityExtracts; /** The list of query parameters to extract. */ private volatile List queryExtracts; /** The list of attribute validations. */ private volatile List validations; /** * Constructor behaving as a simple extractor filter. * * @param next * The next Restlet. */ public Route(Restlet next) { this(null, (Template) null, next); } /** * Constructor. The URIs will be matched agains the template using the * {@link Template#MODE_STARTS_WITH} matching mode. This can be changed by * getting the template and calling {@link Template#setMatchingMode(int)} * with {@link Template#MODE_EQUALS} for exact matching. * * @param router * The parent router. * @param uriTemplate * The URI template. * @param next * The next Restlet. */ public Route(Router router, String uriTemplate, Restlet next) { this(router, new Template(uriTemplate, Template.MODE_STARTS_WITH, Variable.TYPE_URI_SEGMENT, "", true, false), next); } /** * Constructor. * * @param router * The parent router. * @param template * The URI template. * @param next * The next Restlet. */ public Route(Router router, Template template, Restlet next) { super(router, template, next); } /** * Allows filtering before its handling by the target Restlet. By default it * parses the template variable, adjust the base reference, then extracts * the attributes from form parameters (query, cookies, entity) and finally * tries to validates the variables as indicated by the * {@link #validate(String, boolean, String)} method. * * @param request * The request to filter. * @param response * The response to filter. * @return The continuation status. */ @Override protected int beforeHandle(Request request, Response response) { // 1 - Parse the template variables and adjust the base reference if (getTemplate() != null) { final String remainingPart = request.getResourceRef() .getRemainingPart(false, isMatchingQuery()); final int matchedLength = getTemplate().parse(remainingPart, request); if (getLogger().isLoggable(Level.FINER)) { getLogger().finer( "Attempting to match this pattern: " + getTemplate().getPattern() + " >> " + matchedLength); } if (matchedLength != -1) { // Updates the context final String matchedPart = remainingPart.substring(0, matchedLength); Reference baseRef = request.getResourceRef().getBaseRef(); if (baseRef == null) { if (matchedLength > 0) { baseRef = new Reference(matchedPart); } } else { baseRef = new Reference(baseRef.toString(false, false) + matchedPart); } request.getResourceRef().setBaseRef(baseRef); if (getLogger().isLoggable(Level.FINE)) { getLogger().fine( "New base URI: " + request.getResourceRef().getBaseRef()); getLogger().fine( "New remaining part: " + request.getResourceRef() .getRemainingPart(false, isMatchingQuery())); } if (getLogger().isLoggable(Level.FINE)) { getLogger().fine( "Delegating the call to the target Restlet"); } } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } // 2 - Extract the attributes from form parameters (query, cookies, // entity). extractAttributes(request, response); // 3 - Validate the attributes extracted (or others) validateAttributes(request, response); return CONTINUE; } /** * Extracts the attributes value from the request. * * @param request * The request to process. * @param response * The response to process. */ private void extractAttributes(Request request, Response response) { // Extract the query parameters if (!getQueryExtracts().isEmpty()) { final Form form = request.getResourceRef().getQueryAsForm(); if (form != null) { for (final ExtractInfo ei : getQueryExtracts()) { if (ei.first) { request.getAttributes().put(ei.attribute, form.getFirstValue(ei.parameter)); } else { request.getAttributes().put(ei.attribute, form.subList(ei.parameter)); } } } } // Extract the request entity parameters if (!getEntityExtracts().isEmpty()) { Representation entity = request.getEntity(); if (entity != null) { final Form form = new Form(entity); for (final ExtractInfo ei : getEntityExtracts()) { if (ei.first) { request.getAttributes().put(ei.attribute, form.getFirstValue(ei.parameter)); } else { request.getAttributes().put(ei.attribute, form.subList(ei.parameter)); } } } } // Extract the cookie parameters if (!getCookieExtracts().isEmpty()) { final Series cookies = request.getCookies(); if (cookies != null) { for (final ExtractInfo ei : getCookieExtracts()) { if (ei.first) { request.getAttributes().put(ei.attribute, cookies.getFirstValue(ei.parameter)); } else { request.getAttributes().put(ei.attribute, cookies.subList(ei.parameter)); } } } } } /** * Extracts an attribute from the request cookies. * * @param attribute * The name of the request attribute to set. * @param cookieName * The name of the cookies to extract. * @param first * Indicates if only the first cookie should be set. Otherwise as * a List instance might be set in the attribute value. * @return The current Filter. */ public Route extractCookie(String attribute, String cookieName, boolean first) { getCookieExtracts().add(new ExtractInfo(attribute, cookieName, first)); return this; } /** * Extracts an attribute from the request entity form. * * @param attribute * The name of the request attribute to set. * @param parameter * The name of the entity form parameter to extract. * @param first * Indicates if only the first cookie should be set. Otherwise as * a List instance might be set in the attribute value. * @return The current Filter. */ public Route extractEntity(String attribute, String parameter, boolean first) { getEntityExtracts().add(new ExtractInfo(attribute, parameter, first)); return this; } /** * Extracts an attribute from the query string of the resource reference. * * @param attribute * The name of the request attribute to set. * @param parameter * The name of the query string parameter to extract. * @param first * Indicates if only the first cookie should be set. Otherwise as * a List instance might be set in the attribute value. * @return The current Filter. */ public Route extractQuery(String attribute, String parameter, boolean first) { getQueryExtracts().add(new ExtractInfo(attribute, parameter, first)); return this; } /** * Returns the list of query extracts. * * @return The list of query extracts. */ private List getCookieExtracts() { // Lazy initialization with double-check. List ce = this.cookieExtracts; if (ce == null) { synchronized (this) { ce = this.cookieExtracts; if (ce == null) { this.cookieExtracts = ce = new CopyOnWriteArrayList(); } } } return ce; } /** * Returns the list of query extracts. * * @return The list of query extracts. */ private List getEntityExtracts() { // Lazy initialization with double-check. List ee = this.entityExtracts; if (ee == null) { synchronized (this) { ee = this.entityExtracts; if (ee == null) { this.entityExtracts = ee = new CopyOnWriteArrayList(); } } } return ee; } /** * Returns the list of query extracts. * * @return The list of query extracts. */ private List getQueryExtracts() { // Lazy initialization with double-check. List qe = this.queryExtracts; if (qe == null) { synchronized (this) { qe = this.queryExtracts; if (qe == null) { this.queryExtracts = qe = new CopyOnWriteArrayList(); } } } return qe; } /** * Returns the list of attribute validations. * * @return The list of attribute validations. */ private List getValidations() { // Lazy initialization with double-check. List v = this.validations; if (v == null) { synchronized (this) { v = this.validations; if (v == null) { this.validations = v = new CopyOnWriteArrayList(); } } } return v; } /** * Checks the request attributes for presence, format, etc. If the check * fails, then a response status CLIENT_ERROR_BAD_REQUEST is returned with * the proper status description. * * @param attribute * Name of the attribute to look for. * @param required * Indicates if the attribute presence is required. * @param format * Format of the attribute value, using Regex pattern syntax. */ public void validate(String attribute, boolean required, String format) { getValidations().add(new ValidateInfo(attribute, required, format)); } /** * Validates the attributes from the request. * * @param request * The request to process. * @param response * The response to process. */ private void validateAttributes(Request request, Response response) { if (this.validations != null) { for (final ValidateInfo validate : getValidations()) { if (validate.required && !request.getAttributes().containsKey( validate.attribute)) { response .setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to find the \"" + validate.attribute + "\" attribute in the request. Please check your request."); } else if (validate.format != null) { final Object value = request.getAttributes().get( validate.attribute); if (value == null) { response .setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to validate the \"" + validate.attribute + "\" attribute with a null value. Please check your request."); } else { if (!Pattern.matches(validate.format, value.toString())) { response .setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to validate the value of the \"" + validate.attribute + "\" attribute. The expected format is: " + validate.format + " (Java Regex). Please check your request."); } } } } } } } restlet-2.0.14/org.restlet/src/org/restlet/routing/Validator.java0000664000175000017500000001736111757206346025546 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Pattern; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Status; /** * Filter validating attributes from a call. Validation is verified based on * regex pattern matching.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel * @see Pattern */ public class Validator extends Filter { /** Internal class holding validation information. */ private static final class ValidateInfo { /** Name of the attribute to look for. */ protected String attribute; /** Format of the attribute value, using Regex pattern syntax. */ protected String format; /** Indicates if the attribute presence is required. */ protected boolean required; /** * Constructor. * * @param attribute * Name of the attribute to look for. * @param required * Indicates if the attribute presence is required. * @param format * Format of the attribute value, using Regex pattern syntax. */ public ValidateInfo(String attribute, boolean required, String format) { this.attribute = attribute; this.required = required; this.format = format; } } /** The list of attribute validations. */ private volatile List validations; /** * Constructor. */ public Validator() { this(null); } /** * Constructor. * * @param context * The context. */ public Validator(Context context) { this(context, null); } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. */ public Validator(Context context, Restlet next) { super(context, next); } /** * Allows filtering before its handling by the target Restlet. By default it * parses the template variable, adjust the base reference, then extracts * the attributes from form parameters (query, cookies, entity) and finally * tries to validate the variables as indicated by the * {@link #validate(String, boolean, String)} method. * * @param request * The request to filter. * @param response * The response to filter. * @return The {@link Filter#CONTINUE} status. */ @Override protected int beforeHandle(Request request, Response response) { if (this.validations != null) { for (ValidateInfo validate : getValidations()) { if (validate.required && !request.getAttributes().containsKey( validate.attribute)) { response .setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to find the \"" + validate.attribute + "\" attribute in the request. Please check your request."); } else if (validate.format != null) { Object value = request.getAttributes().get( validate.attribute); if ((value != null) && !Pattern.matches(validate.format, value .toString())) { response .setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to validate the value of the \"" + validate.attribute + "\" attribute. The expected format is: " + validate.format + " (Java Regex). Please check your request."); } } } } return CONTINUE; } /** * Returns the list of attribute validations. * * @return The list of attribute validations. */ private List getValidations() { // Lazy initialization with double-check. List v = this.validations; if (v == null) { synchronized (this) { v = this.validations; if (v == null) { this.validations = v = new CopyOnWriteArrayList(); } } } return v; } /** * Checks the request attributes for presence or format. If the check fails, * then a response status CLIENT_ERROR_BAD_REQUEST is returned with the * proper status description. * * @param attribute * Name of the attribute to look for. * @param required * Indicates if the attribute presence is required. * @param format * Format of the attribute value, using Regex pattern syntax. */ public void validate(String attribute, boolean required, String format) { getValidations().add(new ValidateInfo(attribute, required, format)); } /** * Checks the request attributes for format only. If the check fails, then a * response status CLIENT_ERROR_BAD_REQUEST is returned with the proper * status description. * * @param attribute * Name of the attribute to look for. * @param format * Format of the attribute value, using Regex pattern syntax. */ public void validateFormat(String attribute, String format) { getValidations().add(new ValidateInfo(attribute, false, format)); } /** * Checks the request attributes for presence only. If the check fails, then * a response status CLIENT_ERROR_BAD_REQUEST is returned with the proper * status description. * * @param attribute * Name of the attribute to look for. */ public void validatePresence(String attribute) { getValidations().add(new ValidateInfo(attribute, true, null)); } } restlet-2.0.14/org.restlet/src/org/restlet/routing/Extractor.java0000664000175000017500000002366611757206350025574 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Cookie; import org.restlet.data.Form; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Filter extracting attributes from a call. Multiple extractions can be * defined, based on the query string of the resource reference, on the request * form (ex: posted from a browser) or on cookies.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class Extractor extends Filter { /** Internal class holding extraction information. */ private static final class ExtractInfo { /** Target attribute name. */ protected String attribute; /** Indicates how to handle repeating values. */ protected boolean first; /** Name of the parameter to look for. */ protected String parameter; /** * Constructor. * * @param attribute * Target attribute name. * @param parameter * Name of the parameter to look for. * @param first * Indicates how to handle repeating values. */ public ExtractInfo(String attribute, String parameter, boolean first) { this.attribute = attribute; this.parameter = parameter; this.first = first; } } /** The list of cookies to extract. */ private volatile List cookieExtracts; /** The list of request entity parameters to extract. */ private volatile List entityExtracts; /** The list of query parameters to extract. */ private volatile List queryExtracts; /** * Constructor. */ public Extractor() { this(null); } /** * Constructor. * * @param context * The context. */ public Extractor(Context context) { this(context, null); } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. */ public Extractor(Context context, Restlet next) { super(context, next); } /** * Allows filtering before its handling by the target Restlet. By default it * extracts the attributes from form parameters (query, cookies, entity) and * finally puts them in the request's attributes ( * {@link Request#getAttributes()}). * * @param request * The request to filter. * @param response * The response to filter. * @return The continuation status. */ @Override protected int beforeHandle(Request request, Response response) { // Extract the query parameters if (!getQueryExtracts().isEmpty()) { final Form form = request.getResourceRef().getQueryAsForm(); if (form != null) { for (final ExtractInfo ei : getQueryExtracts()) { if (ei.first) { String value = form.getFirstValue(ei.parameter); if (value != null) { request.getAttributes().put(ei.attribute, value); } } else { request.getAttributes().put(ei.attribute, form.subList(ei.parameter)); } } } } // Extract the request entity parameters if (!getEntityExtracts().isEmpty()) { Representation entity = request.getEntity(); if (entity != null) { final Form form = new Form(entity); for (final ExtractInfo ei : getEntityExtracts()) { if (ei.first) { String value = form.getFirstValue(ei.parameter); if (value != null) { request.getAttributes().put(ei.attribute, value); } } else { request.getAttributes().put(ei.attribute, form.subList(ei.parameter)); } } } } // Extract the cookie parameters if (!getCookieExtracts().isEmpty()) { final Series cookies = request.getCookies(); if (cookies != null) { for (final ExtractInfo ei : getCookieExtracts()) { if (ei.first) { String value = cookies.getFirstValue(ei.parameter); if (value != null) { request.getAttributes().put(ei.attribute, value); } } else { request.getAttributes().put(ei.attribute, cookies.subList(ei.parameter)); } } } } return CONTINUE; } /** * Extracts an attribute from the request cookies. * * @param attribute * The name of the request attribute to set. * @param cookieName * The name of the cookies to extract. * @param first * Indicates if only the first cookie should be set. Otherwise as * a List instance might be set in the attribute value. */ public void extractFromCookie(String attribute, String cookieName, boolean first) { getCookieExtracts().add(new ExtractInfo(attribute, cookieName, first)); } /** * Extracts an attribute from the request entity form. * * @param attribute * The name of the request attribute to set. * @param parameter * The name of the entity form parameter to extract. * @param first * Indicates if only the first cookie should be set. Otherwise as * a List instance might be set in the attribute value. */ public void extractFromEntity(String attribute, String parameter, boolean first) { getEntityExtracts().add(new ExtractInfo(attribute, parameter, first)); } /** * Extracts an attribute from the query string of the resource reference. * * @param attribute * The name of the request attribute to set. * @param parameter * The name of the query string parameter to extract. * @param first * Indicates if only the first cookie should be set. Otherwise as * a List instance might be set in the attribute value. */ public void extractFromQuery(String attribute, String parameter, boolean first) { getQueryExtracts().add(new ExtractInfo(attribute, parameter, first)); } /** * Returns the list of query extracts. * * @return The list of query extracts. */ private List getCookieExtracts() { // Lazy initialization with double-check. List ce = this.cookieExtracts; if (ce == null) { synchronized (this) { ce = this.cookieExtracts; if (ce == null) { this.cookieExtracts = ce = new CopyOnWriteArrayList(); } } } return ce; } /** * Returns the list of query extracts. * * @return The list of query extracts. */ private List getEntityExtracts() { // Lazy initialization with double-check. List ee = this.entityExtracts; if (ee == null) { synchronized (this) { ee = this.entityExtracts; if (ee == null) { this.entityExtracts = ee = new CopyOnWriteArrayList(); } } } return ee; } /** * Returns the list of query extracts. * * @return The list of query extracts. */ private List getQueryExtracts() { // Lazy initialization with double-check. List qe = this.queryExtracts; if (qe == null) { synchronized (this) { qe = this.queryExtracts; if (qe == null) { this.queryExtracts = qe = new CopyOnWriteArrayList(); } } } return qe; } } restlet-2.0.14/org.restlet/src/org/restlet/routing/Template.java0000664000175000017500000010177611757206346025400 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.util.Resolver; /** * String template with a pluggable model. Supports both formatting and parsing. * The template variables can be inserted using the "{name}" syntax and * described using the modifiable map of variable descriptors. When no * descriptor is found for a given variable, the template logic uses its default * variable property initialized using the default {@link Variable} constructor.
    *
    * Note that the variable descriptors can be changed before the first parsing or * matching call. After that point, changes won't be taken into account.
    *
    * Format and parsing methods are specially available to deal with requests and * response. See {@link #format(Request, Response)} and * {@link #parse(String, Request)}. * * @see Resolver * @see URI Template * specification * @author Jerome Louvel */ public class Template { /** Mode where all characters must match the template and size be identical. */ public static final int MODE_EQUALS = 2; /** Mode where characters at the beginning must match the template. */ public static final int MODE_STARTS_WITH = 1; /** * Appends to a pattern a repeating group of a given content based on a * class of characters. * * @param pattern * The pattern to append to. * @param content * The content of the group. * @param required * Indicates if the group is required. */ private static void appendClass(StringBuilder pattern, String content, boolean required) { pattern.append("("); if (content.equals(".")) { // Special case for the TYPE_ALL variable type because the // dot looses its meaning inside a character class pattern.append(content); } else { pattern.append("[").append(content).append(']'); } if (required) { pattern.append("+"); } else { pattern.append("*"); } pattern.append(")"); } /** * Appends to a pattern a repeating group of a given content based on a * non-capturing group. * * @param pattern * The pattern to append to. * @param content * The content of the group. * @param required * Indicates if the group is required. */ private static void appendGroup(StringBuilder pattern, String content, boolean required) { pattern.append("((?:").append(content).append(')'); if (required) { pattern.append("+"); } else { pattern.append("*"); } pattern.append(")"); } /** * Returns the Regex pattern string corresponding to a variable. * * @param variable * The variable. * @return The Regex pattern string corresponding to a variable. */ private static String getVariableRegex(Variable variable) { String result = null; if (variable.isFixed()) { result = "(" + Pattern.quote(variable.getDefaultValue()) + ")"; } else { // Expressions to create character classes final String ALL = "."; final String ALPHA = "a-zA-Z"; final String DIGIT = "\\d"; final String ALPHA_DIGIT = ALPHA + DIGIT; final String HEXA = DIGIT + "ABCDEFabcdef"; final String URI_UNRESERVED = ALPHA_DIGIT + "\\-\\.\\_\\~"; final String URI_GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@"; final String URI_SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\="; final String URI_RESERVED = URI_GEN_DELIMS + URI_SUB_DELIMS; final String WORD = "\\w"; // Basic rules expressed by the HTTP rfc. final String CRLF = "\\r\\n"; final String CTL = "\\p{Cntrl}"; final String LWS = CRLF + "\\ \\t"; final String SEPARATOR = "\\(\\)\\<\\>\\@\\,\\;\\:\\[\\]\"\\/\\\\?\\=\\{\\}\\ \\t"; final String TOKEN = "[^" + SEPARATOR + "]"; final String COMMENT = "[^" + CTL + "]" + "[^\\(\\)]" + LWS; final String COMMENT_ATTRIBUTE = "[^\\;\\(\\)]"; // Expressions to create non-capturing groups final String PCT_ENCODED = "\\%[" + HEXA + "][" + HEXA + "]"; // final String PCHAR = "[" + URI_UNRESERVED + "]|(?:" + PCT_ENCODED // + ")|[" + URI_SUB_DELIMS + "]|\\:|\\@"; final String PCHAR = "[" + URI_UNRESERVED + URI_SUB_DELIMS + "\\:\\@]|(?:" + PCT_ENCODED + ")"; final String QUERY = PCHAR + "|\\/|\\?"; final String FRAGMENT = QUERY; final String URI_PATH = PCHAR + "|\\/"; final String URI_ALL = "[" + URI_RESERVED + URI_UNRESERVED + "]|(?:" + PCT_ENCODED + ")"; // Special case of query parameter characters final String QUERY_PARAM_DELIMS = "\\!\\$\\'\\(\\)\\*\\+\\,\\;"; final String QUERY_PARAM_CHAR = "[" + URI_UNRESERVED + QUERY_PARAM_DELIMS + "\\:\\@]|(?:" + PCT_ENCODED + ")"; final String QUERY_PARAM = QUERY_PARAM_CHAR + "|\\/|\\?"; final StringBuilder coreRegex = new StringBuilder(); switch (variable.getType()) { case Variable.TYPE_ALL: appendClass(coreRegex, ALL, variable.isRequired()); break; case Variable.TYPE_ALPHA: appendClass(coreRegex, ALPHA, variable.isRequired()); break; case Variable.TYPE_DIGIT: appendClass(coreRegex, DIGIT, variable.isRequired()); break; case Variable.TYPE_ALPHA_DIGIT: appendClass(coreRegex, ALPHA_DIGIT, variable.isRequired()); break; case Variable.TYPE_URI_ALL: appendGroup(coreRegex, URI_ALL, variable.isRequired()); break; case Variable.TYPE_URI_UNRESERVED: appendClass(coreRegex, URI_UNRESERVED, variable.isRequired()); break; case Variable.TYPE_WORD: appendClass(coreRegex, WORD, variable.isRequired()); break; case Variable.TYPE_URI_FRAGMENT: appendGroup(coreRegex, FRAGMENT, variable.isRequired()); break; case Variable.TYPE_URI_PATH: appendGroup(coreRegex, URI_PATH, variable.isRequired()); break; case Variable.TYPE_URI_QUERY: appendGroup(coreRegex, QUERY, variable.isRequired()); break; case Variable.TYPE_URI_QUERY_PARAM: appendGroup(coreRegex, QUERY_PARAM, variable.isRequired()); break; case Variable.TYPE_URI_SEGMENT: appendGroup(coreRegex, PCHAR, variable.isRequired()); break; case Variable.TYPE_TOKEN: appendClass(coreRegex, TOKEN, variable.isRequired()); break; case Variable.TYPE_COMMENT: appendClass(coreRegex, COMMENT, variable.isRequired()); break; case Variable.TYPE_COMMENT_ATTRIBUTE: appendClass(coreRegex, COMMENT_ATTRIBUTE, variable.isRequired()); break; } result = coreRegex.toString(); } return result; } /** The default variable to use when no matching variable descriptor exists. */ private volatile Variable defaultVariable; /** True if the variables must be encoded when formatting the template. */ private volatile boolean encodingVariables; /** The logger to use. */ private volatile Logger logger; /** The matching mode to use when parsing a formatted reference. */ private volatile int matchingMode; /** The pattern to use for formatting or parsing. */ private volatile String pattern; /** The internal Regex pattern. */ private volatile Pattern regexPattern; /** The sequence of Regex variable names as found in the pattern string. */ private volatile List regexVariables; /** The map of variables associated to the route's template. */ private final Map variables; /** * Default constructor. Each variable matches any sequence of characters by * default. When parsing, the template will attempt to match the whole * template. When formatting, the variable are replaced by an empty string * if they don't exist in the model. * * @param pattern * The pattern to use for formatting or parsing. */ public Template(String pattern) { this(pattern, MODE_EQUALS, Variable.TYPE_ALL, "", true, false); } /** * Constructor. * * @param pattern * The pattern to use for formatting or parsing. * @param matchingMode * The matching mode to use when parsing a formatted reference. */ public Template(String pattern, int matchingMode) { this(pattern, matchingMode, Variable.TYPE_ALL, "", true, false); } /** * Constructor. * * @param pattern * The pattern to use for formatting or parsing. * @param matchingMode * The matching mode to use when parsing a formatted reference. * @param defaultType * The default type of variables with no descriptor. * @param defaultDefaultValue * The default value for null variables with no descriptor. * @param defaultRequired * The default required flag for variables with no descriptor. * @param defaultFixed * The default fixed value for variables with no descriptor. */ public Template(String pattern, int matchingMode, int defaultType, String defaultDefaultValue, boolean defaultRequired, boolean defaultFixed) { this(pattern, matchingMode, defaultType, defaultDefaultValue, defaultRequired, defaultFixed, false); } /** * Constructor. * * @param pattern * The pattern to use for formatting or parsing. * @param matchingMode * The matching mode to use when parsing a formatted reference. * @param defaultType * The default type of variables with no descriptor. * @param defaultDefaultValue * The default value for null variables with no descriptor. * @param defaultRequired * The default required flag for variables with no descriptor. * @param defaultFixed * The default fixed value for variables with no descriptor. * @param encodingVariables * True if the variables must be encoded when formatting the * template. */ public Template(String pattern, int matchingMode, int defaultType, String defaultDefaultValue, boolean defaultRequired, boolean defaultFixed, boolean encodingVariables) { this.logger = (logger == null) ? Context.getCurrentLogger() : logger; this.pattern = pattern; this.defaultVariable = new Variable(defaultType, defaultDefaultValue, defaultRequired, defaultFixed); this.matchingMode = matchingMode; this.variables = new ConcurrentHashMap(); this.regexPattern = null; this.encodingVariables = encodingVariables; } /** * Creates a formatted string based on the given map of values. * * @param values * The values to use when formatting. * @return The formatted string. * @see Resolver#createResolver(Map) */ public String format(Map values) { return format(Resolver.createResolver(values)); } /** * Creates a formatted string based on the given request and response. * * @param request * The request to use as a model. * @param response * The response to use as a model. * @return The formatted string. * @see Resolver#createResolver(Request, Response) */ public String format(Request request, Response response) { return format(Resolver.createResolver(request, response)); } /** * Creates a formatted string based on the given variable resolver. * * @param resolver * The variable resolver to use. * @return The formatted string. */ public String format(Resolver resolver) { final StringBuilder result = new StringBuilder(); StringBuilder varBuffer = null; char next; boolean inVariable = false; final int patternLength = getPattern().length(); for (int i = 0; i < patternLength; i++) { next = getPattern().charAt(i); if (inVariable) { if (Reference.isUnreserved(next)) { // Append to the variable name varBuffer.append(next); } else if (next == '}') { // End of variable detected if (varBuffer.length() == 0) { getLogger().warning( "Empty pattern variables are not allowed : " + this.regexPattern); } else { final String varName = varBuffer.toString(); Object varValue = resolver.resolve(varName); Variable var = getVariables().get(varName); // Use the default values instead if (varValue == null) { if (var == null) { var = getDefaultVariable(); } if (var != null) { varValue = var.getDefaultValue(); } } String varValueString = (varValue == null) ? null : varValue.toString(); if (this.encodingVariables) { // In case the values must be encoded. if (var != null) { result.append(var.encode(varValueString)); } else { result.append(Reference.encode(varValueString)); } } else { if ((var != null) && var.isEncodingOnFormat()) { result.append(Reference.encode(varValueString)); } else { result.append(varValueString); } } // Reset the variable name buffer varBuffer = new StringBuilder(); } inVariable = false; } else { getLogger().warning( "An invalid character was detected inside a pattern variable : " + this.regexPattern); } } else { if (next == '{') { inVariable = true; varBuffer = new StringBuilder(); } else if (next == '}') { getLogger().warning( "An invalid character was detected inside a pattern variable : " + this.regexPattern); } else { result.append(next); } } } return result.toString(); } /** * Returns the default variable. * * @return The default variable. */ public Variable getDefaultVariable() { return this.defaultVariable; } /** * Returns the logger to use. * * @return The logger to use. */ public Logger getLogger() { return this.logger; } /** * Returns the matching mode to use when parsing a formatted reference. * * @return The matching mode to use when parsing a formatted reference. */ public int getMatchingMode() { return this.matchingMode; } /** * Returns the pattern to use for formatting or parsing. * * @return The pattern to use for formatting or parsing. */ public String getPattern() { return this.pattern; } /** * Compiles the URI pattern into a Regex pattern. * * @return The Regex pattern. */ private Pattern getRegexPattern() { if (this.regexPattern == null) { synchronized (this) { if (this.regexPattern == null) { getRegexVariables().clear(); final StringBuilder patternBuffer = new StringBuilder(); StringBuilder varBuffer = null; char next; boolean inVariable = false; for (int i = 0; i < getPattern().length(); i++) { next = getPattern().charAt(i); if (inVariable) { if (Reference.isUnreserved(next)) { // Append to the variable name varBuffer.append(next); } else if (next == '}') { // End of variable detected if (varBuffer.length() == 0) { getLogger().warning( "Empty pattern variables are not allowed : " + this.regexPattern); } else { final String varName = varBuffer.toString(); final int varIndex = getRegexVariables() .indexOf(varName); if (varIndex != -1) { // The variable is used several times in // the pattern, ensure that this // constraint is enforced when parsing. patternBuffer.append("\\" + (varIndex + 1)); } else { // New variable detected. Insert a // capturing group. getRegexVariables().add(varName); Variable var = getVariables().get( varName); if (var == null) { var = getDefaultVariable(); } patternBuffer .append(getVariableRegex(var)); } // Reset the variable name buffer varBuffer = new StringBuilder(); } inVariable = false; } else { getLogger().warning( "An invalid character was detected inside a pattern variable : " + this.regexPattern); } } else { if (next == '{') { inVariable = true; varBuffer = new StringBuilder(); } else if (next == '}') { getLogger().warning( "An invalid character was detected inside a pattern variable : " + this.regexPattern); } else { patternBuffer.append(quote(next)); } } } this.regexPattern = Pattern.compile(patternBuffer .toString()); } } } return this.regexPattern; } /** * Returns the sequence of Regex variable names as found in the pattern * string. * * @return The sequence of Regex variable names as found in the pattern * string. */ private List getRegexVariables() { // Lazy initialization with double-check. List rv = this.regexVariables; if (rv == null) { synchronized (this) { rv = this.regexVariables; if (rv == null) { this.regexVariables = rv = new CopyOnWriteArrayList(); } } } return rv; } /** * Returns the list of variable names in the template. * * @return The list of variable names. */ public List getVariableNames() { final List result = new ArrayList(); StringBuilder varBuffer = null; char next; boolean inVariable = false; final String pattern = getPattern(); for (int i = 0; i < pattern.length(); i++) { next = pattern.charAt(i); if (inVariable) { if (Reference.isUnreserved(next)) { // Append to the variable name varBuffer.append(next); } else if (next == '}') { // End of variable detected if (varBuffer.length() == 0) { getLogger().warning( "Empty pattern variables are not allowed : " + this.pattern); } else { result.add(varBuffer.toString()); // Reset the variable name buffer varBuffer = new StringBuilder(); } inVariable = false; } else { getLogger().warning( "An invalid character was detected inside a pattern variable : " + this.pattern); } } else { if (next == '{') { inVariable = true; varBuffer = new StringBuilder(); } else if (next == '}') { getLogger().warning( "An invalid character was detected inside a pattern variable : " + this.pattern); } } } return result; } /** * Returns the modifiable map of variable descriptors. Creates a new * instance if no one has been set. Note that those variables are only * descriptors that can influence the way parsing and formatting is done, * they don't contain the actual value parsed. * * @return The modifiable map of variables. */ public synchronized Map getVariables() { return this.variables; } /** * Indicates if the variables must be encoded when formatting the template. * * @return True if the variables must be encoded when formatting the * template, false otherwise. * @deprecated Use {@link #isEncodingVariables()} instead. */ @Deprecated public boolean isEncodeVariables() { return this.encodingVariables; } /** * Indicates if the variables must be encoded when formatting the template. * * @return True if the variables must be encoded when formatting the * template, false otherwise. */ public boolean isEncodingVariables() { return isEncodeVariables(); } /** * Indicates if the current pattern matches the given formatted string. * * @param formattedString * The formatted string to match. * @return The number of matched characters or -1 if the match failed. */ public int match(String formattedString) { int result = -1; try { if (formattedString != null) { final Matcher matcher = getRegexPattern().matcher( formattedString); if ((getMatchingMode() == MODE_EQUALS) && matcher.matches()) { result = matcher.end(); } else if ((getMatchingMode() == MODE_STARTS_WITH) && matcher.lookingAt()) { result = matcher.end(); } } } catch (StackOverflowError soe) { getLogger().warning( "StackOverflowError exception encountered while matching this string : " + formattedString); } return result; } /** * Attempts to parse a formatted reference. If the parsing succeeds, the * given request's attributes are updated.
    * Note that the values parsed are directly extracted from the formatted * reference and are therefore not percent-decoded. * * @see Reference#decode(String) * * @param formattedString * The string to parse. * @param variables * The map of variables to update. * @return The number of matched characters or -1 if no character matched. */ public int parse(String formattedString, Map variables) { int result = -1; if (formattedString != null) { try { final Matcher matcher = getRegexPattern().matcher( formattedString); final boolean matched = ((getMatchingMode() == MODE_EQUALS) && matcher .matches()) || ((getMatchingMode() == MODE_STARTS_WITH) && matcher .lookingAt()); if (matched) { // Update the number of matched characters result = matcher.end(); // Update the attributes with the variables value String attributeName = null; String attributeValue = null; for (int i = 0; i < getRegexVariables().size(); i++) { attributeName = getRegexVariables().get(i); attributeValue = matcher.group(i + 1); final Variable var = getVariables().get(attributeName); if ((var != null) && var.isDecodingOnParse()) { variables.put(attributeName, Reference .decode(attributeValue)); } else { variables.put(attributeName, attributeValue); } } } } catch (StackOverflowError soe) { getLogger().warning( "StackOverflowError exception encountered while matching this string : " + formattedString); } } return result; } /** * Attempts to parse a formatted reference. If the parsing succeeds, the * given request's attributes are updated.
    * Note that the values parsed are directly extracted from the formatted * reference and are therefore not percent-decoded. * * @see Reference#decode(String) * * @param formattedString * The string to parse. * @param request * The request to update. * @return The number of matched characters or -1 if no character matched. */ public int parse(String formattedString, Request request) { return parse(formattedString, request.getAttributes()); } /** * Quotes special characters that could be taken for special Regex * characters. * * @param character * The character to quote if necessary. * @return The quoted character. */ private String quote(char character) { switch (character) { case '[': return "\\["; case ']': return "\\]"; case '.': return "\\."; case '\\': return "\\\\"; case '$': return "\\$"; case '^': return "\\^"; case '?': return "\\?"; case '*': return "\\*"; case '|': return "\\|"; case '(': return "\\("; case ')': return "\\)"; case ':': return "\\:"; case '-': return "\\-"; case '!': return "\\!"; case '<': return "\\<"; case '>': return "\\>"; default: return Character.toString(character); } } /** * Sets the variable to use, if no variable is given. * * @param defaultVariable */ public void setDefaultVariable(Variable defaultVariable) { this.defaultVariable = defaultVariable; } /** * Indicates if the variables must be encoded when formatting the template. * * @param encodingVariables * True if the variables must be encoded when formatting the * template. * @deprecated Use {@link #setEncodingVariables(boolean)} instead. */ @Deprecated public void setEncodeVariables(boolean encodingVariables) { this.encodingVariables = encodingVariables; } /** * Indicates if the variables must be encoded when formatting the template. * * @param encodingVariables * True if the variables must be encoded when formatting the * template. */ public void setEncodingVariables(boolean encodingVariables) { setEncodeVariables(encodingVariables); } /** * Sets the logger to use. * * @param logger * The logger to use. */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets the matching mode to use when parsing a formatted reference. * * @param matchingMode * The matching mode to use when parsing a formatted reference. */ public void setMatchingMode(int matchingMode) { this.matchingMode = matchingMode; } /** * Sets the pattern to use for formatting or parsing. * * @param pattern * The pattern to use for formatting or parsing. */ public void setPattern(String pattern) { this.pattern = pattern; this.regexPattern = null; } /** * Sets the modifiable map of variables. * * @param variables * The modifiable map of variables. */ public void setVariables(Map variables) { synchronized (this.variables) { if (variables != this.variables) { this.variables.clear(); if (variables != null) { this.variables.putAll(variables); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/routing/TemplateRoute.java0000664000175000017500000002552011757206346026407 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.util.logging.Level; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Reference; import org.restlet.data.Status; /** * Filter scoring the affinity of calls with the attached Restlet. The score is * used by an associated Router in order to determine the most appropriate * Restlet for a given call. The routing is based on a reference template.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see org.restlet.routing.Template * @author Jerome Louvel */ public class TemplateRoute extends Filter { /** * Indicates whether the query part should be taken into account when * matching a reference with the template. */ private volatile boolean matchingQuery; /** The parent router. */ private volatile Router router; /** The reference template to match. */ private volatile Template template; /** * Constructor behaving as a simple extractor filter. * * @param next * The next Restlet. */ public TemplateRoute(Restlet next) { this(null, (Template) null, next); } /** * Constructor. The URIs will be matched agains the template using the * {@link Template#MODE_STARTS_WITH} matching mode. This can be changed by * getting the template and calling {@link Template#setMatchingMode(int)} * with {@link Template#MODE_EQUALS} for exact matching. * * @param router * The parent router. * @param uriTemplate * The URI template. * @param next * The next Restlet. */ public TemplateRoute(Router router, String uriTemplate, Restlet next) { this(router, new Template(uriTemplate, Template.MODE_STARTS_WITH, Variable.TYPE_URI_SEGMENT, "", true, false), next); } /** * Constructor. * * @param router * The parent router. * @param template * The URI template. * @param next * The next Restlet. */ public TemplateRoute(Router router, Template template, Restlet next) { super(router == null ? null : router.getContext(), next); this.matchingQuery = (router == null) ? true : router .getDefaultMatchingQuery(); this.router = router; this.template = template; } /** * Allows filtering before its handling by the target Restlet. By default it * parses the template variable, adjust the base reference of the target * resource's reference. * * @param request * The request to filter. * @param response * The response to filter. * @return The continuation status. */ @Override protected int beforeHandle(Request request, Response response) { // 1 - Parse the template variables and adjust the base reference if (getTemplate() != null) { final String remainingPart = request.getResourceRef() .getRemainingPart(false, isMatchingQuery()); final int matchedLength = getTemplate().parse(remainingPart, request); if (getLogger().isLoggable(Level.FINER)) { getLogger().finer( "Attempting to match this pattern: " + getTemplate().getPattern() + " >> " + matchedLength); } if (matchedLength != -1) { // Updates the context final String matchedPart = remainingPart.substring(0, matchedLength); Reference baseRef = request.getResourceRef().getBaseRef(); if (baseRef == null) { baseRef = new Reference(matchedPart); } else { baseRef = new Reference(baseRef.toString(false, false) + matchedPart); } request.getResourceRef().setBaseRef(baseRef); if (getLogger().isLoggable(Level.FINE)) { getLogger().fine( "New base URI: " + request.getResourceRef().getBaseRef()); getLogger().fine( "New remaining part: " + request.getResourceRef() .getRemainingPart(false, isMatchingQuery())); } if (getLogger().isLoggable(Level.FINE)) { getLogger().fine( "Delegating the call to the target Restlet"); } } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } return CONTINUE; } /** * Returns the matching mode to use on the template when parsing a formatted * reference. * * @return The matching mode to use. */ public int getMatchingMode() { return getTemplate().getMatchingMode(); } /** * Indicates whether the query part should be taken into account when * matching a reference with the template. * * @return True if the query part of the reference should be taken into * account, false otherwise. * @deprecated Use {@link #isMatchingQuery()} instead. */ @Deprecated public boolean getMatchQuery() { return this.matchingQuery; } /** * Returns the parent router. * * @return The parent router. */ public Router getRouter() { return this.router; } /** * Returns the reference template to match. * * @return The reference template to match. */ public Template getTemplate() { return this.template; } /** * Indicates whether the query part should be taken into account when * matching a reference with the template. * * @return True if the query part of the reference should be taken into * account, false otherwise. */ public boolean isMatchingQuery() { return getMatchQuery(); } /** * Returns the score for a given call (between 0 and 1.0). * * @param request * The request to score. * @param response * The response to score. * @return The score for a given call (between 0 and 1.0). */ public float score(Request request, Response response) { float result = 0F; if ((getRouter() != null) && (request.getResourceRef() != null) && (getTemplate() != null)) { final String remainingPart = request.getResourceRef() .getRemainingPart(false, isMatchingQuery()); if (remainingPart != null) { final int matchedLength = getTemplate().match(remainingPart); if (matchedLength != -1) { final float totalLength = remainingPart.length(); if (totalLength > 0.0F) { result = getRouter().getRequiredScore() + (1.0F - getRouter().getRequiredScore()) * (matchedLength / totalLength); } else { result = 1.0F; } } } if (getLogger().isLoggable(Level.FINER)) { getLogger().finer( "Call score for the \"" + getTemplate().getPattern() + "\" URI pattern: " + result); } } return result; } /** * Sets the matching mode to use on the template when parsing a formatted * reference. * * @param matchingMode * The matching mode to use. */ public void setMatchingMode(int matchingMode) { getTemplate().setMatchingMode(matchingMode); } /** * Sets whether the matching should be done on the URI with or without query * string. * * @param matchingQuery * True if the matching should be done with the query string, * false otherwise. */ public void setMatchingQuery(boolean matchingQuery) { setMatchQuery(matchingQuery); } /** * Sets whether the matching should be done on the URI with or without query * string. * * @param matchingQuery * True if the matching should be done with the query string, * false otherwise. * @deprecated Use {@link #setMatchingQuery(boolean)} instead. */ @Deprecated public void setMatchQuery(boolean matchingQuery) { this.matchingQuery = matchingQuery; } /** * Sets the parent router. * * @param router * The parent router. */ public void setRouter(Router router) { this.router = router; } /** * Sets the reference template to match. * * @param template * The reference template to match. */ public void setTemplate(Template template) { this.template = template; } @Override public String toString() { return "\"" + ((getTemplate() == null) ? super.toString() : getTemplate() .getPattern()) + "\" -> " + ((getNext() == null) ? "null" : getNext().toString()); } } restlet-2.0.14/org.restlet/src/org/restlet/routing/Redirector.java0000664000175000017500000004166011757206350025715 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.util.logging.Level; import org.restlet.Application; import org.restlet.Component; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.representation.Representation; import org.restlet.util.Resolver; /** * Rewrites URIs then redirects the call or the client to a new destination. * There are various redirection modes that you can choose from: client-side * redirections ({@link #MODE_CLIENT_FOUND}, {@link #MODE_CLIENT_PERMANENT}, * {@link #MODE_CLIENT_SEE_OTHER}, {@link #MODE_CLIENT_TEMPORARY}) or * server-side redirections, similar to a reverse proxy ( * {@link #MODE_SERVER_OUTBOUND} and {@link #MODE_SERVER_INBOUND}).
    *
    * When setting the redirection URIs, you can also used special URI variables to * reuse most properties from the original request as well as URI template * variables. For a complete list of properties, please see the {@link Resolver} * class. For example "/target?referrer={fi}" would redirect to the relative * URI, inserting the referrer URI as a query parameter.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see org.restlet.routing.Template * @see User * Guide - URI rewriting and redirection * @author Jerome Louvel */ public class Redirector extends Restlet { /** * In this mode, the client is permanently redirected to the URI generated * from the target URI pattern.
    * * @see Status#REDIRECTION_PERMANENT */ public static final int MODE_CLIENT_PERMANENT = 1; /** * In this mode, the client is simply redirected to the URI generated from * the target URI pattern.
    * * @see Status#REDIRECTION_FOUND */ public static final int MODE_CLIENT_FOUND = 2; /** * In this mode, the client is simply redirected to the URI generated from * the target URI pattern.
    * * @see Status#REDIRECTION_SEE_OTHER */ public static final int MODE_CLIENT_SEE_OTHER = 3; /** * In this mode, the client is temporarily redirected to the URI generated * from the target URI pattern.
    * * @see Status#REDIRECTION_TEMPORARY */ public static final int MODE_CLIENT_TEMPORARY = 4; /** * In this mode, the call is sent to the context's dispatcher. Once the * selected client connector has completed the request handling, the * response is normally returned to the client. In this case, you can view * the Redirector as acting as a transparent proxy Restlet.
    *
    * Remember to add the required connectors to the parent Component and to * declare them in the list of required connectors on the * Application.connectorService property.
    *
    * Note that in this mode, the headers of HTTP requests, stored in the * request's attributes, are removed before dispatching. Also, when a HTTP * response comes back the headers are also removed. * * @deprecated Use the {@link Redirector#MODE_SERVER_OUTBOUND} instead. */ @Deprecated public static final int MODE_DISPATCHER = 5; /** * In this mode, the call is sent to the application's outboundRoot or if * null to the context's client dispatcher. Once the selected client * connector has completed the request handling, the response is normally * returned to the client. In this case, you can view the {@link Redirector} * as acting as a transparent server-side proxy Restlet.
    *
    * Remember to add the required connectors to the parent {@link Component} * and to declare them in the list of required connectors on the * {@link Application#getConnectorService()} property.
    *
    * Note that in this mode, the headers of HTTP requests, stored in the * request's attributes, are removed before dispatching. Also, when a HTTP * response comes back the headers are also removed. * * @see Application#getOutboundRoot() * @see Context#getClientDispatcher() */ public static final int MODE_SERVER_OUTBOUND = 6; /** * In this mode, the call is sent to the context's server dispatcher. Once * the selected client connector has completed the request handling, the * response is normally returned to the client. In this case, you can view * the Redirector as acting as a transparent proxy Restlet.
    *
    * Remember to add the required connectors to the parent {@link Component} * and to declare them in the list of required connectors on the * {@link Application#getConnectorService()} property.
    *
    * Note that in this mode, the headers of HTTP requests, stored in the * request's attributes, are removed before dispatching. Also, when a HTTP * response comes back the headers are also removed. * * @see Context#getServerDispatcher() */ public static final int MODE_SERVER_INBOUND = 7; /** The target URI pattern. */ protected volatile String targetTemplate; /** The redirection mode. */ protected volatile int mode; /** * Constructor for the client dispatcher mode. * * @param context * The context. * @param targetTemplate * The template to build the target URI. * @see org.restlet.routing.Template */ public Redirector(Context context, String targetTemplate) { this(context, targetTemplate, MODE_SERVER_OUTBOUND); } /** * Constructor. * * @param context * The context. * @param targetPattern * The pattern to build the target URI (using StringTemplate * syntax and the CallModel for variables). * @param mode * The redirection mode. */ public Redirector(Context context, String targetPattern, int mode) { super(context); this.targetTemplate = targetPattern; this.mode = mode; } /** * Returns the redirection mode. * * @return The redirection mode. */ public int getMode() { return this.mode; } /** * Returns the target reference to redirect to. * * @param request * The request to handle. * @param response * The response to update. * @return The target reference to redirect to. */ protected Reference getTargetRef(Request request, Response response) { // Create the template final Template rt = new Template(this.targetTemplate); rt.setLogger(getLogger()); // Return the formatted target URI if (new Reference(this.targetTemplate).isRelative()) { // Be sure to keep the resource's base reference. return new Reference(request.getResourceRef(), rt.format(request, response)); } return new Reference(rt.format(request, response)); } /** * Returns the target URI pattern. * * @return The target URI pattern. */ public String getTargetTemplate() { return this.targetTemplate; } /** * Handles a call by redirecting using the selected redirection mode. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { // Generate the target reference Reference targetRef = getTargetRef(request, response); switch (this.mode) { case MODE_CLIENT_PERMANENT: getLogger().log(Level.INFO, "Permanently redirecting client to: " + targetRef); response.redirectPermanent(targetRef); break; case MODE_CLIENT_FOUND: getLogger().log(Level.INFO, "Redirecting client to found location: " + targetRef); response.setLocationRef(targetRef); response.setStatus(Status.REDIRECTION_FOUND); break; case MODE_CLIENT_SEE_OTHER: getLogger().log(Level.INFO, "Redirecting client to another location: " + targetRef); response.redirectSeeOther(targetRef); break; case MODE_CLIENT_TEMPORARY: getLogger().log(Level.INFO, "Temporarily redirecting client to: " + targetRef); response.redirectTemporary(targetRef); break; case MODE_DISPATCHER: getLogger().log(Level.INFO, "Redirecting via client connector to: " + targetRef); redirectDispatcher(targetRef, request, response); break; case MODE_SERVER_OUTBOUND: getLogger().log(Level.INFO, "Redirecting via client dispatcher to: " + targetRef); outboundServerRedirect(targetRef, request, response); break; case MODE_SERVER_INBOUND: getLogger().log(Level.INFO, "Redirecting via server dispatcher to: " + targetRef); inboundServerRedirect(targetRef, request, response); break; } } /** * Redirects a given call to a target reference. In the default * implementation, the request HTTP headers, stored in the request's * attributes, are removed before dispatching. After dispatching, the * response HTTP headers are also removed to prevent conflicts with the main * call. * * @param targetRef * The target reference with URI variables resolved. * @param request * The request to handle. * @param response * The response to update. */ protected void inboundServerRedirect(Reference targetRef, Request request, Response response) { serverRedirect(getContext().getServerDispatcher(), targetRef, request, response); } /** * Redirects a given call to a target reference. In the default * implementation, the request HTTP headers, stored in the request's * attributes, are removed before dispatching. After dispatching, the * response HTTP headers are also removed to prevent conflicts with the main * call. * * @param targetRef * The target reference with URI variables resolved. * @param request * The request to handle. * @param response * The response to update. */ protected void outboundServerRedirect(Reference targetRef, Request request, Response response) { Restlet next = (getApplication() == null) ? null : getApplication() .getOutboundRoot(); if (next == null) { next = getContext().getClientDispatcher(); } serverRedirect(next, targetRef, request, response); if (response.getEntity() != null && !request.getResourceRef().getScheme() .equalsIgnoreCase(targetRef.getScheme())) { // Distinct protocol, this data cannot be exposed. response.getEntity().setLocationRef((Reference) null); } } /** * Redirects a given call to a target reference. In the default * implementation, the request HTTP headers, stored in the request's * attributes, are removed before dispatching. After dispatching, the * response HTTP headers are also removed to prevent conflicts with the main * call. * * @param targetRef * The target reference with URI variables resolved. * @param request * The request to handle. * @param response * The response to update. * @deprecated Use * {@link #outboundServerRedirect(Reference, Request, Response)} * instead. */ @Deprecated protected void redirectDispatcher(Reference targetRef, Request request, Response response) { outboundServerRedirect(targetRef, request, response); } /** * Optionally rewrites the response entity returned in the * {@link #MODE_SERVER_INBOUND} and {@link #MODE_SERVER_OUTBOUND} modes. By * default, it just returns the initial entity without any modification. * * @param initialEntity * The initial entity returned. * @return The rewritten entity. */ protected Representation rewrite(Representation initialEntity) { return initialEntity; } /** * Redirects a given call on the server-side to a next Restlet with a given * target reference. In the default implementation, the request HTTP * headers, stored in the request's attributes, are removed before * dispatching. After dispatching, the response HTTP headers are also * removed to prevent conflicts with the main call. * * @param next * The next Restlet to forward the call to. * @param targetRef * The target reference with URI variables resolved. * @param request * The request to handle. * @param response * The response to update. */ protected void serverRedirect(Restlet next, Reference targetRef, Request request, Response response) { if (next == null) { getLogger().warning( "No next Restlet provided for server redirection to " + targetRef); } else { // Save the base URI if it exists as we might need it for // redirections Reference resourceRef = request.getResourceRef(); Reference baseRef = resourceRef.getBaseRef(); // Reset the protocol and let the dispatcher handle the protocol request.setProtocol(null); // Update the request to cleanly go to the target URI request.setResourceRef(targetRef); request.getAttributes().remove(HeaderConstants.ATTRIBUTE_HEADERS); next.handle(request, response); // Allow for response rewriting and clean the headers response.setEntity(rewrite(response.getEntity())); response.getAttributes().remove(HeaderConstants.ATTRIBUTE_HEADERS); request.setResourceRef(resourceRef); // In case of redirection, we may have to rewrite the redirect URI if (response.getLocationRef() != null) { Template rt = new Template(this.targetTemplate); rt.setLogger(getLogger()); int matched = rt.parse(response.getLocationRef().toString(), request); if (matched > 0) { String remainingPart = (String) request.getAttributes() .get("rr"); if (remainingPart != null) { response.setLocationRef(baseRef.toString() + remainingPart); } } } } } /** * Sets the redirection mode. * * @param mode * The redirection mode. */ public void setMode(int mode) { this.mode = mode; } /** * Sets the target URI pattern. * * @param targetTemplate * The target URI pattern. */ public void setTargetTemplate(String targetTemplate) { this.targetTemplate = targetTemplate; } } restlet-2.0.14/org.restlet/src/org/restlet/routing/VirtualHost.java0000664000175000017500000004153611757206346026106 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.net.InetAddress; import java.net.UnknownHostException; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.resource.Finder; /** * Router of calls from Server connectors to Restlets. The attached Restlets are * typically Applications.
    *
    * A virtual host is defined along three properties: *
      *
    • request's {@link Request#getHostRef()}: the URI of the host that received * the request. Note that the same IP address can correspond to multiple domain * names and therefore receive request with different "hostRef" URIs.
    • *
    • request's {@link Request#getResourceRef()}: the URI of the target * resource of the request. If this reference is relative, then it is based on * the "hostRef", otherwise it is maintained as received. This difference is * useful for resources identified by URNs or for Web proxies or Web caches.
    • *
    • response's {@link Response#getServerInfo()}: the information about the * server connector receiving the requests such as it IP address and port * number.
    • *
    * When creating a new instance, you can define Java regular expressions ( * {@link java.util.regex.Pattern}) that must match the domain name, port, * scheme for references or IP address and port number for server information. * The default values match everything.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see java.util.regex.Pattern * @see Wikipedia - * Virtual Hosting * @see Apache - Virtual * Hosting * @author Jerome Louvel */ public class VirtualHost extends Router { private static final ThreadLocal CURRENT = new ThreadLocal(); /** * Returns the virtual host code associated to the current thread. * * This variable is stored internally as a thread local variable and updated * each time a call is routed by a virtual host. * * @return The current context. */ public static Integer getCurrent() { return CURRENT.get(); } /** * Returns the IP address of a given domain name. * * @param domain * The domain name. * @return The IP address. */ public static String getIpAddress(String domain) { String result = null; try { result = InetAddress.getByName(domain).getHostAddress(); } catch (UnknownHostException e) { } return result; } /** * Returns the local host IP address. * * @return The local host IP address. */ public static String getLocalHostAddress() { String result = null; try { result = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { } return result; } /** * Returns the local host name. * * @return The local host name. */ public static String getLocalHostName() { String result = null; try { result = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { } return result; } /** * Sets the virtual host code associated with the current thread. * * @param code * The thread's virtual host code. */ public static void setCurrent(Integer code) { CURRENT.set(code); } /** The hostRef host domain pattern to match. */ private volatile String hostDomain; /** The hostRef host port pattern to match. */ private volatile String hostPort; /** The hostRef scheme pattern to match. */ private volatile String hostScheme; /** The resourceRef host domain pattern to match. */ private volatile String resourceDomain; /** The resourceRef host port pattern to match. */ private volatile String resourcePort; /** The resourceRef scheme pattern to match. */ private volatile String resourceScheme; /** The listening server address pattern to match. */ private volatile String serverAddress; /** The listening server port pattern to match. */ private volatile String serverPort; /** The parent component's context. */ private volatile Context parentContext; /** * Constructor. Note that usage of this constructor is not recommended as * the Router won't have a proper context set. In general you will prefer to * use the other constructor and pass it the parent component's context. */ public VirtualHost() { this(null); } /** * Constructor. Accepts all incoming requests by default, use the set * methods to restrict the matchable patterns. * * @param parentContext * The parent component's context. */ public VirtualHost(Context parentContext) { this(parentContext, ".*", ".*", ".*", ".*", ".*", ".*", ".*", ".*"); } /** * Constructor. * * @param parentContext * The parent component's context. * @param hostDomain * The hostRef host domain pattern to match. * @param hostPort * The hostRef host port pattern to match. * @param hostScheme * The hostRef scheme protocol pattern to match. * @param resourceDomain * The resourceRef host domain pattern to match. * @param resourcePort * The resourceRef host port pattern to match. * @param resourceScheme * The resourceRef scheme protocol pattern to match. * @param serverAddress * The listening server address pattern to match. * @param serverPort * The listening server port pattern to match. * @see java.util.regex.Pattern */ public VirtualHost(Context parentContext, String hostDomain, String hostPort, String hostScheme, String resourceDomain, String resourcePort, String resourceScheme, String serverAddress, String serverPort) { super((parentContext == null) ? null : parentContext .createChildContext()); // Override Router's default modes setDefaultMatchingMode(Template.MODE_STARTS_WITH); setRoutingMode(MODE_BEST_MATCH); this.parentContext = parentContext; this.hostDomain = hostDomain; this.hostPort = hostPort; this.hostScheme = hostScheme; this.resourceDomain = resourceDomain; this.resourcePort = resourcePort; this.resourceScheme = resourceScheme; this.serverAddress = serverAddress; this.serverPort = serverPort; } /** * Attaches a target Restlet to this router with an empty URI pattern. A new * route will be added routing to the target when any call is received. * * In addition to super class behavior, this method will set the context of * the target if it is empty by creating a protected context via the * {@link Context#createChildContext()} method. * * @param target * The target Restlet to attach. * @return The created route. */ @Override @SuppressWarnings("deprecation") public Route attach(Restlet target) { if ((target.getContext() == null) && (this.parentContext != null)) { target.setContext(this.parentContext.createChildContext()); } return super.attach(target); } /** * Attaches a target Restlet to this router based on a given URI pattern. A * new route will be added routing to the target when calls with a URI * matching the pattern will be received. * * In addition to super class behavior, this method will set the context of * the target if it is empty by creating a protected context via the * {@link Context#createChildContext()} method. * * @param uriPattern * The URI pattern that must match the relative part of the * resource URI. * @param target * The target Restlet to attach. * @return The created route. */ @Override @SuppressWarnings("deprecation") public Route attach(String uriPattern, Restlet target) { if ((target.getContext() == null) && (this.parentContext != null)) { target.setContext(this.parentContext.createChildContext()); } return super.attach(uriPattern, target); } /** * Attaches a Restlet to this router as the default target to invoke when no * route matches. It actually sets a default route that scores all calls to * 1.0. * * In addition to super class behavior, this method will set the context of * the target if it is empty by creating a protected context via the * {@link Context#createChildContext()} method. * * @param defaultTarget * The Restlet to use as the default target. * @return The created route. */ @Override @SuppressWarnings("deprecation") public Route attachDefault(Restlet defaultTarget) { if ((defaultTarget.getContext() == null) && (this.parentContext != null)) { defaultTarget.setContext(this.parentContext.createChildContext()); } return super.attachDefault(defaultTarget); } /** * Creates a new finder instance based on the "targetClass" property. * * In addition to super class behavior, this method will set the context of * the finder by creating a protected context via the * {@link Context#createChildContext()} method. * * @param targetClass * The target Resource class to attach. * @return The new finder instance. */ @Override public Finder createFinder(Class targetClass) { Finder result = super.createFinder(targetClass); result.setContext(getContext().createChildContext()); return result; } @Override @SuppressWarnings("deprecation") protected Route createRoute(String uriPattern, Restlet target, int matchingMode) { Route result = new Route(this, uriPattern, target) { @Override protected int beforeHandle(Request request, Response response) { final int result = super.beforeHandle(request, response); // Set the request's root reference request.setRootRef(request.getResourceRef().getBaseRef()); // Save the hash code of the current host setCurrent(VirtualHost.this.hashCode()); return result; } }; result.getTemplate().setMatchingMode(matchingMode); result.setMatchingQuery(getDefaultMatchingQuery()); return result; } /** * Returns the hostRef host domain to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The hostRef host domain to match. */ public String getHostDomain() { return this.hostDomain; } /** * Returns the hostRef host port to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The hostRef host port to match. */ public String getHostPort() { return this.hostPort; } /** * Returns the hostRef scheme to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The hostRef scheme to match. */ public String getHostScheme() { return this.hostScheme; } /** * Returns the resourceRef host domain to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The resourceRef host domain to match. */ public String getResourceDomain() { return this.resourceDomain; } /** * Returns the resourceRef host port to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The resourceRef host port to match. */ public String getResourcePort() { return this.resourcePort; } /** * Returns the resourceRef scheme to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The resourceRef scheme to match. */ public String getResourceScheme() { return this.resourceScheme; } /** * Returns the listening server address. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The listening server address. */ public String getServerAddress() { return this.serverAddress; } /** * Returns the listening server port. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @return The listening server port. */ public String getServerPort() { return this.serverPort; } /** * Sets the hostRef host domain to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @param hostDomain * The hostRef host domain to match. */ public void setHostDomain(String hostDomain) { this.hostDomain = hostDomain; } /** * Sets the hostRef host port to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @param hostPort * The hostRef host port to match. */ public void setHostPort(String hostPort) { this.hostPort = hostPort; } /** * Sets the hostRef scheme to match. See the {@link java.util.regex.Pattern} * class for details on the syntax. * * @param hostScheme * The hostRef scheme to match. */ public void setHostScheme(String hostScheme) { this.hostScheme = hostScheme; } /** * Sets the resourceRef host domain to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @param resourceDomain * The resourceRef host domain to match. */ public void setResourceDomain(String resourceDomain) { this.resourceDomain = resourceDomain; } /** * Sets the resourceRef host port to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @param resourcePort * The resourceRef host port to match. */ public void setResourcePort(String resourcePort) { this.resourcePort = resourcePort; } /** * Sets the resourceRef scheme to match. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @param resourceScheme * The resourceRef scheme to match. */ public void setResourceScheme(String resourceScheme) { this.resourceScheme = resourceScheme; } /** * Sets the listening server address. See the * {@link java.util.regex.Pattern} class for details on the syntax. * * @param serverAddress * The listening server address. */ public void setServerAddress(String serverAddress) { this.serverAddress = serverAddress; } /** * Sets the listening server port. See the {@link java.util.regex.Pattern} * class for details on the syntax. * * @param serverPort * The listening server port. */ public void setServerPort(String serverPort) { this.serverPort = serverPort; } } restlet-2.0.14/org.restlet/src/org/restlet/routing/package.html0000664000175000017500000000033311757206350025221 0ustar jamespagejamespage Classes related to call routing.

    @since Restlet 2.0 @see User Guide - Routing package restlet-2.0.14/org.restlet/src/org/restlet/routing/Variable.java0000664000175000017500000002614011757206346025341 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import org.restlet.data.Reference; /** * Variable descriptor for reference templates. * * @see Template * @author Jerome Louvel */ public final class Variable { /** Matches all characters. */ public static final int TYPE_ALL = 1; /** Matches all alphabetical characters. */ public static final int TYPE_ALPHA = 2; /** Matches all alphabetical and digital characters. */ public static final int TYPE_ALPHA_DIGIT = 3; /** Matches any TEXT excluding "(" and ")". */ public static final int TYPE_COMMENT = 4; /** Matches any TEXT inside a comment excluding ";". */ public static final int TYPE_COMMENT_ATTRIBUTE = 5; /** Matches all digital characters. */ public static final int TYPE_DIGIT = 6; /** Matches any CHAR except CTLs or separators. */ public static final int TYPE_TOKEN = 7; /** Matches all URI characters. */ public static final int TYPE_URI_ALL = 8; /** Matches URI fragment characters. */ public static final int TYPE_URI_FRAGMENT = 9; /** Matches URI path characters (not the query or the fragment parts). */ public static final int TYPE_URI_PATH = 10; /** Matches URI query characters. */ public static final int TYPE_URI_QUERY = 11; /** Matches URI query parameter characters (name or value). */ public static final int TYPE_URI_QUERY_PARAM = 12; /** Matches URI scheme characters. */ public static final int TYPE_URI_SCHEME = 13; /** Matches URI segment characters. */ public static final int TYPE_URI_SEGMENT = 14; /** Matches unreserved URI characters. */ public static final int TYPE_URI_UNRESERVED = 15; /** Matches all alphabetical and digital characters plus the underscore. */ public static final int TYPE_WORD = 16; /** Indicates if the parsed value must be decoded. */ private volatile boolean decodingOnParse; /** The default value to use if the key couldn't be found in the model. */ private volatile String defaultValue; /** Indicates if the formatted value must be encoded. */ private volatile boolean encodingOnFormat; /** * Indicates if the value is fixed, in which case the "defaultValue" * property is always used. */ private volatile boolean fixed; /** Indicates if the variable is required or optional. */ private volatile boolean required; /** The type of variable. See TYPE_* constants. */ private volatile int type; /** * Default constructor. Type is TYPE_ALL, default value is "", required is * true and fixed is false. */ public Variable() { this(Variable.TYPE_ALL, "", true, false); } /** * Constructor. Default value is "", required is true and fixed is false. * * @param type * The type of variable. See TYPE_* constants. */ public Variable(int type) { this(type, "", true, false); } /** * Constructor. * * @param type * The type of variable. See TYPE_* constants. * @param defaultValue * The default value to use if the key couldn't be found in the * model. * @param required * Indicates if the variable is required or optional. * @param fixed * Indicates if the value is fixed, in which case the * "defaultValue" property is always used. */ public Variable(int type, String defaultValue, boolean required, boolean fixed) { this(type, defaultValue, required, fixed, false, false); } /** * Constructor. * * @param type * The type of variable. See TYPE_* constants. * @param defaultValue * The default value to use if the key couldn't be found in the * model. * @param required * Indicates if the variable is required or optional. * @param fixed * Indicates if the value is fixed, in which case the * "defaultValue" property is always used. * @param decodingOnParse * Indicates if the parsed value must be decoded. * @param encodingOnFormat * Indicates if the formatted value must be encoded. */ public Variable(int type, String defaultValue, boolean required, boolean fixed, boolean decodingOnParse, boolean encodingOnFormat) { this.type = type; this.defaultValue = defaultValue; this.required = required; this.fixed = fixed; this.decodingOnParse = decodingOnParse; this.encodingOnFormat = encodingOnFormat; } /** * According to the type of the variable, encodes the value given in * parameters. * * @param value * The value to encode. * @return The encoded value, according to the variable type. */ public String encode(String value) { switch (this.type) { case Variable.TYPE_URI_ALL: return Reference.encode(value); case Variable.TYPE_URI_UNRESERVED: return Reference.encode(value); case Variable.TYPE_URI_FRAGMENT: return Reference.encode(value); case Variable.TYPE_URI_PATH: return Reference.encode(value); case Variable.TYPE_URI_QUERY: return Reference.encode(value); case Variable.TYPE_URI_SEGMENT: return Reference.encode(value); default: return value; } } /** * Returns the default value to use if the key couldn't be found in the * model. * * @return The default value to use if the key couldn't be found in the * model. */ public String getDefaultValue() { return this.defaultValue; } /** * Returns the type of variable. See TYPE_* constants. * * @return The type of variable. See TYPE_* constants. */ public int getType() { return this.type; } /** * Indicates if the parsed value must be decoded. * * @return True if the parsed value must be decoded, false otherwise. * @deprecated Use {@link #isDecodingOnParse()} instead. */ @Deprecated public boolean isDecodedOnParse() { return this.decodingOnParse; } /** * Indicates if the parsed value must be decoded. * * @return True if the parsed value must be decoded, false otherwise. */ public boolean isDecodingOnParse() { return isDecodedOnParse(); } /** * Indicates if the formatted value must be encoded. * * @return True if the formatted value must be encoded, false otherwise. * @deprecated Use {@link #isEncodingOnFormat()} instead. */ @Deprecated public boolean isEncodedOnFormat() { return this.encodingOnFormat; } /** * Indicates if the formatted value must be encoded. * * @return True if the formatted value must be encoded, false otherwise. */ public boolean isEncodingOnFormat() { return isEncodedOnFormat(); } /** * Returns true if the value is fixed, in which case the "defaultValue" * property is always used. * * @return True if the value is fixed, in which case the "defaultValue" * property is always used. */ public boolean isFixed() { return this.fixed; } /** * Returns true if the variable is required or optional. * * @return True if the variable is required or optional. */ public boolean isRequired() { return this.required; } /** * Indicates if the parsed value must be decoded. * * @param decodingOnParse * True if the parsed value must be decoded, false otherwise. * @deprecated Use {@link #setDecodingOnParse(boolean)} instead. */ @Deprecated public void setDecodedOnParse(boolean decodingOnParse) { this.decodingOnParse = decodingOnParse; } /** * Indicates if the parsed value must be decoded. * * @param decodingOnParse * True if the parsed value must be decoded, false otherwise. */ public void setDecodingOnParse(boolean decodingOnParse) { setDecodedOnParse(decodingOnParse); } /** * Sets the default value to use if the key couldn't be found in the model. * * @param defaultValue * The default value to use if the key couldn't be found in the * model. */ public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } /** * Indicates if the formatted value must be encoded. * * @param encodingOnFormat * True if the formatted value must be encoded, false otherwise. * @deprecated Use {@link #setEncodingOnFormat(boolean)} instead. */ @Deprecated public void setEncodedOnFormat(boolean encodingOnFormat) { this.encodingOnFormat = encodingOnFormat; } /** * Indicates if the formatted value must be encoded. * * @param encodingOnFormat * True if the formatted value must be encoded, false otherwise. */ public void setEncodingOnFormat(boolean encodingOnFormat) { setEncodedOnFormat(encodingOnFormat); } /** * Indicates if the value is fixed * * @param fixed * True if the value is fixed */ public void setFixed(boolean fixed) { this.fixed = fixed; } /** * Indicates if the variable is required or optional. * * @param required * True if the variable is required or optional. */ public void setRequired(boolean required) { this.required = required; } /** * Sets the type of variable. See TYPE_* constants. * * @param type * The type of variable. */ public void setType(int type) { this.type = type; } } restlet-2.0.14/org.restlet/src/org/restlet/routing/Router.java0000664000175000017500000007400711757206346025101 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Status; import org.restlet.resource.Directory; import org.restlet.resource.Finder; import org.restlet.util.RouteList; /** * Restlet routing calls to one of the attached routes. Each route can compute * an affinity score for each call depending on various criteria. The attach() * method allow the creation of routes based on URI patterns matching the * beginning of a the resource reference's remaining part.
    *
    * In addition, several routing modes are supported, implementing various * algorithms: *

      *
    • Best match
    • *
    • First match (default)
    • *
    • Last match
    • *
    • Random match
    • *
    • Round robin
    • *
    • Custom
    • *
    *
    * Note that for routes using URI patterns will update the resource reference's * base reference during the routing if they are selected. It is also important * to know that the routing is very strict about path separators in your URI * patterns. Finally, you can modify the list of routes while handling incoming * calls as the delegation code is ensured to be thread-safe.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see User * Guide - Routers and hierarchical URIs * @author Jerome Louvel */ public class Router extends Restlet { /** * Each call will be routed to the route with the best score, if the * required score is reached. * * @deprecated Use {@link #MODE_BEST_MATCH} instead. */ @Deprecated public static final int BEST = 1; /** * Each call will be routed according to a custom mode. * * @deprecated Use {@link #MODE_CUSTOM} instead. */ @Deprecated public static final int CUSTOM = 6; /** * Each call is routed to the first route if the required score is reached. * If the required score is not reached, then the route is skipped and the * next one is considered. * * @deprecated Use {@link #MODE_FIRST_MATCH} instead. */ @Deprecated public static final int FIRST = 2; /** * Each call will be routed to the last route if the required score is * reached. If the required score is not reached, then the route is skipped * and the previous one is considered. * * @deprecated Use {@link #MODE_LAST_MATCH} instead. */ @Deprecated public static final int LAST = 3; /** * Each call will be routed to the route with the best score, if the * required score is reached. */ public static final int MODE_BEST_MATCH = 1; /** * Each call will be routed according to a custom mode. */ public static final int MODE_CUSTOM = 6; /** * Each call is routed to the first route if the required score is reached. * If the required score is not reached, then the route is skipped and the * next one is considered. */ public static final int MODE_FIRST_MATCH = 2; /** * Each call will be routed to the last route if the required score is * reached. If the required score is not reached, then the route is skipped * and the previous one is considered. */ public static final int MODE_LAST_MATCH = 3; /** * Each call is be routed to the next route target if the required score is * reached. The next route is relative to the previous call routed (round * robin mode). If the required score is not reached, then the route is * skipped and the next one is considered. If the last route is reached, the * first route will be considered. */ public static final int MODE_NEXT_MATCH = 4; /** * Each call will be randomly routed to one of the routes that reached the * required score. If the random route selected is not a match then the * immediate next route is evaluated until one matching route is found. If * we get back to the initial random route selected with no match, then we * return null. */ public static final int MODE_RANDOM_MATCH = 5; /** * Each call is be routed to the next route target if the required score is * reached. The next route is relative to the previous call routed (round * robin mode). If the required score is not reached, then the route is * skipped and the next one is considered. If the last route is reached, the * first route will be considered. * * @deprecated Use {@link #MODE_NEXT_MATCH} instead. */ @Deprecated public static final int NEXT = 4; /** * Each call will be randomly routed to one of the routes that reached the * required score. If the random route selected is not a match then the * immediate next route is evaluated until one matching route is found. If * we get back to the initial random route selected with no match, then we * return null. * * @deprecated Use {@link #MODE_RANDOM_MATCH} instead. */ @Deprecated public static final int RANDOM = 5; /** The default matching mode to use when selecting routes based on URIs. */ private volatile int defaultMatchingMode; /** * The default setting for whether the routing should be done on URIs with * or without taking into account query string. */ private volatile boolean defaultMatchingQuery; /** The default route tested if no other one was available. */ @SuppressWarnings("deprecation") private volatile Route defaultRoute; /** Finder class to instantiate. */ private volatile Class finderClass; /** * The maximum number of attempts if no attachment could be matched on the * first attempt. */ private volatile int maxAttempts; /** The minimum score required to have a match. */ private volatile float requiredScore; /** The delay (in milliseconds) before a new attempt. */ private volatile long retryDelay; /** The modifiable list of routes. */ private volatile RouteList routes; /** The routing mode. */ private volatile int routingMode; /** * Constructor. Note that usage of this constructor is not recommended as * the Router won't have a proper context set. In general you will prefer to * use the other constructor and pass it the parent application's context or * eventually the parent component's context if you don't use applications. */ public Router() { this(null); } /** * Constructor. * * @param context * The context. */ public Router(Context context) { super(context); this.routes = new RouteList(); this.defaultMatchingMode = Template.MODE_EQUALS; this.defaultMatchingQuery = false; this.defaultRoute = null; this.finderClass = Finder.class; this.routingMode = MODE_FIRST_MATCH; this.requiredScore = 0.5F; this.maxAttempts = 1; this.retryDelay = 500L; } /** * Attaches a target Restlet to this router with an empty URI pattern. A new * route using the matching mode returned by * {@link #getMatchingMode(Restlet)} will be added routing to the target * when any call is received. * * @param target * The target Restlet to attach. * @return The created route. */ @SuppressWarnings("deprecation") public Route attach(Restlet target) { return attach(target, getMatchingMode(target)); } /** * Attaches a target Restlet to this router with an empty URI pattern. A new * route will be added routing to the target when any call is received. * * @param target * The target Restlet to attach. * @param matchingMode * The matching mode. * @return The created route. */ @SuppressWarnings("deprecation") public Route attach(Restlet target, int matchingMode) { return attach("", target, matchingMode); } /** * Attaches a target Resource class to this router based on a given URI * pattern. A new route using the matching mode returned by * {@link #getMatchingMode(Restlet)} will be added routing to the target * when calls with a URI matching the pattern will be received. * * @param pathTemplate * The URI path template that must match the relative part of the * resource URI. * @param targetClass * The target Resource class to attach. * @return The created route. */ @SuppressWarnings("deprecation") public Route attach(String pathTemplate, Class targetClass) { return attach(pathTemplate, createFinder(targetClass)); } /** * Attaches a target Resource class to this router based on a given URI * pattern. A new route will be added routing to the target when calls with * a URI matching the pattern will be received. * * @param pathTemplate * The URI path template that must match the relative part of the * resource URI. * @param targetClass * The target Resource class to attach. * @param matchingMode * The matching mode. * @return The created route. */ @SuppressWarnings("deprecation") public Route attach(String pathTemplate, Class targetClass, int matchingMode) { return attach(pathTemplate, createFinder(targetClass), matchingMode); } /** * Attaches a target Restlet to this router based on a given URI pattern. A * new route using the matching mode returned by * {@link #getMatchingMode(Restlet)} will be added routing to the target * when calls with a URI matching the pattern will be received. * * @param pathTemplate * The URI path template that must match the relative part of the * resource URI. * @param target * The target Restlet to attach. * @return The created route. */ @SuppressWarnings("deprecation") public Route attach(String pathTemplate, Restlet target) { return attach(pathTemplate, target, getMatchingMode(target)); } /** * Attaches a target Restlet to this router based on a given URI pattern. A * new route will be added routing to the target when calls with a URI * matching the pattern will be received. * * @param pathTemplate * The URI path template that must match the relative part of the * resource URI. * @param target * The target Restlet to attach. * @param matchingMode * The matching mode. * @return The created route. */ @SuppressWarnings("deprecation") public Route attach(String pathTemplate, Restlet target, int matchingMode) { final Route result = createRoute(pathTemplate, target, matchingMode); getRoutes().add(result); return result; } /** * Attaches a Resource class to this router as the default target to invoke * when no route matches. It actually sets a default route that scores all * calls to 1.0. * * @param defaultTargetClass * The target Resource class to attach. * @return The created route. */ @SuppressWarnings("deprecation") public Route attachDefault(Class defaultTargetClass) { return attachDefault(createFinder(defaultTargetClass)); } /** * Attaches a Restlet to this router as the default target to invoke when no * route matches. It actually sets a default route that scores all calls to * 1.0. * * @param defaultTarget * The Restlet to use as the default target. * @return The created route. */ @SuppressWarnings("deprecation") public Route attachDefault(Restlet defaultTarget) { Route result = createRoute("", defaultTarget); result.setMatchingMode(Template.MODE_STARTS_WITH); setDefaultRoute(result); return result; } /** * Creates a new finder instance based on the "targetClass" property. * * @param targetClass * The target Resource class to attach. * @return The new finder instance. */ public Finder createFinder(Class targetClass) { return Finder.createFinder(targetClass, getFinderClass(), getContext(), getLogger()); } /** * Creates a new route for the given URI pattern and target. The route will * match the URI query string depending on the result of * {@link #getDefaultMatchingQuery()} and the matching mode will be given by * {@link #getMatchingMode(Restlet)}. * * @param uriPattern * The URI pattern that must match the relative part of the * resource URI. * @param target * The target Restlet to attach. * @return The created route. */ @SuppressWarnings("deprecation") protected Route createRoute(String uriPattern, Restlet target) { return createRoute(uriPattern, target, getMatchingMode(target)); } /** * Creates a new route for the given URI pattern, target and matching mode. * The route will match the URI query string depending on the result of * {@link #getDefaultMatchingQuery()}. * * @param uriPattern * The URI pattern that must match the relative part of the * resource URI. * @param target * The target Restlet to attach. * @param matchingMode * The matching mode. * @return The created route. */ @SuppressWarnings("deprecation") protected Route createRoute(String uriPattern, Restlet target, int matchingMode) { Route result = new Route(this, uriPattern, target); result.getTemplate().setMatchingMode(matchingMode); result.setMatchingQuery(getDefaultMatchingQuery()); return result; } /** * Detaches the target from this router. All routes routing to this target * Restlet are removed from the list of routes and the default route is set * to null. * * @param targetClass * The target class to detach. */ public void detach(Class targetClass) { for (int i = getRoutes().size() - 1; i >= 0; i--) { Restlet target = getRoutes().get(i).getNext(); if (target != null && Finder.class.isAssignableFrom(target.getClass())) { Finder finder = (Finder) target; if (finder.getTargetClass().equals(targetClass)) { getRoutes().remove(i); } } } if (getDefaultRoute() != null) { Restlet target = getDefaultRoute().getNext(); if (target != null && Finder.class.isAssignableFrom(target.getClass())) { Finder finder = (Finder) target; if (finder.getTargetClass().equals(targetClass)) { setDefaultRoute(null); } } } } /** * Detaches the target from this router. All routes routing to this target * Restlet are removed from the list of routes and the default route is set * to null. * * @param target * The target Restlet to detach. */ public void detach(Restlet target) { getRoutes().removeAll(target); if ((getDefaultRoute() != null) && (getDefaultRoute().getNext() == target)) { setDefaultRoute(null); } } /** * Effectively handles the call using the selected next {@link Restlet}, * typically the selected {@link Route}. By default, it just invokes the * next Restlet. * * @param next * The next Restlet to invoke. * @param request * The request. * @param response * The response. */ protected void doHandle(Restlet next, Request request, Response response) { next.handle(request, response); } /** * Returns the matched route according to a custom algorithm. To use in * combination of the {@link #MODE_CUSTOM} option. The default * implementation (to be overridden), returns null. * * @param request * The request to handle. * @param response * The response to update. * @return The matched route if available or null. */ @SuppressWarnings("deprecation") protected Route getCustom(Request request, Response response) { return null; } /** * Returns the default matching mode to use when selecting routes based on * URIs. By default it returns {@link Template#MODE_EQUALS}. * * @return The default matching mode. */ public int getDefaultMatchingMode() { return this.defaultMatchingMode; } /** * Returns the default setting for whether the routing should be done on * URIs with or without taking into account query string. By default, it * returns false. * * @return the default setting for whether the routing should be done on * URIs with or without taking into account query string. */ public boolean getDefaultMatchingQuery() { return getDefaultMatchQuery(); } /** * Returns the default setting for whether the routing should be done on * URIs with or without taking into account query string. By default, it * returns false. * * @return the default setting for whether the routing should be done on * URIs with or without taking into account query string. * @deprecated Use {@link #getDefaultMatchingQuery()} instead. */ @Deprecated public boolean getDefaultMatchQuery() { return this.defaultMatchingQuery; } /** * Returns the default route to test if no other one was available after * retrying the maximum number of attempts. * * @return The default route tested if no other one was available. */ @SuppressWarnings("deprecation") public Route getDefaultRoute() { return this.defaultRoute; } /** * Returns the finder class to instantiate. * * @return the finder class to instantiate. */ public Class getFinderClass() { return this.finderClass; } /** * Returns the matching mode for the target Restlet. By default it returns * {@link #getDefaultMatchingMode()}. If the target is an instance of * {@link Directory} or {@link Router} then the mode returned is * {@link Template#MODE_STARTS_WITH} to allow further routing by those * objects. If the target is an instance of {@link Filter}, then it returns * the matching mode for the {@link Filter#getNext()} Restlet recursively. * * @param target * The target Restlet. * @return The preferred matching mode. */ protected int getMatchingMode(Restlet target) { int result = getDefaultMatchingMode(); if ((target instanceof Directory) || (target instanceof Router)) { result = Template.MODE_STARTS_WITH; } else if (target instanceof Filter) { result = getMatchingMode(((Filter) target).getNext()); } return result; } /** * Returns the maximum number of attempts if no attachment could be matched * on the first attempt. This is useful when the attachment scoring is * dynamic and therefore could change on a retry. The default value is set * to 1. * * @return The maximum number of attempts if no attachment could be matched * on the first attempt. */ public int getMaxAttempts() { return this.maxAttempts; } /** * Returns the next Restlet if available. * * @param request * The request to handle. * @param response * The response to update. * @return The next Restlet if available or null. */ @SuppressWarnings("deprecation") public Restlet getNext(Request request, Response response) { Route result = null; for (int i = 0; (result == null) && (i < getMaxAttempts()); i++) { if (i > 0) { // Before attempting another time, let's // sleep during the "retryDelay" set. try { Thread.sleep(getRetryDelay()); } catch (InterruptedException e) { } } if (this.routes != null) { // Select the routing mode switch (getRoutingMode()) { case MODE_BEST_MATCH: result = getRoutes().getBest(request, response, getRequiredScore()); break; case MODE_FIRST_MATCH: result = getRoutes().getFirst(request, response, getRequiredScore()); break; case MODE_LAST_MATCH: result = getRoutes().getLast(request, response, getRequiredScore()); break; case MODE_NEXT_MATCH: result = getRoutes().getNext(request, response, getRequiredScore()); break; case MODE_RANDOM_MATCH: result = getRoutes().getRandom(request, response, getRequiredScore()); break; case MODE_CUSTOM: result = getCustom(request, response); break; } } } if (result == null) { // If nothing matched in the routes list, check the default // route if ((getDefaultRoute() != null) && (getDefaultRoute().score(request, response) >= getRequiredScore())) { result = getDefaultRoute(); } else { // No route could be found response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } logRoute(result); return result; } /** * Returns the minimum score required to have a match. By default, it * returns {@code 0.5}. * * @return The minimum score required to have a match. */ public float getRequiredScore() { return this.requiredScore; } /** * Returns the delay in milliseconds before a new attempt is made. The * default value is {@code 500}. * * @return The delay in milliseconds before a new attempt is made. */ public long getRetryDelay() { return this.retryDelay; } /** * Returns the modifiable list of routes. Creates a new instance if no one * has been set. * * @return The modifiable list of routes. */ public RouteList getRoutes() { return this.routes; } /** * Returns the routing mode. By default, it returns the * {@link #MODE_FIRST_MATCH} mode. * * @return The routing mode. */ public int getRoutingMode() { return this.routingMode; } /** * Handles a call by invoking the next Restlet if it is available. * * @param request * The request to handle. * @param response * The response to update. */ @Override public void handle(Request request, Response response) { super.handle(request, response); Restlet next = getNext(request, response); if (next != null) { doHandle(next, request, response); } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } /** * Logs the route selected. * * @param route * The route selected. */ @SuppressWarnings("deprecation") protected void logRoute(Route route) { if (getLogger().isLoggable(Level.FINE)) { if (getDefaultRoute() == route) { getLogger().fine("The default route was selected."); } else { getLogger().fine("This route was selected: " + route); } } } /** * Sets the default matching mode to use when selecting routes based on * URIs. By default it is set to {@link Template#MODE_EQUALS}. * * @param defaultMatchingMode * The default matching mode. */ public void setDefaultMatchingMode(int defaultMatchingMode) { this.defaultMatchingMode = defaultMatchingMode; } /** * Sets the default setting for whether the routing should be done on URIs * with or without taking into account query string. By default, it is set * to false. * * @param defaultMatchingQuery * The default setting for whether the routing should be done on * URIs with or without taking into account query string. * */ public void setDefaultMatchingQuery(boolean defaultMatchingQuery) { setDefaultMatchQuery(defaultMatchingQuery); } /** * Sets the default setting for whether the routing should be done on URIs * with or without taking into account query string. By default, it is set * to false. * * @param defaultMatchingQuery * The default setting for whether the routing should be done on * URIs with or without taking into account query string. * @deprecated Use {@link #setDefaultMatchingQuery(boolean)} instead. */ @Deprecated public void setDefaultMatchQuery(boolean defaultMatchingQuery) { this.defaultMatchingQuery = defaultMatchingQuery; } /** * Sets the default route tested if no other one was available. * * @param defaultRoute * The default route tested if no other one was available. */ @SuppressWarnings("deprecation") public void setDefaultRoute(Route defaultRoute) { this.defaultRoute = defaultRoute; } /** * Sets the finder class to instantiate. * * @param finderClass * The finder class to instantiate. */ public void setFinderClass(Class finderClass) { this.finderClass = finderClass; } /** * Sets the maximum number of attempts if no attachment could be matched on * the first attempt. This is useful when the attachment scoring is dynamic * and therefore could change on a retry. * * @param maxAttempts * The maximum number of attempts. */ public void setMaxAttempts(int maxAttempts) { this.maxAttempts = maxAttempts; } /** * Sets the score required to have a match. By default, it is set to * {@code 0.5}. * * @param score * The score required to have a match. */ public void setRequiredScore(float score) { this.requiredScore = score; } /** * Sets the delay in milliseconds before a new attempt is made. By default, * it is set to {@code 500}. * * @param retryDelay * The delay in milliseconds before a new attempt is made. */ public void setRetryDelay(long retryDelay) { this.retryDelay = retryDelay; } /** * Sets the modifiable list of routes. * * @param routes * The modifiable list of routes. */ public void setRoutes(RouteList routes) { this.routes = routes; } /** * Sets the routing mode. By default, it is set to the * {@link #MODE_FIRST_MATCH} mode. * * @param routingMode * The routing mode. */ public void setRoutingMode(int routingMode) { this.routingMode = routingMode; } /** * Starts the filter and the attached routes. */ @SuppressWarnings("deprecation") @Override public synchronized void start() throws Exception { if (isStopped()) { super.start(); for (Route route : getRoutes()) { route.start(); } if (getDefaultRoute() != null) { getDefaultRoute().start(); } } } /** * Stops the filter and the attached routes. */ @SuppressWarnings("deprecation") @Override public synchronized void stop() throws Exception { if (isStarted()) { if (getDefaultRoute() != null) { getDefaultRoute().stop(); } for (Route route : getRoutes()) { route.stop(); } super.stop(); } } } restlet-2.0.14/org.restlet/src/org/restlet/routing/Filter.java0000664000175000017500000002105111757206346025035 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.routing; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Status; import org.restlet.resource.Finder; import org.restlet.resource.ServerResource; /** * Restlet filtering calls before passing them to an attached Restlet. The * purpose is to do some pre-processing or post-processing on the calls going * through it before or after they are actually handled by an attached Restlet. * Also note that you can attach and detach targets while handling incoming * calls as the filter is ensured to be thread-safe.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public abstract class Filter extends Restlet { /** * Indicates that the request processing should continue normally. If * returned from the {@link #beforeHandle(Request, Response)} method, the * filter then invokes the {@link #doHandle(Request, Response)} method. If * returned from the {@link #doHandle(Request, Response)} method, the filter * then invokes the {@link #afterHandle(Request, Response)} method. */ public static final int CONTINUE = 0; /** * Indicates that after the {@link #beforeHandle(Request, Response)} method, * the request processing should skip the * {@link #doHandle(Request, Response)} method to continue with the * {@link #afterHandle(Request, Response)} method. */ public static final int SKIP = 1; /** * Indicates that the request processing should stop and return the current * response from the filter. */ public static final int STOP = 2; /** The next Restlet. */ private volatile Restlet next; /** * Constructor. */ public Filter() { this(null); } /** * Constructor. * * @param context * The context. */ public Filter(Context context) { this(context, null); } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. */ public Filter(Context context, Restlet next) { super(context); this.next = next; } /** * Allows filtering after processing by the next Restlet. Does nothing by * default. * * @param request * The request to handle. * @param response * The response to update. */ protected void afterHandle(Request request, Response response) { // To be overriden } /** * Allows filtering before processing by the next Restlet. Returns * {@link #CONTINUE} by default. * * @param request * The request to handle. * @param response * The response to update. * @return The continuation status. Either {@link #CONTINUE} or * {@link #SKIP} or {@link #STOP}. */ protected int beforeHandle(Request request, Response response) { return CONTINUE; } /** * Handles the call by distributing it to the next Restlet. If no Restlet is * attached, then a {@link Status#SERVER_ERROR_INTERNAL} status is returned. * Returns {@link #CONTINUE} by default. * * @param request * The request to handle. * @param response * The response to update. * @return The continuation status. Either {@link #CONTINUE} or * {@link #STOP}. */ protected int doHandle(Request request, Response response) { final int result = CONTINUE; if (getNext() != null) { getNext().handle(request, response); // Re-associate the response to the current thread Response.setCurrent(response); // Associate the context to the current thread if (getContext() != null) { Context.setCurrent(getContext()); } } else { response.setStatus(Status.SERVER_ERROR_INTERNAL); getLogger() .warning( "The filter " + getName() + " was executed without a next Restlet attached to it."); } return result; } /** * Returns the next Restlet. * * @return The next Restlet or null. */ public Restlet getNext() { return this.next; } /** * Handles a call by first invoking the beforeHandle() method for * pre-filtering, then distributing the call to the next Restlet via the * doHandle() method. When the handling is completed, it finally invokes the * afterHandle() method for post-filtering. * * @param request * The request to handle. * @param response * The response to update. */ @Override public final void handle(Request request, Response response) { super.handle(request, response); switch (beforeHandle(request, response)) { case CONTINUE: switch (doHandle(request, response)) { case CONTINUE: afterHandle(request, response); break; default: // Stop the processing break; } break; case SKIP: afterHandle(request, response); break; default: // Stop the processing break; } } /** * Indicates if there is a next Restlet. * * @return True if there is a next Restlet. */ public boolean hasNext() { return getNext() != null; } /** * Sets the next Restlet as a Finder for a given * {@link org.restlet.resource.Handler} or {@link ServerResource} class. * When the call is delegated to the Finder instance, a new instance of the * resource class will be created and will actually handle the request. * * @param targetClass * The target resource class to attach. */ public void setNext(Class targetClass) { setNext(new Finder(getContext(), targetClass)); } /** * Sets the next Restlet. * * In addition, this method will set the context of the next Restlet if it * is null by passing a reference to its own context. * * @param next * The next Restlet. */ public void setNext(Restlet next) { if ((next != null) && (next.getContext() == null)) { next.setContext(getContext()); } this.next = next; } /** * Starts the filter and the next Restlet if attached. */ @Override public synchronized void start() throws Exception { if (isStopped()) { super.start(); if (getNext() != null) { getNext().start(); } } } /** * Stops the filter and the next Restlet if attached. */ @Override public synchronized void stop() throws Exception { if (isStarted()) { if (getNext() != null) { getNext().stop(); } super.stop(); } } } restlet-2.0.14/org.restlet/src/org/restlet/representation/0000775000175000017500000000000011757206350024314 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/representation/ReadableRepresentation.java0000664000175000017500000000723011757206346031610 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.engine.io.NioUtils; /** * Transient representation based on a readable NIO byte channel. * * @author Jerome Louvel */ public class ReadableRepresentation extends ChannelRepresentation { /** The representation's input stream. */ private volatile ReadableByteChannel channel; /** * Constructor. * * @param readableChannel * The representation's channel. * @param mediaType * The representation's media type. */ public ReadableRepresentation(ReadableByteChannel readableChannel, MediaType mediaType) { this(readableChannel, mediaType, UNKNOWN_SIZE); } /** * Constructor. * * @param channel * The representation's channel. * @param mediaType * The representation's media type. * @param expectedSize * The expected stream size. */ public ReadableRepresentation(ReadableByteChannel channel, MediaType mediaType, long expectedSize) { super(mediaType); setSize(expectedSize); this.channel = channel; setAvailable(channel != null); setTransient(true); } @Override public ReadableByteChannel getChannel() throws IOException { ReadableByteChannel result = this.channel; setAvailable(false); return result; } /** * Closes and releases the readable channel. */ @Override public void release() { if (this.channel != null) { try { this.channel.close(); } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Error while releasing the representation.", e); } this.channel = null; } super.release(); } /** * Sets the readable channel. * * @param channel * The readable channel. */ public void setChannel(ReadableByteChannel channel) { this.channel = channel; } @Override public void write(WritableByteChannel writableChannel) throws IOException { NioUtils.copy(getChannel(), writableChannel); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/RepresentationInfo.java0000664000175000017500000001343211757206346031005 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.util.Date; import org.restlet.data.MediaType; import org.restlet.data.Tag; import org.restlet.engine.util.DateUtils; /** * Information about a representation. Those metadata don't belong to the parent * {@link Variant} class, however they are important for conditional method * processing. The advantage over the complete {@link Representation} class is * that it is much lighter to create. * * @see Source dissertation * @author Jerome Louvel */ public class RepresentationInfo extends Variant { /** The modification date. */ private volatile Date modificationDate; /** The tag. */ private volatile Tag tag; /** * Default constructor. */ public RepresentationInfo() { this(null); } /** * Constructor. * * @param mediaType * The media type. */ public RepresentationInfo(MediaType mediaType) { this(mediaType, null, null); } /** * Constructor. * * @param mediaType * The media type. * @param modificationDate * The modification date. */ public RepresentationInfo(MediaType mediaType, Date modificationDate) { this(mediaType, modificationDate, null); } /** * Constructor. * * @param mediaType * The media type. * @param modificationDate * The modification date. * @param tag * The tag. */ public RepresentationInfo(MediaType mediaType, Date modificationDate, Tag tag) { super(mediaType); this.modificationDate = modificationDate; this.tag = tag; } /** * Constructor. * * @param mediaType * The media type. * @param tag * The tag. */ public RepresentationInfo(MediaType mediaType, Tag tag) { this(mediaType, null, tag); } /** * Constructor from a variant. * * @param variant * The variant to copy. * @param modificationDate * The modification date. */ public RepresentationInfo(Variant variant, Date modificationDate) { this(variant, modificationDate, null); } /** * Constructor from a variant. * * @param variant * The variant to copy. * @param modificationDate * The modification date. * @param tag * The tag. */ public RepresentationInfo(Variant variant, Date modificationDate, Tag tag) { setCharacterSet(variant.getCharacterSet()); setEncodings(variant.getEncodings()); setLocationRef(variant.getLocationRef()); setLanguages(variant.getLanguages()); setMediaType(variant.getMediaType()); setModificationDate(modificationDate); setTag(tag); } /** * Constructor from a variant. * * @param variant * The variant to copy. * @param tag * The tag. */ public RepresentationInfo(Variant variant, Tag tag) { this(variant, null, tag); } /** * Returns the last date when this representation was modified. If this * information is not known, returns null.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Last-Modified" header. * * @return The modification date. */ public Date getModificationDate() { return this.modificationDate; } /** * Returns the tag.
    *
    * Note that when used with HTTP connectors, this property maps to the * "ETag" header. * * @return The tag. */ public Tag getTag() { return this.tag; } /** * Sets the last date when this representation was modified. If this * information is not known, pass null.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Last-Modified" header. * * @param modificationDate * The modification date. */ public void setModificationDate(Date modificationDate) { this.modificationDate = DateUtils.unmodifiable(modificationDate); } /** * Sets the tag.
    *
    * Note that when used with HTTP connectors, this property maps to the * "ETag" header. * * @param tag * The tag. */ public void setTag(Tag tag) { this.tag = tag; } } restlet-2.0.14/org.restlet/src/org/restlet/representation/DigestRepresentation.java0000664000175000017500000001655211757206346031337 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.security.DigestInputStream; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.restlet.data.Digest; import org.restlet.engine.io.BioUtils; import org.restlet.engine.io.NioUtils; import org.restlet.util.WrapperRepresentation; /** * Representation capable of computing a digest. It wraps another representation * and allows to get the computed digest of the wrapped entity after reading or * writing operations. The final digest value is guaranteed to be correct only * after the wrapped representation has been entirely exhausted (that is to say * read or written).
    *
    * This wrapper allows to get the computed digest at the same time the * representation is read or written. It does not need two separate operations * which may require specific attention for transient representations. * * @see Representation#isTransient(). * @deprecated See {@link DigesterRepresentation} instead. * @author Jerome Louvel */ @Deprecated public abstract class DigestRepresentation extends WrapperRepresentation { /** The digest algorithm. */ private final String algorithm; /** The computed digest value. */ private volatile MessageDigest computedDigest; /** * Constructor.
    * By default, the instance relies on the {@link Digest#ALGORITHM_MD5} * digest algorithm. * * @param wrappedRepresentation * The wrapped representation. * @throws NoSuchAlgorithmException */ public DigestRepresentation(Representation wrappedRepresentation) throws NoSuchAlgorithmException { this(wrappedRepresentation, Digest.ALGORITHM_MD5); } /** * Constructor.
    * * @param wrappedRepresentation * The wrapped representation. * @param algorithm * The digest algorithm * @throws NoSuchAlgorithmException */ public DigestRepresentation(Representation wrappedRepresentation, String algorithm) throws NoSuchAlgorithmException { super(wrappedRepresentation); this.algorithm = algorithm; this.computedDigest = MessageDigest.getInstance(algorithm); } /** * Check that the digest computed from the wrapped representation content * and the digest declared by the wrapped representation are the same. User * must be aware that the computed value is accurate only after a complete * reading or writing operation. */ @Override public boolean checkDigest() { Digest digest = getDigest(); return (digest != null && digest.equals(getComputedDigest())); } /** * {@inheritDoc}
    * If case the given algorithm is the same than the one provided at * instantiation, the check operation is made with the current stored * computed value and does not require to exhaust entirely the * representation's stream. */ @Override public boolean checkDigest(String algorithm) { if (this.algorithm != null && this.algorithm.equals(algorithm)) { return checkDigest(); } return super.checkDigest(algorithm); } /** * {@inheritDoc}
    * If case the given algorithm is the same than the one provided at * instantiation, the computation operation is made with the current stored * computed value and does not require to exhaust entirely the * representation's stream. */ @Override public Digest computeDigest(String algorithm) { if (this.algorithm != null && this.algorithm.equals(algorithm)) { return getComputedDigest(); } return super.computeDigest(algorithm); } @Override public ReadableByteChannel getChannel() throws IOException { return NioUtils.getChannel(getStream()); } /** * Returns the current computed digest value of the representation. User * must be aware that, if the representation has not been entirely read or * written, the computed digest value may not be accurate. * * @return The current computed digest value. */ public Digest getComputedDigest() { return new Digest(this.algorithm, computedDigest.digest()); } @Override public Reader getReader() throws IOException { return BioUtils.getReader(getStream(), getCharacterSet()); } /** * {@inheritDoc}
    * * The stream of the underlying representation is wrapped with a new * instance of the {@link DigestInputStream} class, which allows to compute * progressively the digest value. */ @Override public InputStream getStream() throws IOException { return new DigestInputStream(getWrappedRepresentation().getStream(), this.computedDigest); } @Override public String getText() throws IOException { String result = null; if (isAvailable()) { if (getSize() == 0) { result = ""; } else { java.io.StringWriter sw = new java.io.StringWriter(); write(sw); result = sw.toString(); } } return result; } /** * {@inheritDoc}
    * * The output stream is wrapped with a new instance of the * {@link DigestOutputStream} class, which allows to compute progressively * the digest value. */ @Override public void write(OutputStream outputStream) throws IOException { OutputStream dos = new DigestOutputStream(outputStream, this.computedDigest); getWrappedRepresentation().write(dos); dos.flush(); } @Override public void write(WritableByteChannel writableChannel) throws IOException { write(NioUtils.getStream(writableChannel)); } @Override public void write(Writer writer) throws IOException { write(BioUtils.getStream(writer)); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/InputRepresentation.java0000664000175000017500000001015011757206350031176 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.engine.Edition; import org.restlet.engine.io.BioUtils; /** * Transient representation based on a BIO input stream. * * @author Jerome Louvel */ public class InputRepresentation extends StreamRepresentation { /** The representation's stream. */ private volatile InputStream stream; /** * Constructor. * * @param inputStream * The representation's stream. */ public InputRepresentation(InputStream inputStream) { this(inputStream, null); } /** * Constructor. * * @param inputStream * The representation's stream. * @param mediaType * The representation's media type. */ public InputRepresentation(InputStream inputStream, MediaType mediaType) { this(inputStream, mediaType, UNKNOWN_SIZE); } /** * Constructor. * * @param inputStream * The representation's stream. * @param mediaType * The representation's media type. * @param expectedSize * The expected input stream size. */ public InputRepresentation(InputStream inputStream, MediaType mediaType, long expectedSize) { super(mediaType); setSize(expectedSize); setTransient(true); setStream(inputStream); } @Override public InputStream getStream() throws IOException { if (Edition.CURRENT != Edition.GWT) { final InputStream result = this.stream; setStream(null); return result; } return this.stream; } /** * Note that this method relies on {@link #getStream()}. This stream is * closed once fully read. */ @Override public String getText() throws IOException { return BioUtils.toString(getStream(), getCharacterSet()); } /** * Closes and releases the input stream. */ @Override public void release() { if (this.stream != null) { try { this.stream.close(); } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Error while releasing the representation.", e); } this.stream = null; } super.release(); } /** * Sets the input stream to use. * * @param stream * The input stream to use. */ public void setStream(InputStream stream) { this.stream = stream; setAvailable(stream != null); } @Override public void write(OutputStream outputStream) throws IOException { BioUtils.copy(getStream(), outputStream); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/Variant.java0000664000175000017500000004625111757206346026600 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.restlet.data.CharacterSet; import org.restlet.data.ClientInfo; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.data.Reference; import org.restlet.util.WrapperList; /** * Descriptor for available representations of a resource. It contains all the * important metadata about a representation but is not able to actually serve * the representation's content itself.
    *
    * For this, you need to use the Representation subclass. * * @author Jerome Louvel */ public class Variant { /** The character set or null if not applicable. */ private volatile CharacterSet characterSet; /** The additional content codings applied to the entity-body. */ private volatile List encodings; /** The location reference. */ private volatile Reference locationRef; /** The natural language(s) of the intended audience for this variant. */ private volatile List languages; /** The media type. */ private volatile MediaType mediaType; /** * Default constructor. */ public Variant() { this(null); } /** * Constructor. * * @param mediaType * The media type. */ public Variant(MediaType mediaType) { this(mediaType, null); } /** * Constructor. * * @param mediaType * The media type. * @param language * The language. */ public Variant(MediaType mediaType, Language language) { this.characterSet = null; this.encodings = null; if (language != null) { getLanguages().add(language); } else { this.languages = null; } this.mediaType = mediaType; this.locationRef = null; } /** * Creates a {@link ClientInfo} instance with preferences matching exactly * the current variant. * * @return The new {@link ClientInfo} instance. */ public ClientInfo createClientInfo() { ClientInfo result = new ClientInfo(); if (getCharacterSet() != null) { result.getAcceptedCharacterSets().add( new Preference(getCharacterSet())); } if (getEncodings() != null) { for (Encoding encoding : getEncodings()) { result.getAcceptedEncodings().add( new Preference(encoding)); } } if (getLanguages() != null) { for (Language language : getLanguages()) { result.getAcceptedLanguages().add( new Preference(language)); } } if (getMediaType() != null) { result.getAcceptedMediaTypes().add( new Preference(getMediaType())); } return result; } /** * Indicates if the current variant is equal to the given variant. * * @param other * The other variant. * @return True if the current variant includes the other. */ @Override public boolean equals(Object other) { boolean result = (other instanceof Variant); if (result && (other != this)) { Variant otherVariant = (Variant) other; // Compare the character set if (result) { result = ((getCharacterSet() == null) && (otherVariant.getCharacterSet() == null) || (getCharacterSet() != null) && getCharacterSet().equals( otherVariant.getCharacterSet())); } // Compare the media type if (result) { result = ((getMediaType() == null) && (otherVariant.getMediaType() == null) || (getMediaType() != null) && getMediaType().equals(otherVariant.getMediaType())); } // Compare the languages if (result) { result = getLanguages().equals(otherVariant.getLanguages()); } // Compare the encodings if (result) { result = getEncodings().equals(otherVariant.getEncodings()); } // Compare the location URI if (result) { result = ((getLocationRef() == null) && (otherVariant.getLocationRef() == null) || (getLocationRef() != null) && getLocationRef().equals( otherVariant.getLocationRef())); } } return result; } /** * Returns the character set or null if not applicable. Note that when used * with HTTP connectors, this property maps to the "Content-Type" header. * * @return The character set or null if not applicable. */ public CharacterSet getCharacterSet() { return this.characterSet; } /** * Returns the modifiable list of encodings applied to the entity-body. * Creates a new instance if no one has been set. An * "IllegalArgumentException" exception is thrown when adding a null * encoding to this list.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Encoding" header. * * @return The list of encodings applied to the entity-body. */ public List getEncodings() { if (this.encodings == null) { this.encodings = new WrapperList() { @Override public boolean add(Encoding element) { if (element == null) { throw new IllegalArgumentException( "Cannot add a null encoding."); } return super.add(element); } @Override public void add(int index, Encoding element) { if (element == null) { throw new IllegalArgumentException( "Cannot add a null encoding."); } super.add(index, element); } @Override public boolean addAll(Collection elements) { boolean addNull = (elements == null); if (!addNull) { for (final Iterator iterator = elements .iterator(); !addNull && iterator.hasNext();) { addNull = (iterator.next() == null); } } if (addNull) { throw new IllegalArgumentException( "Cannot add a null encoding."); } return super.addAll(elements); } @Override public boolean addAll(int index, Collection elements) { boolean addNull = (elements == null); if (!addNull) { for (final Iterator iterator = elements .iterator(); !addNull && iterator.hasNext();) { addNull = (iterator.next() == null); } } if (addNull) { throw new IllegalArgumentException( "Cannot add a null encoding."); } return super.addAll(index, elements); } }; } return this.encodings; } /** * Returns an optional identifier. This is useful when the representation is * accessible from a location separate from the representation's resource * URI, for example when content negotiation occurs.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Location" header. * * @return The identifier. * @deprecated Use {@link #getLocationRef()} instead. */ @Deprecated public Reference getIdentifier() { return getLocationRef(); } /** * Returns the modifiable list of languages. Creates a new instance if no * one has been set. An "IllegalArgumentException" exception is thrown when * adding a null language to this list.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Language" header. * * @return The list of languages. */ public List getLanguages() { if (this.languages == null) { this.languages = new WrapperList() { @Override public void add(int index, Language element) { if (element == null) { throw new IllegalArgumentException( "Cannot add a null language."); } super.add(index, element); } @Override public boolean add(Language element) { if (element == null) { throw new IllegalArgumentException( "Cannot add a null language."); } return super.add(element); } @Override public boolean addAll(Collection elements) { boolean addNull = (elements == null); if (!addNull) { for (final Iterator iterator = elements .iterator(); !addNull && iterator.hasNext();) { addNull = (iterator.next() == null); } } if (addNull) { throw new IllegalArgumentException( "Cannot add a null language."); } return super.addAll(elements); } @Override public boolean addAll(int index, Collection elements) { boolean addNull = (elements == null); if (!addNull) { for (final Iterator iterator = elements .iterator(); !addNull && iterator.hasNext();) { addNull = (iterator.next() == null); } } if (addNull) { throw new IllegalArgumentException( "Cannot add a null language."); } return super.addAll(index, elements); } }; } return this.languages; } /** * Returns an optional location reference. This is useful when the * representation is accessible from a location separate from the * representation's resource URI, for example when content negotiation * occurs.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Location" header. * * @return The identifier. */ public Reference getLocationRef() { return this.locationRef; } /** * Returns the media type.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Type" header. * * @return The media type. */ public MediaType getMediaType() { return this.mediaType; } /** * Indicates if the current variant includes the given variant. * * @param other * The other variant. * @return True if the current variant includes the other. */ public boolean includes(Variant other) { boolean result = other != null; // Compare the character set if (result) { result = (getCharacterSet() == null) || getCharacterSet().includes(other.getCharacterSet()); } // Compare the media type if (result) { result = (getMediaType() == null) || getMediaType().includes(other.getMediaType()); } // Compare the languages if (result) { result = (getLanguages().isEmpty()) || getLanguages().contains(Language.ALL) || getLanguages().containsAll(other.getLanguages()); } // Compare the encodings if (result) { result = (getEncodings().isEmpty()) || getEncodings().contains(Encoding.ALL) || getEncodings().containsAll(other.getEncodings()); } return result; } /** * Indicates if the current variant is compatible with the given variant. * * @param other * The other variant. * @return True if the current variant is compatible with the other. */ public boolean isCompatible(Variant other) { return (other != null) && (includes(other) || other.includes(this)); } /** * Sets the character set or null if not applicable.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Type" header. * * @param characterSet * The character set or null if not applicable. */ public void setCharacterSet(CharacterSet characterSet) { this.characterSet = characterSet; } /** * Sets the list of encodings applied to the entity-body.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Encoding" header. * * @param encodings * The list of encodings applied to the entity-body. */ public void setEncodings(List encodings) { this.encodings = encodings; } /** * Sets the optional identifier. This is useful when the representation is * accessible from a location separate from the representation's resource * URI, for example when content negotiation occurs.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Location" header. * * @param identifier * The identifier. * @deprecated Use {@link #setLocationRef(Reference)} instead */ @Deprecated public void setIdentifier(Reference identifier) { setLocationRef(identifier); } /** * Sets the identifier from a URI string.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Location" header. * * @param identifierUri * The identifier to parse. * @see #setIdentifier(Reference) * @deprecated Use {@link #setLocationRef(String)} instead. */ @Deprecated public void setIdentifier(String identifierUri) { setLocationRef(identifierUri); } /** * Sets the list of languages.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Language" header. * * @param languages * The list of languages. */ public void setLanguages(List languages) { this.languages = languages; } /** * Sets the optional identifier. This is useful when the representation is * accessible from a location separate from the representation's resource * URI, for example when content negotiation occurs.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Location" header. * * @param location * The location reference. */ public void setLocationRef(Reference location) { this.locationRef = location; } /** * Sets the identifier from a URI string.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Location" header. * * @param locationUri * The location URI to parse. * @see #setIdentifier(Reference) */ public void setLocationRef(String locationUri) { setLocationRef(new Reference(locationUri)); } /** * Sets the media type.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Type" header. * * @param mediaType * The media type. */ public void setMediaType(MediaType mediaType) { this.mediaType = mediaType; } @Override public String toString() { StringBuilder sb = new StringBuilder("["); boolean first = true; if (getIdentifier() != null) { sb.append(getIdentifier()); first = false; } if (getMediaType() != null) { if (!first) { sb.append(","); } else { first = false; } sb.append(getMediaType()); } if (getCharacterSet() != null) { if (!first) { sb.append(","); } else { first = false; } sb.append(getCharacterSet()); } if (!getLanguages().isEmpty()) { if (!first) { sb.append(","); } else { first = false; } sb.append(getLanguages()); } if (!getEncodings().isEmpty()) { if (!first) { sb.append(","); } else { first = false; } sb.append(getEncodings()); } sb.append("]"); return sb.toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/ObjectRepresentation.java0000664000175000017500000001377011757206346031325 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import org.restlet.data.MediaType; /** * Representation based on a serializable Java object. * * @author Jerome Louvel * @param * The class to serialize, see {@link Serializable} */ public class ObjectRepresentation extends OutputRepresentation { /** The serializable object. */ private volatile T object; /** * Constructor reading the object from a serialized representation. This * representation must have the proper media type: * "application/x-java-serialized-object". * * @param serializedRepresentation * The serialized representation. * @throws IOException * @throws ClassNotFoundException * @throws IllegalArgumentException */ @SuppressWarnings("unchecked") public ObjectRepresentation(Representation serializedRepresentation) throws IOException, ClassNotFoundException, IllegalArgumentException { super(MediaType.APPLICATION_JAVA_OBJECT); if (serializedRepresentation.getMediaType().equals( MediaType.APPLICATION_JAVA_OBJECT)) { setMediaType(MediaType.APPLICATION_JAVA_OBJECT); InputStream is = serializedRepresentation.getStream(); ObjectInputStream ois = new ObjectInputStream(is); this.object = (T) ois.readObject(); if (is.read() != -1) { throw new IOException( "The input stream has not been fully read."); } ois.close(); } else if (serializedRepresentation.getMediaType().equals( MediaType.APPLICATION_JAVA_OBJECT_XML)) { setMediaType(MediaType.APPLICATION_JAVA_OBJECT_XML); InputStream is = serializedRepresentation.getStream(); java.beans.XMLDecoder decoder = new java.beans.XMLDecoder(is); this.object = (T) decoder.readObject(); if (is.read() != -1) { throw new IOException( "The input stream has not been fully read."); } decoder.close(); } else { throw new IllegalArgumentException( "The serialized representation must have this media type: " + MediaType.APPLICATION_JAVA_OBJECT.toString() + " or this one: " + MediaType.APPLICATION_JAVA_OBJECT_XML.toString()); } } /** * Constructor for the {@link MediaType#APPLICATION_JAVA_OBJECT} type. * * @param object * The serializable object. */ public ObjectRepresentation(T object) { super(MediaType.APPLICATION_JAVA_OBJECT); this.object = object; } /** * Constructor for either the {@link MediaType#APPLICATION_JAVA_OBJECT} type * or the {@link MediaType#APPLICATION_XML} type. In the first case, the * Java Object Serialization mechanism is used, based on * {@link ObjectOutputStream}. In the latter case, the JavaBeans XML * serialization is used, based on {@link java.beans.XMLEncoder}. * * @param object * The serializable object. * @param mediaType * The media type. */ public ObjectRepresentation(T object, MediaType mediaType) { super((mediaType == null) ? MediaType.APPLICATION_JAVA_OBJECT : mediaType); this.object = object; } /** * Returns the represented object. * * @return The represented object. * @throws IOException */ public T getObject() throws IOException { return this.object; } /** * Releases the represented object. */ @Override public void release() { setObject(null); super.release(); } /** * Sets the represented object. * * @param object * The represented object. */ public void setObject(T object) { this.object = object; } @Override public void write(OutputStream outputStream) throws IOException { if (MediaType.APPLICATION_JAVA_OBJECT.isCompatible(getMediaType())) { ObjectOutputStream oos = new ObjectOutputStream(outputStream); oos.writeObject(getObject()); oos.flush(); } else if (MediaType.APPLICATION_JAVA_OBJECT_XML .isCompatible(getMediaType())) { java.beans.XMLEncoder encoder = new java.beans.XMLEncoder( outputStream); encoder.writeObject(getObject()); encoder.close(); } } } restlet-2.0.14/org.restlet/src/org/restlet/representation/StringRepresentation.java0000664000175000017500000001430311757206346031356 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; /** * Represents an Unicode string that can be converted to any character set * supported by Java. * * @author Jerome Louvel */ public class StringRepresentation extends CharacterRepresentation { /** The string value. */ private volatile CharSequence text; /** * Constructor. The following metadata are used by default: "text/plain" * media type, no language and the UTF-8 character set. * * @param text * The string value. */ public StringRepresentation(CharSequence text) { this(text, MediaType.TEXT_PLAIN); } /** * Constructor. The following metadata are used by default: "text/plain" * media type, no language and the UTF-8 character set. * * @param text * The string value. * @param language * The language. */ public StringRepresentation(CharSequence text, Language language) { this(text, MediaType.TEXT_PLAIN, language); } /** * Constructor. The following metadata are used by default: no language and * the UTF-8 character set. * * @param text * The string value. * @param mediaType * The media type. */ public StringRepresentation(CharSequence text, MediaType mediaType) { this(text, mediaType, null); } /** * Constructor. The following metadata are used by default: UTF-8 character * set. * * @param text * The string value. * @param mediaType * The media type. * @param language * The language. */ public StringRepresentation(CharSequence text, MediaType mediaType, Language language) { this(text, mediaType, language, CharacterSet.UTF_8); } /** * Constructor. * * @param text * The string value. * @param mediaType * The media type. * @param language * The language. * @param characterSet * The character set. */ public StringRepresentation(CharSequence text, MediaType mediaType, Language language, CharacterSet characterSet) { super(mediaType); setMediaType(mediaType); if (language != null) { getLanguages().add(language); } setCharacterSet(characterSet); setText(text); } @Override public InputStream getStream() throws IOException { CharacterSet charset = getCharacterSet() == null ? CharacterSet.ISO_8859_1 : getCharacterSet(); ByteArrayInputStream result = new ByteArrayInputStream(getText() .getBytes(charset.getName())); return result; } @Override public Reader getReader() throws IOException { if (getText() != null) { return new StringReader(getText()); } return null; } @Override public String getText() { return (this.text == null) ? null : this.text.toString(); } /** * Closes and releases the input stream. */ @Override public void release() { setText(null); super.release(); } @Override public void setCharacterSet(CharacterSet characterSet) { super.setCharacterSet(characterSet); updateSize(); } /** * Sets the string value. * * @param text * The string value. */ public void setText(CharSequence text) { this.text = text; updateSize(); } /** * Sets the string value. * * @param text * The string value. */ public void setText(String text) { setText((CharSequence) text); } /** * Updates the expected size according to the current string value. */ protected void updateSize() { if (getText() != null) { try { if (getCharacterSet() != null) { setSize(getText().getBytes(getCharacterSet().getName()).length); } else { setSize(getText().getBytes().length); } } catch (UnsupportedEncodingException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to update size", e); setSize(UNKNOWN_SIZE); } } else { setSize(UNKNOWN_SIZE); } } @Override public void write(Writer writer) throws IOException { if (getText() != null) { writer.write(getText()); writer.flush(); } } } restlet-2.0.14/org.restlet/src/org/restlet/representation/ReaderRepresentation.java0000664000175000017500000000757011757206346031322 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; /** * Transient representation based on a BIO characters reader. * * @author Jerome Louvel */ public class ReaderRepresentation extends CharacterRepresentation { /** The representation's reader. */ private volatile Reader reader; /** * Constructor. * * @param reader * The representation's stream. */ public ReaderRepresentation(Reader reader) { this(reader, null); } /** * Constructor. * * @param reader * The representation's stream. * @param mediaType * The representation's media type. */ public ReaderRepresentation(Reader reader, MediaType mediaType) { this(reader, mediaType, UNKNOWN_SIZE); } /** * Constructor. * * @param reader * The representation's stream. * @param mediaType * The representation's media type. * @param expectedSize * The expected reader size in bytes. */ public ReaderRepresentation(Reader reader, MediaType mediaType, long expectedSize) { super(mediaType); setSize(expectedSize); setTransient(true); setReader(reader); } @Override public Reader getReader() throws IOException { final Reader result = this.reader; setReader(null); return result; } /** * Note that this method relies on {@link #getStream()}. This stream is * closed once fully read. */ @Override public String getText() throws IOException { return BioUtils.toString(getStream(), getCharacterSet()); } /** * Closes and releases the input stream. */ @Override public void release() { if (this.reader != null) { try { this.reader.close(); } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Error while releasing the representation.", e); } this.reader = null; } super.release(); } /** * Sets the reader to use. * * @param reader * The reader to use. */ public void setReader(Reader reader) { this.reader = reader; setAvailable(reader != null); } @Override public void write(Writer writer) throws IOException { BioUtils.copy(getReader(), writer); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/package.html0000664000175000017500000000034611757206350026600 0ustar jamespagejamespage Common representation data elements.

    @since Restlet 2.0 @see User Guide - Representation package restlet-2.0.14/org.restlet/src/org/restlet/representation/EmptyRepresentation.java0000664000175000017500000000512311757206346031206 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; /** * Empty representation with no content. It is always considered available but * calling the {@link #getText()} method for example will return an empty * string. It can also have regular metadata available. * * @author Jerome Louvel */ public class EmptyRepresentation extends Representation { /** * Constructor. */ public EmptyRepresentation() { setAvailable(false); setTransient(true); setSize(0); } @Override public java.nio.channels.ReadableByteChannel getChannel() throws IOException { return null; } @Override public Reader getReader() throws IOException { return null; } @Override public InputStream getStream() throws IOException { return null; } @Override public String getText() throws IOException { return null; } @Override public void write(java.io.Writer writer) throws IOException { // Do nothing } @Override public void write(java.nio.channels.WritableByteChannel writableChannel) throws IOException { // Do nothing } @Override public void write(OutputStream outputStream) throws IOException { // Do nothing } } restlet-2.0.14/org.restlet/src/org/restlet/representation/ChannelRepresentation.java0000664000175000017500000000454011757206346031462 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; import org.restlet.engine.io.NioUtils; /** * Representation based on a NIO byte channel. * * @author Jerome Louvel */ public abstract class ChannelRepresentation extends Representation { /** * Constructor. * * @param mediaType * The media type. */ public ChannelRepresentation(MediaType mediaType) { super(mediaType); } @Override public Reader getReader() throws IOException { return BioUtils.getReader(getStream(), getCharacterSet()); } @Override public InputStream getStream() throws IOException { return NioUtils.getStream(getChannel()); } @Override public void write(OutputStream outputStream) throws IOException { NioUtils.copy(getChannel(), outputStream); } @Override public void write(Writer writer) throws IOException { write(BioUtils.getStream(writer)); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/FileRepresentation.java0000664000175000017500000002266011757206346030774 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.util.Date; import org.restlet.data.Disposition; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; import org.restlet.engine.io.NioUtils; /** * Representation based on a static file. Note that in order for Web clients to * display a download box upon reception of a file representation, it needs an * additional call to {@link Disposition#setType(String)} with a * {@link Disposition#TYPE_ATTACHMENT} value. * * @author Jerome Louvel */ public class FileRepresentation extends Representation { /** * Creates a new file by detecting if the name is a URI or a simple path * name. * * @param path * The path name or file URI of the represented file (either in * system format or in 'file:///' format). * @return The associated File instance. */ private static File createFile(String path) { if (path.startsWith("file://")) { return new LocalReference(path).getFile(); } return new File(path); } /** * Indicates if this file should be automatically deleted on release of the * representation. */ private volatile boolean autoDeleting; /** The file handle. */ private volatile File file; /** * Constructor that does not set an expiration date for {@code file} * * @param file * The represented file. * @param mediaType * The representation's media type. * @see #FileRepresentation(File, MediaType, int) */ public FileRepresentation(File file, MediaType mediaType) { this(file, mediaType, -1); } /** * Constructor. If a positive "timeToLive" parameter is given, then the * expiration date is set accordingly. If "timeToLive" is equal to zero, * then the expiration date is set to the current date, meaning that it will * immediately expire on the client. If -1 is given, then no expiration date * is set. * * @param file * The represented file. * @param mediaType * The representation's media type. * @param timeToLive * The time to live before it expires (in seconds). */ public FileRepresentation(File file, MediaType mediaType, int timeToLive) { super(mediaType); this.file = file; setModificationDate(new Date(file.lastModified())); if (timeToLive == 0) { setExpirationDate(null); } else if (timeToLive > 0) { setExpirationDate(new Date(System.currentTimeMillis() + (1000L * timeToLive))); } setMediaType(mediaType); Disposition disposition = new Disposition(); disposition.setFilename(file.getName()); this.setDisposition(disposition); } /** * Constructor that does not set an expiration date for {@code path} * * @param path * The path name or file URI of the represented file (either in * system format or in 'file:///' format). * @param mediaType * The representation's media type. * @see #FileRepresentation(String, MediaType, int) */ public FileRepresentation(String path, MediaType mediaType) { this(path, mediaType, -1); } /** * Constructor. * * @param path * The path name or file URI of the represented file (either in * system format or in 'file:///' format). * @param mediaType * The representation's media type. * @param timeToLive * The time to live before it expires (in seconds). * @see java.io.File#File(String) */ public FileRepresentation(String path, MediaType mediaType, int timeToLive) { this(createFile(path), mediaType, timeToLive); } /** * Returns a readable byte channel. If it is supported by a file a read-only * instance of FileChannel is returned. * * @return A readable byte channel. */ @Override public FileChannel getChannel() throws IOException { try { return new FileInputStream(this.file).getChannel(); } catch (FileNotFoundException fnfe) { throw new IOException("Couldn't get the channel. File not found"); } } /** * Returns the file handle. * * @return the file handle. */ public File getFile() { return this.file; } @Override public Reader getReader() throws IOException { return new FileReader(this.file); } @Override public long getSize() { if (super.getSize() != UNKNOWN_SIZE) { return super.getSize(); } return this.file.length(); } @Override public FileInputStream getStream() throws IOException { try { return new FileInputStream(this.file); } catch (FileNotFoundException fnfe) { throw new IOException("Couldn't get the stream. File not found"); } } /** * Note that this method relies on {@link #getStream()}. This stream is * closed once fully read. */ @Override public String getText() throws IOException { return BioUtils.toString(getStream(), getCharacterSet()); } /** * Indicates if this file should be automatically deleted on release of the * representation. * * @return True if this file should be automatically deleted on release of * the representation. * @deprecated Use {@link #isAutoDeleting()} instead. */ @Deprecated public boolean isAutoDelete() { return autoDeleting; } /** * Indicates if this file should be automatically deleted on release of the * representation. * * @return True if this file should be automatically deleted on release of * the representation. */ public boolean isAutoDeleting() { return isAutoDelete(); } /** * Releases the file handle. */ @Override public void release() { if (isAutoDeleting() && getFile() != null) { try { BioUtils.delete(getFile(), true); } catch (Exception e) { } } setFile(null); super.release(); } /** * Indicates if this file should be automatically deleted on release of the * representation. * * @param autoDeleting * True if this file should be automatically deleted on release * of the representation. * @deprecated Use {@link #setAutoDeleting(boolean)} instead. */ @Deprecated public void setAutoDelete(boolean autoDeleting) { this.autoDeleting = autoDeleting; } /** * Indicates if this file should be automatically deleted on release of the * representation. * * @param autoDeleting * True if this file should be automatically deleted on release * of the representation. */ public void setAutoDeleting(boolean autoDeleting) { setAutoDelete(autoDeleting); } /** * Sets the file handle. * * @param file * The file handle. */ public void setFile(File file) { this.file = file; } @Override public void write(OutputStream outputStream) throws IOException { BioUtils.copy(getStream(), outputStream); } /** * Writes the representation to a byte channel. Optimizes using the file * channel transferTo method. * * @param writableChannel * A writable byte channel. */ @Override public void write(WritableByteChannel writableChannel) throws IOException { NioUtils.copy(getChannel(), writableChannel); } @Override public void write(Writer writer) throws IOException { BioUtils.copy(getReader(), writer); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/StreamRepresentation.java0000664000175000017500000000477011757206346031352 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.OutputStream; import java.io.Reader; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; /** * Representation based on a BIO stream. * * @author Jerome Louvel */ public abstract class StreamRepresentation extends Representation { /** * Constructor. * * @param mediaType * The media type. */ public StreamRepresentation(MediaType mediaType) { super(mediaType); } @Override public java.nio.channels.ReadableByteChannel getChannel() throws IOException { return org.restlet.engine.io.NioUtils.getChannel(getStream()); } @Override public Reader getReader() throws IOException { return BioUtils.getReader(getStream(), getCharacterSet()); } @Override public void write(java.nio.channels.WritableByteChannel writableChannel) throws IOException { OutputStream os = org.restlet.engine.io.NioUtils .getStream(writableChannel); write(os); os.flush(); } @Override public void write(java.io.Writer writer) throws IOException { OutputStream os = BioUtils.getStream(writer); write(os); os.flush(); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/OutputRepresentation.java0000664000175000017500000000533711757206346031417 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; /** * Representation based on a BIO output stream. This class is a good basis to * write your own representations, especially for the dynamic and large ones.
    *
    * For this you just need to create a subclass and override the abstract * Representation.write(OutputStream) method. This method will later be called * back by the connectors when the actual representation's content is needed. * * @author Jerome Louvel */ public abstract class OutputRepresentation extends StreamRepresentation { /** * Constructor. * * @param mediaType * The representation's mediaType. */ public OutputRepresentation(MediaType mediaType) { super(mediaType); } /** * Constructor. * * @param mediaType * The representation's mediaType. * @param expectedSize * The expected input stream size. */ public OutputRepresentation(MediaType mediaType, long expectedSize) { super(mediaType); setSize(expectedSize); } /** * Returns a stream with the representation's content. Internally, it uses a * writer thread and a pipe stream. * * @return A stream with the representation's content. */ @Override public InputStream getStream() throws IOException { return BioUtils.getStream(this); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/AppendableRepresentation.java0000664000175000017500000001230411757206350032135 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; /** * Represents an appendable sequence of characters. * * @author Jerome Louvel */ public class AppendableRepresentation extends StringRepresentation implements Appendable { /** The appendable text. */ private volatile StringBuilder appendableText; /** * Constructor. The following metadata are used by default: "text/plain" * media type, no language and the ISO-8859-1 character set. * */ public AppendableRepresentation() { this(null); } /** * Constructor. The following metadata are used by default: "text/plain" * media type, no language and the ISO-8859-1 character set. * * @param text * The string value. */ public AppendableRepresentation(CharSequence text) { super(text); } /** * Constructor. The following metadata are used by default: "text/plain" * media type, no language and the ISO-8859-1 character set. * * @param text * The string value. * @param language * The language. */ public AppendableRepresentation(CharSequence text, Language language) { super(text, language); } /** * Constructor. The following metadata are used by default: no language and * the ISO-8859-1 character set. * * @param text * The string value. * @param mediaType * The media type. */ public AppendableRepresentation(CharSequence text, MediaType mediaType) { super(text, mediaType); } /** * Constructor. The following metadata are used by default: ISO-8859-1 * character set. * * @param text * The string value. * @param mediaType * The media type. * @param language * The language. */ public AppendableRepresentation(CharSequence text, MediaType mediaType, Language language) { super(text, mediaType, language); } /** * Constructor. * * @param text * The string value. * @param mediaType * The media type. * @param language * The language. * @param characterSet * The character set. */ public AppendableRepresentation(CharSequence text, MediaType mediaType, Language language, CharacterSet characterSet) { super(text, mediaType, language, characterSet); } public Appendable append(char c) throws IOException { if (this.appendableText == null) { this.appendableText = new StringBuilder(c); } else { this.appendableText.append(c); } return this; } public Appendable append(CharSequence csq) throws IOException { if (this.appendableText == null) { this.appendableText = new StringBuilder(csq); } else { this.appendableText.append(csq); } return this; } public Appendable append(CharSequence csq, int start, int end) throws IOException { if (this.appendableText == null) { this.appendableText = new StringBuilder(); } this.appendableText.append(csq, start, end); return this; } @Override public String getText() { return (this.appendableText == null) ? null : this.appendableText .toString(); } @Override public void setText(CharSequence text) { if (text != null) { if (this.appendableText == null) { this.appendableText = new StringBuilder(text); } else { this.appendableText.delete(0, this.appendableText.length()); this.appendableText.append(text); } } else { this.appendableText = null; } } } restlet-2.0.14/org.restlet/src/org/restlet/representation/CharacterRepresentation.java0000664000175000017500000000477211757206346032015 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; /** * Representation based on a BIO character stream. * * @author Jerome Louvel */ public abstract class CharacterRepresentation extends Representation { /** * Constructor. * * @param mediaType * The media type. */ public CharacterRepresentation(MediaType mediaType) { super(mediaType); setCharacterSet(CharacterSet.UTF_8); } @Override public java.nio.channels.ReadableByteChannel getChannel() throws IOException { return org.restlet.engine.io.NioUtils.getChannel(getStream()); } @Override public InputStream getStream() throws IOException { return BioUtils.getStream(getReader(), getCharacterSet()); } @Override public void write(OutputStream outputStream) throws IOException { BioUtils.copy(getStream(), outputStream); } @Override public void write(java.nio.channels.WritableByteChannel writableChannel) throws IOException { write(org.restlet.engine.io.NioUtils.getStream(writableChannel)); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/Representation.java0000664000175000017500000006032211757206346030171 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.util.Date; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.Disposition; import org.restlet.data.MediaType; import org.restlet.data.Range; import org.restlet.data.Tag; import org.restlet.engine.io.BioUtils; import org.restlet.engine.util.DateUtils; /** * Current or intended state of a resource. The content of a representation can * be retrieved several times if there is a stable and accessible source, like a * local file or a string. When the representation is obtained via a temporary * source like a network socket, its content can only be retrieved once. The * "transient" and "available" properties are available to help you figure out * those aspects at runtime.
    *
    * For performance purpose, it is essential that a minimal overhead occurs upon * initialization. The main overhead must only occur during invocation of * content processing methods (write, getStream, getChannel and toString).
    *
    * "REST components perform actions on a resource by using a representation to * capture the current or intended state of that resource and transferring that * representation between components. A representation is a sequence of bytes, * plus representation metadata to describe those bytes. Other commonly used but * less precise names for a representation include: document, file, and HTTP * message entity, instance, or variant." Roy T. Fielding * * @see Source dissertation * @author Jerome Louvel */ public abstract class Representation extends RepresentationInfo { /** * Indicates that the size of the representation can't be known in advance. */ public static final long UNKNOWN_SIZE = -1L; /** * Returns a new empty representation with no content. * * @return A new empty representation. * @deprecated Use {@link EmptyRepresentation} instead. */ @Deprecated public static Representation createEmpty() { return new EmptyRepresentation(); } /** Indicates if the representation's content is potentially available. */ private volatile boolean available; /** * The representation digest if any. */ private volatile org.restlet.data.Digest digest; /** The disposition characteristics of the representation. */ private volatile Disposition disposition; /** The expiration date. */ private volatile Date expirationDate; /** Indicates if the representation's content is transient. */ private volatile boolean isTransient; /** * Indicates where in the full content the partial content available should * be applied. */ private volatile Range range; /** * The expected size. Dynamic representations can have any size, but * sometimes we can know in advance the expected size. If this expected size * is specified by the user, it has a higher priority than any size that can * be guessed by the representation (like a file size). */ private volatile long size; /** * Default constructor. */ public Representation() { this(null); } /** * Constructor. * * @param mediaType * The media type. */ public Representation(MediaType mediaType) { super(mediaType); this.available = true; this.disposition = null; this.isTransient = false; this.size = UNKNOWN_SIZE; this.expirationDate = null; this.digest = null; this.range = null; } /** * Constructor. * * @param mediaType * The media type. * @param modificationDate * The modification date. */ public Representation(MediaType mediaType, Date modificationDate) { this(mediaType, modificationDate, null); } /** * Constructor. * * @param mediaType * The media type. * @param modificationDate * The modification date. * @param tag * The tag. */ public Representation(MediaType mediaType, Date modificationDate, Tag tag) { super(mediaType, modificationDate, tag); } /** * Constructor. * * @param mediaType * The media type. * @param tag * The tag. */ public Representation(MediaType mediaType, Tag tag) { this(mediaType, null, tag); } /** * Constructor from a variant. * * @param variant * The variant to copy. * @param modificationDate * The modification date. */ public Representation(Variant variant, Date modificationDate) { this(variant, modificationDate, null); } /** * Constructor from a variant. * * @param variant * The variant to copy. * @param modificationDate * The modification date. * @param tag * The tag. */ public Representation(Variant variant, Date modificationDate, Tag tag) { setCharacterSet(variant.getCharacterSet()); setEncodings(variant.getEncodings()); setLocationRef(variant.getLocationRef()); setLanguages(variant.getLanguages()); setMediaType(variant.getMediaType()); setModificationDate(modificationDate); setTag(tag); } /** * Constructor from a variant. * * @param variant * The variant to copy. * @param tag * The tag. */ public Representation(Variant variant, Tag tag) { this(variant, null, tag); } /** * Check that the digest computed from the representation content and the * digest declared by the representation are the same.
    * Since this method relies on the {@link #computeDigest(String)} method, * and since this method reads entirely the representation's stream, user * must take care of the content of the representation in case the latter is * transient. * * {@link #isTransient} * * @return True if both digests are not null and equals. * @deprecated Use a {@link DigesterRepresentation} instead. */ @Deprecated public boolean checkDigest() { return (getDigest() != null && checkDigest(getDigest().getAlgorithm())); } /** * Check that the digest computed from the representation content and the * digest declared by the representation are the same. It also first checks * that the algorithms are the same.
    * Since this method relies on the {@link #computeDigest(String)} method, * and since this method reads entirely the representation's stream, user * must take care of the content of the representation in case the latter is * transient. * * {@link #isTransient} * * @param algorithm * The algorithm used to compute the digest to compare with. See * constant values in {@link org.restlet.data.Digest}. * @return True if both digests are not null and equals. * @deprecated Use a {@link DigesterRepresentation} instead. */ @Deprecated public boolean checkDigest(String algorithm) { org.restlet.data.Digest digest = getDigest(); if (digest != null) { if (algorithm.equals(digest.getAlgorithm())) { return digest.equals(computeDigest(algorithm)); } } return false; } /** * Compute the representation digest according to the given algorithm.
    * Since this method reads entirely the representation's stream, user must * take care of the content of the representation in case the latter is * transient. * * {@link #isTransient} * * @param algorithm * The algorithm used to compute the digest. See constant values * in {@link org.restlet.data.Digest}. * @return The computed digest or null if the digest cannot be computed. * @deprecated Use a {@link DigesterRepresentation} instead. */ @Deprecated public org.restlet.data.Digest computeDigest(String algorithm) { org.restlet.data.Digest result = null; if (isAvailable()) { try { java.security.MessageDigest md = java.security.MessageDigest .getInstance(algorithm); java.security.DigestInputStream dis = new java.security.DigestInputStream( getStream(), md); org.restlet.engine.io.BioUtils.exhaust(dis); result = new org.restlet.data.Digest(algorithm, md.digest()); } catch (java.security.NoSuchAlgorithmException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to check the digest of the representation.", e); } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to check the digest of the representation.", e); } } return result; } /** * Exhaust the content of the representation by reading it and silently * discarding anything read. By default, it relies on {@link #getStream()} * and closes the retrieved stream in the end. * * @return The number of bytes consumed or -1 if unknown. */ public long exhaust() throws IOException { long result = -1L; if (isAvailable()) { InputStream is = getStream(); result = BioUtils.exhaust(is); is.close(); } return result; } /** * Returns the size effectively available. This returns the same value as * {@link #getSize()} if no range is defined, otherwise it returns the size * of the range using {@link Range#getSize()}. * * @return The available size. */ public long getAvailableSize() { return BioUtils.getAvailableSize(this); } /** * Returns a channel with the representation's content.
    * If it is supported by a file, a read-only instance of FileChannel is * returned.
    * This method is ensured to return a fresh channel for each invocation * unless it is a transient representation, in which case null is returned. * * @return A channel with the representation's content. * @throws IOException */ public abstract java.nio.channels.ReadableByteChannel getChannel() throws IOException; /** * Returns the representation digest if any.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-MD5" header. * * @return The representation digest or null. */ public org.restlet.data.Digest getDigest() { return this.digest; } /** * Returns the disposition characteristics of the representation. * * @return The disposition characteristics of the representation. */ public Disposition getDisposition() { return disposition; } /** * Returns the suggested download file name for this representation. This is * mainly used to suggest to the client a local name for a downloaded * representation.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Disposition" header with this value: * "inline; filename=". * * @return The suggested file name for this representation. * @deprecated Use the "disposition" attribute instead. */ @Deprecated public String getDownloadName() { if (getDisposition() != null) { return getDisposition().getFilename(); } return null; } /** * Returns the future date when this representation expire. If this * information is not known, returns null.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Expires" header. * * @return The expiration date. */ public Date getExpirationDate() { return this.expirationDate; } /** * Returns the range where in the full content the partial content available * should be applied.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Range" header. * * @return The content range or null if the full content is available. */ public Range getRange() { return this.range; } /** * Returns a characters reader with the representation's content. This * method is ensured to return a fresh reader for each invocation unless it * is a transient representation, in which case null is returned. If the * representation has no character set defined, the system's default one * will be used. * * @return A reader with the representation's content. * @throws IOException */ public abstract Reader getReader() throws IOException; /** * Returns the size in bytes if known, UNKNOWN_SIZE (-1) otherwise.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Length" header. * * @return The size in bytes if known, UNKNOWN_SIZE (-1) otherwise. */ public long getSize() { return this.size; } /** * Returns a stream with the representation's content. This method is * ensured to return a fresh stream for each invocation unless it is a * transient representation, in which case null is returned. * * @return A stream with the representation's content. * @throws IOException */ public abstract InputStream getStream() throws IOException; /** * Converts the representation to a string value. Be careful when using this * method as the conversion of large content to a string fully stored in * memory can result in OutOfMemoryErrors being thrown. * * @return The representation as a string value. */ public String getText() throws IOException { String result = null; if (isAvailable()) { if (getSize() == 0) { result = ""; } else { java.io.StringWriter sw = new java.io.StringWriter(); write(sw); sw.flush(); result = sw.toString(); } } return result; } /** * Indicates if some fresh content is potentially available, without having * to actually call one of the content manipulation method like getStream() * that would actually consume it. Note that when the size of a * representation is 0 is a not considered available. However, sometimes the * size isn't known until a read attempt is made, so availability doesn't * guarantee a non empty content.
    *
    * This is especially useful for transient representation whose content can * only be accessed once and also when the size of the representation is not * known in advance. * * @return True if some fresh content is available. */ public boolean isAvailable() { return this.available && (getSize() != 0); } /** * Indicates if the representation is downloadable which means that it can * be obtained via a download dialog box. * * @return True if the representation's content is downloadable. * @deprecated Use the "disposition" attribute instead. */ @Deprecated public boolean isDownloadable() { if (getDisposition() != null) { return !(Disposition.TYPE_INLINE.equalsIgnoreCase(getDisposition() .getType())); } return false; } /** * Indicates if the representation's content is transient, which means that * it can be obtained only once. This is often the case with representations * transmitted via network sockets for example. In such case, if you need to * read the content several times, you need to cache it first, for example * into memory or into a file. * * @return True if the representation's content is transient. */ public boolean isTransient() { return this.isTransient; } /** * Releases the representation and all associated objects like streams, * channels or files which are used to produce its content, transient or * not. This method must be systematically called when the representation is * no longer intended to be used. The framework automatically calls back * this method via its connectors on the server-side when sending responses * with an entity and on the client-side when sending a request with an * entity. By default, it calls the {@link #setAvailable(boolean)} method * with "false" as a value.
    *
    * Note that for transient socket-bound representations, calling this method * after consuming the whole content shouldn't prevent the reuse of * underlying socket via persistent connections for example. However, if the * content hasn't been read, or has been partially read, the impact should * be to discard the remaining content and to close the underlying * connections.
    *
    * Therefore, if you are not interested in the content, or in the remaining * content, you should first call the {@link #exhaust()} method or if this * could be too costly, you should instead explicitly abort the parent * request and the underlying connections using the {@link Request#abort()} * method or a shortcut one like {@link ServerResource#abort()} or * {@link Response#abort()}. */ public void release() { setAvailable(false); } /** * Indicates if some fresh content is available. * * @param available * True if some fresh content is available. */ public void setAvailable(boolean available) { this.available = available; } /** * Sets the representation digest.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-MD5" header. * * @param digest * The representation digest. */ public void setDigest(org.restlet.data.Digest digest) { this.digest = digest; } /** * Sets the disposition characteristics of the representation. * * @param disposition * The disposition characteristics of the representation. */ public void setDisposition(Disposition disposition) { this.disposition = disposition; } /** * Indicates if the representation is downloadable which means that it can * be obtained via a download dialog box. * * @param downloadable * True if the representation's content is downloadable. * @deprecated Use the "disposition" attribute instead. */ @Deprecated public void setDownloadable(boolean downloadable) { if (getDisposition() == null) { this.disposition = new Disposition(); } this.disposition.setType((downloadable ? Disposition.TYPE_ATTACHMENT : Disposition.TYPE_NONE)); } /** * Set the suggested download file name for this representation.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Disposition" header with this value: * "inline; filename=". * * @param fileName * The suggested file name. * @deprecated Use the "disposition" attribute instead. */ @Deprecated public void setDownloadName(String fileName) { if (getDisposition() == null) { this.disposition = new Disposition(); } getDisposition().setFilename(fileName); } /** * Sets the future date when this representation expire. If this information * is not known, pass null.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Expires" header. * * @param expirationDate * The expiration date. */ public void setExpirationDate(Date expirationDate) { this.expirationDate = DateUtils.unmodifiable(expirationDate); } /** * Sets the range where in the full content the partial content available * should be applied.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Range" header. * * @param range * The content range. */ public void setRange(Range range) { this.range = range; } /** * Sets the expected size in bytes if known, -1 otherwise.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Content-Length" header. * * @param expectedSize * The expected size in bytes if known, -1 otherwise. */ public void setSize(long expectedSize) { this.size = expectedSize; } /** * Indicates if the representation's content is transient. * * @param isTransient * True if the representation's content is transient. */ public void setTransient(boolean isTransient) { this.isTransient = isTransient; } /** * Writes the representation to a characters writer. This method is ensured * to write the full content for each invocation unless it is a transient * representation, in which case an exception is thrown.
    *
    * Note that the class implementing this method shouldn't flush or close the * given {@link java.io.Writer} after writing to it as this will be handled * by the Restlet connectors automatically. * * @param writer * The characters writer. * @throws IOException */ public abstract void write(java.io.Writer writer) throws IOException; /** * Writes the representation to a byte channel. This method is ensured to * write the full content for each invocation unless it is a transient * representation, in which case an exception is thrown. * * @param writableChannel * A writable byte channel. * @throws IOException */ public abstract void write( java.nio.channels.WritableByteChannel writableChannel) throws IOException; /** * Writes the representation to a byte stream. This method is ensured to * write the full content for each invocation unless it is a transient * representation, in which case an exception is thrown.
    *
    * Note that the class implementing this method shouldn't flush or close the * given {@link OutputStream} after writing to it as this will be handled by * the Restlet connectors automatically. * * @param outputStream * The output stream. * @throws IOException */ public abstract void write(OutputStream outputStream) throws IOException; } restlet-2.0.14/org.restlet/src/org/restlet/representation/DigesterRepresentation.java0000664000175000017500000002024511757206346031660 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.security.DigestInputStream; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.restlet.data.Digest; import org.restlet.engine.io.BioUtils; import org.restlet.engine.io.NioUtils; import org.restlet.util.WrapperRepresentation; /** * Representation capable of computing a digest. It wraps another representation * and allows to get the computed digest of the wrapped entity after reading or * writing operations. The final digest value is guaranteed to be correct only * after the wrapped representation has been entirely exhausted (that is to say * read or written).
    *
    * This wrapper allows to get the computed digest at the same time the * representation is read or written. It does not need two separate operations * which may require specific attention for transient representations. * * @see Representation#isTransient(). * * @author Jerome Louvel */ public class DigesterRepresentation extends WrapperRepresentation { /** The digest algorithm. */ private final String algorithm; /** The computed digest value. */ private volatile MessageDigest computedDigest; /** * Constructor.
    * By default, the instance relies on the {@link Digest#ALGORITHM_MD5} * digest algorithm. * * @param wrappedRepresentation * The wrapped representation. * @throws NoSuchAlgorithmException */ public DigesterRepresentation(Representation wrappedRepresentation) throws NoSuchAlgorithmException { this(wrappedRepresentation, Digest.ALGORITHM_MD5); } /** * Constructor.
    * * @param wrappedRepresentation * The wrapped representation. * @param algorithm * The digest algorithm. * @throws NoSuchAlgorithmException */ public DigesterRepresentation(Representation wrappedRepresentation, String algorithm) throws NoSuchAlgorithmException { super(wrappedRepresentation); this.algorithm = algorithm; this.computedDigest = MessageDigest.getInstance(algorithm); } /** * Check that the digest computed from the wrapped representation content * and the digest declared by the wrapped representation are the same. User * must be aware that the computed value is accurate only after a complete * reading or writing operation. */ @Override public boolean checkDigest() { Digest digest = getDigest(); return (digest != null && digest.equals(getComputedDigest())); } /** * {@inheritDoc}
    * If case the given algorithm is the same than the one provided at * instantiation, the check operation is made with the current stored * computed value and does not require to exhaust entirely the * representation's stream. */ @SuppressWarnings("deprecation") @Override public boolean checkDigest(String algorithm) { if (this.algorithm != null && this.algorithm.equals(algorithm)) { return checkDigest(); } return super.checkDigest(algorithm); } /** * Compute the representation digest according to MD5 algorithm.
    * If case this algorithm is the same than the one provided at * instantiation, the computation operation is made with the current stored * computed value and does not require to exhaust entirely the * representation's stream. */ public Digest computeDigest() { return computeDigest(Digest.ALGORITHM_MD5); } /** * {@inheritDoc}
    * If case the given algorithm is the same than the one provided at * instantiation, the computation operation is made with the current stored * computed value and does not require to exhaust entirely the * representation's stream. */ @SuppressWarnings("deprecation") @Override public Digest computeDigest(String algorithm) { if (this.algorithm != null && this.algorithm.equals(algorithm)) { return getComputedDigest(); } return super.computeDigest(algorithm); } /** * Exhauts the content of the representation by reading it and silently * discarding anything read. * * @return The number of bytes consumed or -1 if unknown. */ public long exhaust() throws IOException { long result = -1L; if (isAvailable()) { result = BioUtils.exhaust(getStream()); } return result; } @Override public ReadableByteChannel getChannel() throws IOException { return NioUtils.getChannel(getStream()); } /** * Returns the current computed digest value of the representation. User * must be aware that, if the representation has not been entirely read or * written, the computed digest value may not be accurate. * * @return The current computed digest value. */ public Digest getComputedDigest() { return new Digest(this.algorithm, computedDigest.digest()); } @Override public Reader getReader() throws IOException { return BioUtils.getReader(getStream(), getCharacterSet()); } /** * {@inheritDoc}
    * * The stream of the underlying representation is wrapped with a new * instance of the {@link DigestInputStream} class, which allows to compute * progressively the digest value. */ @Override public InputStream getStream() throws IOException { return new DigestInputStream(getWrappedRepresentation().getStream(), this.computedDigest); } @Override public String getText() throws IOException { String result = null; if (isAvailable()) { if (getSize() == 0) { result = ""; } else { java.io.StringWriter sw = new java.io.StringWriter(); write(sw); result = sw.toString(); } } return result; } /** * {@inheritDoc}
    * * The output stream is wrapped with a new instance of the * {@link DigestOutputStream} class, which allows to compute progressively * the digest value. */ @Override public void write(OutputStream outputStream) throws IOException { OutputStream dos = new DigestOutputStream(outputStream, this.computedDigest); getWrappedRepresentation().write(dos); dos.flush(); } @Override public void write(WritableByteChannel writableChannel) throws IOException { write(NioUtils.getStream(writableChannel)); } @Override public void write(Writer writer) throws IOException { write(BioUtils.getStream(writer)); } } restlet-2.0.14/org.restlet/src/org/restlet/representation/WritableRepresentation.java0000664000175000017500000000503611757206346031664 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import org.restlet.data.MediaType; import org.restlet.engine.io.NioUtils; /** * Representation based on a writable NIO byte channel. This class is a good * basis to write your own representations, especially for the dynamic and large * ones.
    *
    * For this you just need to create a subclass and override the abstract * Representation.write(WritableByteChannel) method. This method will later be * called back by the connectors when the actual representation's content is * needed. * * @author Jerome Louvel */ public abstract class WritableRepresentation extends ChannelRepresentation { /** * Constructor. * * @param mediaType * The representation's media type. */ public WritableRepresentation(MediaType mediaType) { super(mediaType); } @Override public ReadableByteChannel getChannel() throws IOException { return NioUtils.getChannel(this); } /** * Calls parent's implementation. */ @Override public void release() { super.release(); } @Override public abstract void write(WritableByteChannel writableChannel) throws IOException; } restlet-2.0.14/org.restlet/src/org/restlet/representation/WriterRepresentation.java0000664000175000017500000000641311757206350031362 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.representation; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.engine.io.BioUtils; /** * Representation based on a BIO characters writer. This class is a good basis * to write your own representations, especially for the dynamic and large ones.
    *
    * For this you just need to create a subclass and override the abstract * Representation.write(Writer) method. This method will later be called back by * the connectors when the actual representation's content is needed. * * @author Jerome Louvel */ public abstract class WriterRepresentation extends CharacterRepresentation { /** * Constructor. * * @param mediaType * The representation's mediaType. */ public WriterRepresentation(MediaType mediaType) { super(mediaType); } /** * Constructor. * * @param mediaType * The representation's mediaType. * @param expectedSize * The expected writer size in bytes. */ public WriterRepresentation(MediaType mediaType, long expectedSize) { super(mediaType); setSize(expectedSize); } @Override public Reader getReader() throws IOException { return BioUtils.getReader(this); } /** * Calls parent's implementation. */ @Override public void release() { super.release(); } @Override public void write(OutputStream outputStream) throws IOException { Writer writer = null; if (getCharacterSet() != null) { writer = new OutputStreamWriter(outputStream, getCharacterSet() .getName()); } else { // Use the default HTTP character set writer = new OutputStreamWriter(outputStream, CharacterSet.ISO_8859_1.getName()); } write(writer); writer.flush(); } } restlet-2.0.14/org.restlet/src/org/restlet/package.html0000664000175000017500000000067011757206350023536 0ustar jamespagejamespage Core classes of the API.

    @since Restlet 1.0 @see REST dissertation by Roy T. Fielding @see User Guide - Restlet API @see User Guide - Base package restlet-2.0.14/org.restlet/src/org/restlet/Component.xsd0000664000175000017500000001520411757206350023736 0ustar jamespagejamespage restlet-2.0.14/org.restlet/src/org/restlet/Connector.java0000664000175000017500000001044111757206346024054 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.Protocol; /** * Restlet enabling communication between Components. "A connector is an * abstract mechanism that mediates communication, coordination, or cooperation * among components. Connectors enable communication between components by * transferring data elements from one interface to another without changing the * data." Roy T. Fielding
    *
    * "Encapsulate the activities of accessing resources and transferring resource * representations. The connectors present an abstract interface for component * communication, enhancing simplicity by providing a clean separation of * concerns and hiding the underlying implementation of resources and * communication mechanisms" Roy T. Fielding
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see Source * dissertation * @see Source * dissertation * @author Jerome Louvel */ public abstract class Connector extends Restlet { /** The list of protocols simultaneously supported. */ private final List protocols; /** * Constructor. * * @param context * The context. */ public Connector(Context context) { this(context, null); } /** * Constructor. * * @param context * The context. * @param protocols * The supported protocols. */ public Connector(Context context, List protocols) { super(context); if (protocols == null) { this.protocols = new CopyOnWriteArrayList(); } else { this.protocols = new CopyOnWriteArrayList(protocols); } } /** * Returns the modifiable list of protocols simultaneously supported. * * @return The protocols simultaneously supported. */ public List getProtocols() { return this.protocols; } /** * Indicates the underlying connector helper is available. * * @return True if the underlying connector helper is available. */ public abstract boolean isAvailable(); /** * Sets the list of protocols simultaneously supported. This method clears * the current list and adds all entries in the parameter list. * * @param protocols * A list of protocols. */ public void setProtocols(List protocols) { synchronized (getProtocols()) { if (protocols != getProtocols()) { getProtocols().clear(); if (protocols != null) { getProtocols().addAll(protocols); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/service/0000775000175000017500000000000011757206350022712 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/service/StatusService.java0000664000175000017500000002017011757206346026366 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.ResourceException; import org.restlet.resource.UniformResource; /** * Service to handle error statuses. If an exception is thrown within your * application or Restlet code, it will be intercepted by this service if it is * enabled.
    *
    * When an exception or an error is caught, the * {@link #getStatus(Throwable, Request, Response)} method is first invoked to * obtain the status that you want to set on the response. If this method isn't * overridden or returns null, the {@link Status#SERVER_ERROR_INTERNAL} constant * will be set by default.
    *
    * Also, when the status of a response returned is an error status (see * {@link Status#isError()}, the * {@link #getRepresentation(Status, Request, Response)} method is then invoked * to give your service a chance to override the default error page.
    *
    * If you want to customize the default behavior, you need to create a subclass * of StatusService that overrides some or all of the methods mentioned above. * Then, just create a instance of your class and set it on your Component or * Application via the setStatusService() methods. * * @see User * Guide * @author Jerome Louvel */ public class StatusService extends Service { /** The email address to contact in case of error. */ private volatile String contactEmail; /** The home URI to propose in case of error. */ private volatile Reference homeRef; /** True if an existing entity should be overwritten. */ private volatile boolean overwriting; /** * Constructor. */ public StatusService() { this(true); } /** * Constructor. * * @param enabled * True if the service has been enabled. */ public StatusService(boolean enabled) { super(enabled); this.contactEmail = null; this.homeRef = new Reference("/"); this.overwriting = false; } @Override public org.restlet.routing.Filter createInboundFilter(Context context) { return new org.restlet.engine.application.StatusFilter(context, this); } /** * Returns the email address to contact in case of error. This is typically * used when creating the status representations. * * @return The email address to contact in case of error. */ public String getContactEmail() { return this.contactEmail; } /** * Returns the home URI to propose in case of error. * * @return The home URI to propose in case of error. */ public Reference getHomeRef() { return this.homeRef; } /** * 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. */ public Representation getRepresentation(Status status, Request request, Response response) { return null; } /** * 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. */ public Status getStatus(Throwable throwable, Request request, Response response) { Status result = null; if (throwable instanceof ResourceException) { ResourceException re = (ResourceException) throwable; result = re.getStatus(); } else { result = new Status(Status.SERVER_ERROR_INTERNAL, throwable); } 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. */ public Status getStatus(Throwable throwable, UniformResource resource) { return getStatus(throwable, (resource == null) ? null : resource.getRequest(), (resource == null) ? null : resource.getResponse()); } /** * Indicates if an existing entity should be overwritten. False by default. * * @return True if an existing entity should be overwritten. * @deprecated Use {@link #isOverwriting()} instead. */ @Deprecated public boolean isOverwrite() { return this.overwriting; } /** * Indicates if an existing entity should be overwritten. False by default. * * @return True if an existing entity should be overwritten. */ public boolean isOverwriting() { return isOverwrite(); } /** * Sets the email address to contact in case of error. This is typically * used when creating the status representations. * * @param contactEmail * The email address to contact in case of error. */ public void setContactEmail(String contactEmail) { this.contactEmail = contactEmail; } /** * Sets the home URI to propose in case of error. * * @param homeRef * The home URI to propose in case of error. */ public void setHomeRef(Reference homeRef) { this.homeRef = homeRef; } /** * Indicates if an existing entity should be overwritten. * * @param overwriting * True if an existing entity should be overwritten. * @deprecated Use {@link #setOverwriting(boolean)} instead. */ @Deprecated public void setOverwrite(boolean overwriting) { this.overwriting = overwriting; } /** * Indicates if an existing entity should be overwritten. * * @param overwriting * True if an existing entity should be overwritten. */ public void setOverwriting(boolean overwriting) { setOverwrite(overwriting); } } restlet-2.0.14/org.restlet/src/org/restlet/service/RangeService.java0000664000175000017500000000421111757206346026135 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import org.restlet.Context; import org.restlet.engine.application.RangeFilter; import org.restlet.routing.Filter; /** * Application service automatically exposes ranges of response entities. This * allows resources to not care of requested ranges and return full * representations that will then be transparently wrapped in partial * representations by this service, allowing the client to benefit from partial * downloads. * * @author Jerome Louvel */ public class RangeService extends Service { /** * Constructor. */ public RangeService() { super(); } /** * Constructor. * * @param enabled * True if the service has been enabled. */ public RangeService(boolean enabled) { super(enabled); } @Override public Filter createInboundFilter(Context context) { return new RangeFilter(context); } } restlet-2.0.14/org.restlet/src/org/restlet/service/LogService.java0000664000175000017500000001670511757206346025635 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import java.util.logging.LogManager; import org.restlet.Context; import org.restlet.data.Reference; import org.restlet.engine.log.LogFilter; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.routing.Filter; /** * Service providing access logging service. The implementation is fully based * on the standard logging mechanism introduced in JDK 1.4.
    *
    * The default access log format follows the W3C Extended Log File Format * with the following fields used:
    *

      *
    1. Date (YYYY-MM-DD)
    2. *
    3. Time (HH:MM:SS)
    4. *
    5. Client address (IP)
    6. *
    7. Remote user identifier (see RFC 1413)
    8. *
    9. Server address (IP)
    10. *
    11. Server port
    12. *
    13. Method (GET|POST|...)
    14. *
    15. Resource reference path (including the leading slash)
    16. *
    17. Resource reference query (excluding the leading question mark)
    18. *
    19. Response status code
    20. *
    21. Number of bytes sent
    22. *
    23. Number of bytes received
    24. *
    25. Time to serve the request (in milliseconds)
    26. *
    27. Host reference
    28. *
    29. Client agent name
    30. *
    31. Referrer reference
    32. *
    *
    * If you use Analog to generate your log * reports, and if you use the default log format, then you can simply specify * this string as a value of the LOGFORMAT command: * (%Y-%m-%d\t%h:%n:%j\t%S\t%u\t%j\t%j\t%j\t%r\t%q\t%c\t%b\t%j\t%T\t%v\t%B\t%f)
    *
    * For custom access log format, see the syntax to use and the list of available * variable names in {@link org.restlet.routing.Template}.
    * * @see User * Guide - Access logging * @see java.util.logging * @author Jerome Louvel */ public class LogService extends Service { /** The access logger name. */ private volatile String loggerName; /** The log entry format. */ private volatile String logFormat; /** The URI reference of the log properties. */ private volatile Reference logPropertiesRef; /** Indicates if the identity check (as specified by RFC1413) is enabled. */ private volatile boolean identityCheck; /** * Constructor. */ public LogService() { this(true); } /** * Constructor. * * @param enabled * True if the service has been enabled. */ public LogService(boolean enabled) { super(enabled); this.loggerName = null; this.logFormat = null; this.logPropertiesRef = null; this.identityCheck = false; } @Override public Filter createInboundFilter(Context context) { return new LogFilter(context, this); } /** * Returns the format used. * * @return The format used, or null if the default one is used. * @see org.restlet.routing.Template for format syntax and variables. */ public String getLogFormat() { return this.logFormat; } /** * Returns the name of the JDK's logger to use when logging access calls. * The default name will follow this pattern: * "org.restlet.MyComponent.LogService", where "MyComponent" will correspond * to the simple class name of your component subclass or to the base * "Component" class. * * @return The name of the JDK's logger to use when logging access calls. */ public String getLoggerName() { return this.loggerName; } /** * Returns the URI reference of the log properties. * * @return The URI reference of the log properties. */ public Reference getLogPropertiesRef() { return logPropertiesRef; } /** * Indicates if the identity check (as specified by RFC1413) is enabled. * Default value is false. * * @return True if the identity check is enabled. */ public boolean isIdentityCheck() { return this.identityCheck; } /** * Indicates if the identity check (as specified by RFC1413) is enabled. * * @param identityCheck * True if the identity check is enabled. */ public void setIdentityCheck(boolean identityCheck) { this.identityCheck = identityCheck; } /** * Sets the format to use when logging calls. The default format matches the * one of IIS 6. * * @param format * The format to use when loggin calls. * @see org.restlet.routing.Template for format syntax and variables. */ public void setLogFormat(String format) { this.logFormat = format; } /** * Sets the name of the JDK's logger to use when logging access calls. * * @param name * The name of the JDK's logger to use when logging access calls. */ public void setLoggerName(String name) { this.loggerName = name; } /** * Sets the URI reference of the log properties. * * @param logPropertiesRef * The URI reference of the log properties. */ public void setLogPropertiesRef(Reference logPropertiesRef) { this.logPropertiesRef = logPropertiesRef; } /** * Sets the URI reference of the log properties. * * @param logPropertiesUri * The URI reference of the log properties. */ public void setLogPropertiesRef(String logPropertiesUri) { setLogPropertiesRef(new Reference(logPropertiesUri)); } /** * Starts the log service by attempting to read the log properties if the * {@link #getLogPropertiesRef()} returns a non null URI reference. */ @Override public synchronized void start() throws Exception { super.start(); if (getLogPropertiesRef() != null) { Representation logProperties = new ClientResource(getContext(), getLogPropertiesRef()).get(); if (logProperties != null) { LogManager.getLogManager().readConfiguration( logProperties.getStream()); } } } } restlet-2.0.14/org.restlet/src/org/restlet/service/TunnelService.java0000664000175000017500000004547511757206346026367 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.ClientInfo; import org.restlet.engine.application.TunnelFilter; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.routing.Filter; /** * Application service tunneling request method or client preferences. The * tunneling can use query parameters, file-like extensions and specific * headers. This is particularly useful for browser-based applications that * can't fully control the HTTP requests sent.
    *
    * Here is the list of the default parameter names supported: * *

    *

    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    PropertyDefault nameValue typeDescription
    methodParametermethodSee values in {@link org.restlet.data.Method}For POST requests, let you specify the actual method to use (DELETE, PUT, * MOVE, etc.). For GET requests, let you specify OPTIONS as the actual method * to use.
    characterSetParametercharsetUse extension names defined in {@link MetadataService} or the full * character set nameFor GET requests, replaces the accepted character set by the given value. *
    encodingParameterencodingUse extension names defined in {@link MetadataService} or the full * encoding nameFor GET requests, replaces the accepted encoding by the given value.
    languageParameterlanguageUse extension names defined in {@link MetadataService} or the full * language nameFor GET requests, replaces the accepted language by the given value.
    mediaTypeParametermediaUse extension names defined in {@link MetadataService} or the full media * type nameFor GET requests, replaces the accepted media type set by the given * value.
    methodHeaderX-HTTP-Method-OverrideName of non-standard header. It is a good practice to prefix it with * "X-".For POST requests, let you specify the actual method to use (DELETE, PUT, * MOVE, etc.).
    *
    * The client preferences can also be updated according to the user agent * properties (its name, version, operating system, or other) available via the * {@link ClientInfo#getAgentAttributes()} method. Check the * {@link #isUserAgentTunnel()} method.
    *
    * The list of new media type preferences is loaded from a property file called * "accept.properties" located in the classpath in the sub directory * "org/restlet/service". This property file is composed of blocks of * properties. One "block" of properties starts either with the beginning of the * properties file or with the end of the previous block. One block ends with * the "acceptNew" property which contains the value of the new accept header. * Here is a sample block.
    * *
     * agentName: firefox
     * acceptOld: 
     * acceptNew: application/xhtml+xml,text/html,text/xml;q=0.9,application/xml;q=0.9,text/plain;q=0.8,image/png,\*\/\*;q=0.5
     * 
    * * Each declared property is a condition that must be filled in order to update * the client preferences. For example "agentName: firefox" expresses the fact * this block concerns only "firefox" clients.
    *
    * The "acceptOld" property allows to check the value of the current "Accept" * header. If it equals to the value of the "acceptOld" property or if the * "acceptOld" property is empty, then the preferences will be updated. This can * be useful for AJAX clients which looks like their browser (same agentName, * agentVersion, etc.) but can provide their own "Accept" header. * * @author Jerome Louvel */ public class TunnelService extends Service { /** The name of the parameter containing the accepted character set. */ private volatile String characterSetParameter; /** The name of the parameter containing the accepted encoding. */ private volatile String encodingParameter; /** * Indicates if the client preferences can be tunneled via file-like * extensions. */ private volatile boolean extensionsTunnel; /** Indicates if the method can be tunneled via the header. */ private volatile boolean headersTunnel; /** The name of the parameter containing the accepted language. */ private volatile String languageParameter; /** The name of the parameter containing the accepted media type. */ private volatile String mediaTypeParameter; /** The name of the header that contains the method name. */ private volatile String methodHeader; /** The name of the parameter containing the method name. */ private volatile String methodParameter; /** Indicates if the method name can be tunneled. */ private volatile boolean methodTunnel; /** Indicates if the client preferences can be tunneled. */ private volatile boolean preferencesTunnel; /** * Indicates if the method and client preferences can be tunneled via query * parameters. */ private volatile boolean queryTunnel; /** * Indicates if the client preferences can be tunneled via the user agent * string. */ private volatile boolean userAgentTunnel; /** * Constructor that enables the query tunnel and disables the extensions and * user agent tunnels. * * @param methodTunnel * Indicates if the method name can be tunneled. * @param preferencesTunnel * Indicates if the client preferences can be tunneled by query * parameters or file-like extensions or user agent string. */ public TunnelService(boolean methodTunnel, boolean preferencesTunnel) { this(true, methodTunnel, preferencesTunnel); } /** * Constructor that enables the query tunnel and disables the extensions and * user agent tunnels. * * @param enabled * True if the service has been enabled. * @param methodTunnel * Indicates if the method name can be tunneled. * @param preferencesTunnel * Indicates if the client preferences can be tunneled by query * parameters or file-like extensions or user agent string. */ public TunnelService(boolean enabled, boolean methodTunnel, boolean preferencesTunnel) { this(enabled, methodTunnel, preferencesTunnel, true, false); } /** * Constructor that disables the user agent tunnel. * * @param enabled * True if the service has been enabled. * @param methodTunnel * Indicates if the method can be tunneled using a query * parameter. * @param preferencesTunnel * Indicates if the client preferences can be tunneled using * query parameters or file-like extensions or user agent string. * @param queryTunnel * Indicates if tunneling can use query parameters. * @param extensionsTunnel * Indicates if tunneling can use file-like extensions. */ public TunnelService(boolean enabled, boolean methodTunnel, boolean preferencesTunnel, boolean queryTunnel, boolean extensionsTunnel) { this(enabled, methodTunnel, preferencesTunnel, queryTunnel, extensionsTunnel, false); } /** * Constructor that enables the header tunneling. * * @param enabled * True if the service has been enabled. * @param methodTunnel * Indicates if the method can be tunneled using a query * parameter. * @param preferencesTunnel * Indicates if the client preferences can be tunneled using * query parameters or file-like extensions or user agent string. * @param queryTunnel * Indicates if tunneling can use query parameters. * @param extensionsTunnel * Indicates if tunneling can use file-like extensions. * @param userAgentTunnel * Indicates if tunneling can use user agent string. */ public TunnelService(boolean enabled, boolean methodTunnel, boolean preferencesTunnel, boolean queryTunnel, boolean extensionsTunnel, boolean userAgentTunnel) { this(enabled, methodTunnel, preferencesTunnel, queryTunnel, extensionsTunnel, userAgentTunnel, true); } /** * Constructor. * * @param enabled * True if the service has been enabled. * @param methodTunnel * Indicates if the method can be tunneled using a query * parameter. * @param preferencesTunnel * Indicates if the client preferences can be tunneled using * query parameters or file-like extensions or user agent string. * @param queryTunnel * Indicates if tunneling can use query parameters. * @param extensionsTunnel * Indicates if tunneling can use file-like extensions. * @param userAgentTunnel * Indicates if tunneling can use user agent string. * @param headersTunnel * Indicates if method can be tunneled via a specific header. */ public TunnelService(boolean enabled, boolean methodTunnel, boolean preferencesTunnel, boolean queryTunnel, boolean extensionsTunnel, boolean userAgentTunnel, boolean headersTunnel) { super(enabled); this.extensionsTunnel = extensionsTunnel; this.methodTunnel = methodTunnel; this.preferencesTunnel = preferencesTunnel; this.queryTunnel = queryTunnel; this.userAgentTunnel = userAgentTunnel; this.headersTunnel = headersTunnel; this.characterSetParameter = "charset"; this.encodingParameter = "encoding"; this.languageParameter = "language"; this.mediaTypeParameter = "media"; this.methodParameter = "method"; this.methodHeader = HeaderConstants.HEADER_X_HTTP_METHOD_OVERRIDE; } /** * Indicates if the request from a given client can be tunneled. The default * implementation always return true. This could be customize to restrict * the usage of the tunnel service. * * @param client * The client to test. * @return True if the request from a given client can be tunneled. */ public boolean allowClient(ClientInfo client) { return true; } @Override public Filter createInboundFilter(Context context) { return new TunnelFilter(context); } /** * Returns the character set parameter name. * * @return The character set parameter name. */ public String getCharacterSetParameter() { return this.characterSetParameter; } /** * Returns the name of the parameter containing the accepted encoding. * * @return The name of the parameter containing the accepted encoding. */ public String getEncodingParameter() { return this.encodingParameter; } /** * Returns the name of the parameter containing the accepted language. * * @return The name of the parameter containing the accepted language. */ public String getLanguageParameter() { return this.languageParameter; } /** * Returns the name of the parameter containing the accepted media type. * * @return The name of the parameter containing the accepted media type. */ public String getMediaTypeParameter() { return this.mediaTypeParameter; } /** * Returns the name of the header containing the method name. * * @return the name of the header containing the method name. */ public String getMethodHeader() { return methodHeader; } /** * Returns the method parameter name. * * @return The method parameter name. */ public String getMethodParameter() { return this.methodParameter; } /** * Indicates if the client preferences can be tunneled via the extensions. * Returns false by default. * * @return True if the client preferences can be tunneled via the extensions * @see Request#getOriginalRef() */ public boolean isExtensionsTunnel() { return this.extensionsTunnel; } /** * Indicates if the method can be tunneled via the header. Returns true by * default. * * @return True if the method can be tunneled via the header. */ public boolean isHeadersTunnel() { return headersTunnel; } /** * Indicates if the method name can be tunneled. Returns true by default. * * @return True if the method name can be tunneled. */ public boolean isMethodTunnel() { return this.methodTunnel; } /** * Indicates if the client preferences can be tunneled via the query * parameters or file extensions. Returns true by default. * * @return True if the client preferences can be tunneled. */ public boolean isPreferencesTunnel() { return this.preferencesTunnel; } /** * Indicates if the method and client preferences can be tunneled via query * parameters or file extensions. Returns true by default. * * @return True if the method and client preferences can be tunneled. */ public boolean isQueryTunnel() { return this.queryTunnel; } /** * Indicates if the client preferences can be tunneled according to the user * agent. Returns false by default. * * @return True if the client preferences can be tunneled according to the * user agent. */ public boolean isUserAgentTunnel() { return this.userAgentTunnel; } /** * Sets the character set parameter name. * * @param parameterName * The character set parameter name. */ public void setCharacterSetParameter(String parameterName) { this.characterSetParameter = parameterName; } /** * Sets the name of the parameter containing the accepted encoding. * * @param parameterName * The name of the parameter containing the accepted encoding. */ public void setEncodingParameter(String parameterName) { this.encodingParameter = parameterName; } /** * Indicates if the client preferences can be tunneled via the extensions. * * @param extensionTunnel * True if the client preferences can be tunneled via the * extensions. * @see Request#getOriginalRef() */ public void setExtensionsTunnel(boolean extensionTunnel) { this.extensionsTunnel = extensionTunnel; } /** * Indicates if the method can be tunneled via the header. * * @param headersTunnel * True if the method can be tunneled via the header. */ public void setHeaderTunnel(boolean headersTunnel) { this.headersTunnel = headersTunnel; } /** * Sets the name of the parameter containing the accepted language. * * @param parameterName * The name of the parameter containing the accepted language. */ public void setLanguageParameter(String parameterName) { this.languageParameter = parameterName; } /** * Sets the name of the parameter containing the accepted media type. * * @param parameterName * The name of the parameter containing the accepted media type. */ public void setMediaTypeParameter(String parameterName) { this.mediaTypeParameter = parameterName; } /** * Sets the name of the header containing the method name. * * @param methodHeader * The name of the header containing the method name. */ public void setMethodHeader(String methodHeader) { this.methodHeader = methodHeader; } /** * Sets the method parameter name. * * @param parameterName * The method parameter name. */ public void setMethodParameter(String parameterName) { this.methodParameter = parameterName; } /** * Indicates if the method name can be tunneled. * * @param methodTunnel * True if the method name can be tunneled. */ public void setMethodTunnel(boolean methodTunnel) { this.methodTunnel = methodTunnel; } /** * Indicates if the client preferences can be tunneled via the query * parameters. * * @param preferencesTunnel * True if the client preferences can be tunneled via the query * parameters. */ public void setPreferencesTunnel(boolean preferencesTunnel) { this.preferencesTunnel = preferencesTunnel; } /** * Indicates if the method and client preferences can be tunneled via query * parameters. * * @param queryTunnel * True if the method and client preferences can be tunneled via * query parameters. */ public void setQueryTunnel(boolean queryTunnel) { this.queryTunnel = queryTunnel; } /** * Indicates if the client preferences can be tunneled according to the user * agent. * * @param userAgentTunnel * True if the client preferences can be tunneled according to * the user agent. */ public void setUserAgentTunnel(boolean userAgentTunnel) { this.userAgentTunnel = userAgentTunnel; } } restlet-2.0.14/org.restlet/src/org/restlet/service/Service.java0000664000175000017500000001055711757206346025172 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import org.restlet.Context; /** * Generic service associated to a component or an application. The life cycle * of a service is tightly related to the one of the associated component or * application.
    *
    * If you want to use a specific service, you can always disable it before it is * actually started via the {@link #setEnabled(boolean)} method. * * @author Jerome Louvel */ public abstract class Service { /** The context. */ private volatile Context context; /** Indicates if the service has been enabled. */ private volatile boolean enabled; /** Indicates if the service was started. */ private volatile boolean started; /** * Constructor. Enables the service by default. */ public Service() { this(true); } /** * Constructor. * * @param enabled * True if the service has been enabled. */ public Service(boolean enabled) { this.context = null; this.enabled = enabled; } /** * Create the filter that should be invoked for incoming calls. * * @param context * The current context. * @return The new filter or null. */ public org.restlet.routing.Filter createInboundFilter( org.restlet.Context context) { return null; } /** * Create the filter that should be invoked for outgoing calls. * * @param context * The current context. * @return The new filter or null. * @see Context#getClientDispatcher() */ public org.restlet.routing.Filter createOutboundFilter( org.restlet.Context context) { return null; } /** * Returns the context. * * @return The context. */ public Context getContext() { return this.context; } /** * Indicates if the service should be enabled. * * @return True if the service should be enabled. */ public boolean isEnabled() { return this.enabled; } /** * Indicates if the service is started. * * @return True if the service is started. */ public boolean isStarted() { return this.started; } /** * Indicates if the service is stopped. * * @return True if the service is stopped. */ public boolean isStopped() { return !this.started; } /** * Sets the context. * * @param context * The context. */ public void setContext(Context context) { this.context = context; } /** * Indicates if the service should be enabled. * * @param enabled * True if the service should be enabled. */ public synchronized void setEnabled(boolean enabled) { this.enabled = enabled; } /** Starts the Restlet. */ public synchronized void start() throws Exception { if (isEnabled()) { this.started = true; } } /** Stops the Restlet. */ public synchronized void stop() throws Exception { if (isEnabled()) { this.started = false; } } } restlet-2.0.14/org.restlet/src/org/restlet/service/package.html0000664000175000017500000000035211757206350025173 0ustar jamespagejamespage Services used by applications and components.

    @since Restlet 1.0 @see User Guide - Service package restlet-2.0.14/org.restlet/src/org/restlet/service/TaskService.java0000664000175000017500000003734211757206350026011 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.restlet.Application; import org.restlet.Context; import org.restlet.Response; import org.restlet.engine.Engine; import org.restlet.routing.VirtualHost; /** * Application service capable of running tasks asynchronously. The service * instance returned will not invoke the runnable task in the current thread.
    *
    * In addition to allowing pooling, this method will ensure that the threads * executing the tasks will have the thread local variables copied from the * calling thread. This will ensure that call to static methods like * {@link Application#getCurrent()} still work.
    *
    * Also, note that this executor service will be shared among all Restlets and * Resources that are part of your context. In general this context corresponds * to a parent Application's context. If you want to have your own service * instance, you can use the {@link #wrap(ExecutorService)} method to ensure * that thread local variables are correctly set. * * @author Jerome Louvel * @author Doug Lea (docs of ExecutorService in public domain) * @author Tim Peierls */ public class TaskService extends Service implements ExecutorService { /** * The default thread factory * * @author Jerome Louvel * @author Tim Peierls */ private static class RestletThreadFactory implements ThreadFactory { final ThreadFactory factory = Executors.defaultThreadFactory(); public Thread newThread(Runnable runnable) { Thread t = factory.newThread(runnable); // Default factory is documented as producing names of the // form "pool-N-thread-M". t.setName(t.getName().replaceFirst("pool", "restlet")); return t; } } /** * Wraps a JDK executor service to ensure that the threads executing the * tasks will have the thread local variables copied from the calling * thread. This will ensure that call to static methods like * {@link Application#getCurrent()} still work. * * @param executorService * The JDK service to wrap. * @return The wrapper service to use. */ public static ExecutorService wrap(final ExecutorService executorService) { return new AbstractExecutorService() { public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return executorService.awaitTermination(timeout, unit); } public void execute(final Runnable runnable) { // Save the thread local variables final Application currentApplication = Application.getCurrent(); final Context currentContext = Context.getCurrent(); final Integer currentVirtualHost = VirtualHost.getCurrent(); final Response currentResponse = Response.getCurrent(); executorService.execute(new Runnable() { public void run() { // Copy the thread local variables Response.setCurrent(currentResponse); Context.setCurrent(currentContext); VirtualHost.setCurrent(currentVirtualHost); Application.setCurrent(currentApplication); try { // Run the user task runnable.run(); } finally { Engine.clearThreadLocalVariables(); } } }); } public boolean isShutdown() { return executorService.isShutdown(); } public boolean isTerminated() { return executorService.isTerminated(); } public void shutdown() { executorService.shutdown(); } public List shutdownNow() { return executorService.shutdownNow(); } }; } /** * Allow {@link #shutdown()} and {@link #shutdownNow()} methods to * effectively shutdown the wrapped executor service. */ private volatile boolean shutdownAllowed; /** The wrapped JDK executor service. */ private volatile ExecutorService wrapped; /** * Constructor. */ public TaskService() { this.shutdownAllowed = false; setWrapped(wrap(createExecutorService())); } /** * Blocks until all tasks have completed execution after a shutdown request, * or the timeout occurs, or the current thread is interrupted, whichever * happens first. * * @param timeout * The maximum time to wait. * @param unit * The time unit. * @return True if this executor terminated and false if the timeout elapsed * before termination. */ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return getWrapped().awaitTermination(timeout, unit); } /** * Creates a new JDK executor service that will be wrapped. By default it * calls {@link Executors#newCachedThreadPool(ThreadFactory)}, passing the * result of {@link #createThreadFactory()} as a parameter. * * * @return A new JDK executor service. */ protected ExecutorService createExecutorService() { return Executors.newCachedThreadPool(createThreadFactory()); } /** * Creates a new thread factory that will properly name the Restlet created * threads with a "restlet-" prefix. * * @return A new thread factory. */ protected ThreadFactory createThreadFactory() { return new RestletThreadFactory(); } /** * Executes the given command asynchronously. * * @param command * The command to execute. */ public void execute(Runnable command) { getWrapped().execute(command); } /** * Returns the wrapped JDK executor service. * * @return The wrapped JDK executor service. */ private ExecutorService getWrapped() { return wrapped; } /** * Executes the given tasks, returning a list of Futures holding their * status and results when all complete.
    *
    * Due to a breaking change between Java SE versions 5 and 6, and in order * to maintain compatibility both at the source and binary level, we have * removed the generic information from this method. You can check the * {@link ExecutorService} interface for typing details. * * @param tasks * The task to execute. * @return The list of futures. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public List invokeAll(Collection tasks) throws InterruptedException { return getWrapped().invokeAll(tasks); } /** * Executes the given tasks, returning a list of Futures holding their * status and results when all complete or the timeout expires, whichever * happens first. Future.isDone() is true for each element of the returned * list. Upon return, tasks that have not completed are canceled. Note that * a completed task could have terminated either normally or by throwing an * exception. The results of this method are undefined if the given * collection is modified while this operation is in progress.
    *
    * Due to a breaking change between Java SE versions 5 and 6, and in order * to maintain compatibility both at the source and binary level, we have * removed the generic information from this method. You can check the * {@link ExecutorService} interface for typing details. * * @param tasks * The task to execute. * @param timeout * The maximum time to wait. * @param unit * The time unit. * @return The list of futures. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public List invokeAll(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException { return getWrapped().invokeAll(tasks, timeout, unit); } /** * Executes the given tasks, returning the result of one that has completed * successfully (i.e., without throwing an exception), if any do. Upon * normal or exceptional return, tasks that have not completed are * cancelled. The results of this method are undefined if the given * collection is modified while this operation is in progress. * * Due to a breaking change between Java SE versions 5 and 6, and in order * to maintain compatibility both at the source and binary level, we have * removed the generic information from this method. You can check the * {@link ExecutorService} interface for typing details. * * @param tasks * The task to execute. * @return The result returned by one of the tasks. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Object invokeAny(Collection tasks) throws InterruptedException, ExecutionException { return getWrapped().invokeAny(tasks); } /** * Executes the given tasks, returning the result of one that has completed * successfully (i.e., without throwing an exception), if any do before the * given timeout elapses. Upon normal or exceptional return, tasks that have * not completed are cancelled. The results of this method are undefined if * the given collection is modified while this operation is in progress. * * Due to a breaking change between Java SE versions 5 and 6, and in order * to maintain compatibility both at the source and binary level, we have * removed the generic information from this method. You can check the * {@link ExecutorService} interface for typing details. * * @param tasks * The task to execute. * @param timeout * The maximum time to wait. * @param unit * The time unit. * @return The result returned by one of the tasks. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Object invokeAny(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return getWrapped().invokeAny(tasks, timeout, unit); } /** * Returns true if this executor has been shut down. * * @return True if this executor has been shut down. */ public boolean isShutdown() { return getWrapped().isShutdown(); } /** * Indicates if the {@link #shutdown()} and {@link #shutdownNow()} methods * are allowed to effectively shutdown the wrapped executor service. Return * false by default. * * @return True if shutdown is allowed. */ public boolean isShutdownAllowed() { return shutdownAllowed; } /** * Returns true if all tasks have completed following shut down. Note that * isTerminated is never true unless either shutdown or shutdownNow was * called first. * * @return True if all tasks have completed following shut down. */ public boolean isTerminated() { return getWrapped().isTerminated(); } /** * Indicates if the {@link #shutdown()} and {@link #shutdownNow()} methods * are allowed to effectively shutdown the wrapped executor service. * * @param allowShutdown * True if shutdown is allowed. */ public void setShutdownAllowed(boolean allowShutdown) { this.shutdownAllowed = allowShutdown; } /** * Sets the wrapped JDK executor service. * * @param wrapped * The wrapped JDK executor service. */ private void setWrapped(ExecutorService wrapped) { this.wrapped = wrapped; } /** * Initiates an orderly shutdown in which previously submitted tasks are * executed, but no new tasks will be accepted. */ public void shutdown() { if (isShutdownAllowed()) { getWrapped().shutdown(); } } /** * Attempts to stop all actively executing tasks, halts the processing of * waiting tasks, and returns a list of the tasks that were awaiting * execution. * * @return The list of tasks that never commenced execution; */ public List shutdownNow() { return isShutdownAllowed() ? getWrapped().shutdownNow() : Collections . emptyList(); } @Override public synchronized void start() throws Exception { if (getWrapped().isShutdown()) { setWrapped(wrap(createExecutorService())); } super.start(); } @Override public synchronized void stop() throws Exception { super.stop(); if (!getWrapped().isShutdown()) { getWrapped().shutdown(); } } /** * Submits a value-returning task for execution and returns a Future * representing the pending results of the task. * * @param task * The task to submit. * @return A Future representing pending completion of the task, and whose * get() method will return the given result upon completion. */ public Future submit(Callable task) { return getWrapped().submit(task); } /** * * @param task * The task to submit. * @return A Future representing pending completion of the task, and whose * get() method will return the given result upon completion. */ public Future submit(Runnable task) { return getWrapped().submit(task); } /** * * @param task * The task to submit. * @param result * The result to return. * @return A Future representing pending completion of the task, and whose * get() method will return the given result upon completion. */ public Future submit(Runnable task, T result) { return getWrapped().submit(task, result); } } restlet-2.0.14/org.restlet/src/org/restlet/service/MetadataService.java0000664000175000017500000006636211757206350026633 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.CharacterSet; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.engine.application.MetadataExtension; /** * Application service providing access to metadata and their associated * extension names. The list of default mappings is documented in the * {@link #addCommonExtensions()} method.
    *
    * Internally, the mappings are stored as a list of "extension, metadata" pairs. * * @author Jerome Louvel */ public class MetadataService extends Service { /** The default character set for textual representations. */ private volatile CharacterSet defaultCharacterSet; /** The default encoding for representations. */ private volatile Encoding defaultEncoding; /** The default language for representations. */ private volatile Language defaultLanguage; /** The default media type for representations. */ private volatile MediaType defaultMediaType; /** The list of mappings between extension names and metadata. */ private final List mappings; /** * Constructor. Sets the default language to {@link Language#ENGLISH_US}, * the default encoding to {@link Encoding#IDENTITY} (no encoding) and the * default media type to {@link MediaType#APPLICATION_OCTET_STREAM}. It also * calls the {@link #addCommonExtensions()} method. */ public MetadataService() { this.defaultCharacterSet = CharacterSet.DEFAULT; this.defaultEncoding = Encoding.IDENTITY; this.defaultLanguage = Language.DEFAULT; this.defaultMediaType = MediaType.APPLICATION_OCTET_STREAM; this.mappings = new CopyOnWriteArrayList(); addCommonExtensions(); } /** * Adds a common list of associations from extensions to metadata. The list * of languages extensions:
    *

      *
    • en: English
    • *
    • es: Spanish
    • *
    • fr: French
    • *
    *
    * The list of media type extensions:
    *
      *
    • ai: PostScript document
    • *
    • atom: Atom syndication document
    • *
    • au: AU audio file
    • *
    • bin: Binary file
    • *
    • bmp: Bitmap graphics
    • *
    • class: Java bytecode
    • *
    • css: CSS stylesheet
    • *
    • csv: Comma-separated Values
    • *
    • dat: Fixed-width Values
    • *
    • dib: Device-Independent Bitmap Graphics
    • *
    • doc: Microsoft Word document
    • *
    • docx: Microsoft Office Word 2007 document
    • *
    • docm: Office Word 2007 macro-enabled document
    • *
    • dotx: Office Word 2007 template
    • *
    • dotm: Office Word 2007 macro-enabled document template
    • *
    • dtd: XML Document Type Definition
    • *
    • eps: Encapsulated PostScript
    • *
    • exe: Executable File (Microsoft Corporation)
    • *
    • fmt: FreeMarker encoding
    • *
    • form: Web forms (URL encoded)
    • *
    • ftl: FreeMarker encoding
    • *
    • gif: GIF image
    • *
    • hqx: BinHex 4 Compressed Archive (Macintosh)
    • *
    • htm, html: HTML document
    • *
    • ico: Windows icon (Favicon)
    • *
    • jad: Java Application Descriptor file
    • *
    • jar: Java Archive
    • *
    • java: Java source code
    • *
    • jnlp: Java Web start launch file
    • *
    • jpe, jpeg, jpg: JPEG image
    • *
    • js: JavaScript document
    • *
    • jsf: Java Server Faces file
    • *
    • json: JavaScript Object Notation document
    • *
    • kar: Karaoke MIDI file
    • *
    • latex: LaTeX document
    • *
    • man: Manual file
    • *
    • mathml: Mathml XML document
    • *
    • mid, midi: MIDI Audio
    • *
    • mov, qt: QuickTime video clip (Apple Computer, Inc.)
    • *
    • mp2, mp3: MPEG Audio Stream file
    • *
    • mp4: MPEG-4 video file
    • *
    • mpe, mpeg, mpg: MPEG video clip
    • *
    • n3: RDF N3 document
    • *
    • nt: RDF N-Triples document
    • *
    • odb: OpenDocument Database
    • *
    • odc: OpenDocument Chart
    • *
    • odf: OpenDocument Formula
    • *
    • odg: OpenDocument Drawing
    • *
    • odi: OpenDocument Image
    • *
    • odm: OpenDocument Master Document
    • *
    • odp: OpenDocument Presentation
    • *
    • ods: OpenDocument Spreadsheet
    • *
    • odt: OpenDocument Text
    • *
    • onetoc: Microsoft Office OneNote 2007 TOC
    • *
    • onetoc2: Office OneNote 2007 TOC
    • *
    • otg: OpenDocument Drawing Template
    • *
    • oth: HTML Document Template
    • *
    • otp: OpenDocument Presentation Template
    • *
    • ots: OpenDocument Spreadsheet Template
    • *
    • ott: OpenDocument Text Template
    • *
    • oxt: OpenOffice.org extension
    • *
    • pdf: Adobe PDF document
    • *
    • png: PNG image
    • *
    • potm: Office PowerPoint 2007 macro-enabled presentation template
    • *
    • potx: Office PowerPoint 2007 template
    • *
    • ppam: Office PowerPoint 2007 add-in
    • *
    • pps, ppt: Microsoft Powerpoint document
    • *
    • ppsm: Office PowerPoint 2007 macro-enabled slide show
    • *
    • ppsx: Office PowerPoint 2007 slide show
    • *
    • pptm: Office PowerPoint 2007 macro-enabled presentation
    • *
    • pptx: Microsoft Office PowerPoint 2007 presentation
    • *
    • ps: PostScript document
    • *
    • rdf: Description Framework document
    • *
    • rnc: Relax NG Schema document, Compact syntax
    • *
    • rng: Relax NG Schema document, XML syntax
    • *
    • rss: RSS file
    • *
    • rtf: Rich Text Format document
    • *
    • sav: SPSS Data
    • *
    • sit: StuffIt compressed archive file
    • *
    • sldm: Office PowerPoint 2007 macro-enabled slide
    • *
    • sldx: Office PowerPoint 2007 slide
    • *
    • snd: Amiga sound
    • *
    • sps: SPSS Script Syntax
    • *
    • sta: Stata data file
    • *
    • svg: Scalable Vector Graphics file
    • *
    • swf: Adobe Flash file
    • *
    • tar: Tape Archive file
    • *
    • tex: Tex file
    • *
    • tif, tiff: Tagged Image Format File
    • *
    • tsv: Tab-separated Values
    • *
    • txt: Plain text
    • *
    • ulw: MU-LAW (US telephony format)
    • *
    • vm: Velocity encoding
    • *
    • vrml: Virtual Reality Modeling Language file
    • *
    • vxml: VoiceXML source file
    • *
    • wadl: Web Application Description Language document
    • *
    • wav: Waveform audio
    • *
    • wrl: Plain text VRML file
    • *
    • xht, xhtml: XHTML document
    • *
    • xlam: Office Excel 2007 add-in
    • *
    • xls: Microsoft Excel document
    • *
    • xlsb: Office Excel 2007 binary workbook
    • *
    • xlsm: Office Excel 2007 macro-enabled workbook
    • *
    • xlsx: Microsoft Office Excel 2007 workbook
    • *
    • xltm: Office Excel 2007 macro-enabled workbook template
    • *
    • xltx: Office Excel 2007 template
    • *
    • xmi: XMI document
    • *
    • xml: XML document
    • *
    • xsd: W3C XML Schema document
    • *
    • xsl, xslt: XSL Transform file
    • *
    • xul: XML User Interface Language file
    • *
    • z: UNIX compressed archive file
    • *
    • zip: Zip archive
    • *
    */ public void addCommonExtensions() { List dm = new ArrayList(); ext(dm, "en", Language.ENGLISH); ext(dm, "es", Language.SPANISH); ext(dm, "fr", Language.FRENCH); ext(dm, "ai", MediaType.APPLICATION_POSTSCRIPT); ext(dm, "ascii", CharacterSet.US_ASCII); ext(dm, "atom", MediaType.APPLICATION_ATOM); ext(dm, "atomcat", MediaType.APPLICATION_ATOMPUB_CATEGORY); ext(dm, "atomsvc", MediaType.APPLICATION_ATOMPUB_SERVICE); ext(dm, "au", MediaType.AUDIO_BASIC); ext(dm, "bin", MediaType.APPLICATION_OCTET_STREAM); ext(dm, "bmp", MediaType.IMAGE_BMP); ext(dm, "class", MediaType.APPLICATION_JAVA); ext(dm, "css", MediaType.TEXT_CSS); ext(dm, "csv", MediaType.TEXT_CSV); ext(dm, "dat", MediaType.TEXT_DAT); ext(dm, "dib", MediaType.IMAGE_BMP); ext(dm, "doc", MediaType.APPLICATION_WORD); ext(dm, "docm", MediaType.APPLICATION_MSOFFICE_DOCM); ext(dm, "docx", MediaType.APPLICATION_MSOFFICE_DOCX); ext(dm, "dotm", MediaType.APPLICATION_MSOFFICE_DOTM); ext(dm, "dotx", MediaType.APPLICATION_MSOFFICE_DOTX); ext(dm, "dtd", MediaType.APPLICATION_XML_DTD); ext(dm, "eps", MediaType.APPLICATION_POSTSCRIPT); ext(dm, "exe", MediaType.APPLICATION_OCTET_STREAM); ext(dm, "fmt", Encoding.FREEMARKER); ext(dm, "form", MediaType.APPLICATION_WWW_FORM); ext(dm, "ftl", Encoding.FREEMARKER, true); ext(dm, "gif", MediaType.IMAGE_GIF); ext(dm, "hqx", MediaType.APPLICATION_MAC_BINHEX40); ext(dm, "ico", MediaType.IMAGE_ICON); ext(dm, "jad", MediaType.TEXT_J2ME_APP_DESCRIPTOR); ext(dm, "jar", MediaType.APPLICATION_JAVA_ARCHIVE); ext(dm, "java", MediaType.TEXT_PLAIN); ext(dm, "jnlp", MediaType.APPLICATION_JNLP); ext(dm, "jpe", MediaType.IMAGE_JPEG); ext(dm, "jpeg", MediaType.IMAGE_JPEG); ext(dm, "jpg", MediaType.IMAGE_JPEG); ext(dm, "js", MediaType.APPLICATION_JAVASCRIPT); ext(dm, "jsf", MediaType.TEXT_PLAIN); ext(dm, "kar", MediaType.AUDIO_MIDI); ext(dm, "latex", MediaType.APPLICATION_LATEX); ext(dm, "latin1", CharacterSet.ISO_8859_1); ext(dm, "mac", CharacterSet.MACINTOSH); ext(dm, "man", MediaType.APPLICATION_TROFF_MAN); ext(dm, "mathml", MediaType.APPLICATION_MATHML); ext(dm, "mid", MediaType.AUDIO_MIDI); ext(dm, "midi", MediaType.AUDIO_MIDI); ext(dm, "mov", MediaType.VIDEO_QUICKTIME); ext(dm, "mp2", MediaType.AUDIO_MPEG); ext(dm, "mp3", MediaType.AUDIO_MPEG); ext(dm, "mp4", MediaType.VIDEO_MP4); ext(dm, "mpe", MediaType.VIDEO_MPEG); ext(dm, "mpeg", MediaType.VIDEO_MPEG); ext(dm, "mpg", MediaType.VIDEO_MPEG); ext(dm, "n3", MediaType.TEXT_RDF_N3); ext(dm, "nt", MediaType.TEXT_PLAIN); ext(dm, "odb", MediaType.APPLICATION_OPENOFFICE_ODB); ext(dm, "odc", MediaType.APPLICATION_OPENOFFICE_ODC); ext(dm, "odf", MediaType.APPLICATION_OPENOFFICE_ODF); ext(dm, "odi", MediaType.APPLICATION_OPENOFFICE_ODI); ext(dm, "odm", MediaType.APPLICATION_OPENOFFICE_ODM); ext(dm, "odg", MediaType.APPLICATION_OPENOFFICE_ODG); ext(dm, "odp", MediaType.APPLICATION_OPENOFFICE_ODP); ext(dm, "ods", MediaType.APPLICATION_OPENOFFICE_ODS); ext(dm, "odt", MediaType.APPLICATION_OPENOFFICE_ODT); ext(dm, "onetoc", MediaType.APPLICATION_MSOFFICE_ONETOC); ext(dm, "onetoc2", MediaType.APPLICATION_MSOFFICE_ONETOC2); ext(dm, "otg", MediaType.APPLICATION_OPENOFFICE_OTG); ext(dm, "oth", MediaType.APPLICATION_OPENOFFICE_OTH); ext(dm, "otp", MediaType.APPLICATION_OPENOFFICE_OTP); ext(dm, "ots", MediaType.APPLICATION_OPENOFFICE_OTS); ext(dm, "ott", MediaType.APPLICATION_OPENOFFICE_OTT); ext(dm, "oxt", MediaType.APPLICATION_OPENOFFICE_OXT); ext(dm, "pdf", MediaType.APPLICATION_PDF); ext(dm, "png", MediaType.IMAGE_PNG); ext(dm, "potx", MediaType.APPLICATION_MSOFFICE_POTX); ext(dm, "potm", MediaType.APPLICATION_MSOFFICE_POTM); ext(dm, "ppam", MediaType.APPLICATION_MSOFFICE_PPAM); ext(dm, "pps", MediaType.APPLICATION_POWERPOINT); ext(dm, "ppsm", MediaType.APPLICATION_MSOFFICE_PPSM); ext(dm, "ppsx", MediaType.APPLICATION_MSOFFICE_PPSX); ext(dm, "ppt", MediaType.APPLICATION_POWERPOINT); ext(dm, "pptm", MediaType.APPLICATION_MSOFFICE_PPTM); ext(dm, "pptx", MediaType.APPLICATION_MSOFFICE_PPTX); ext(dm, "ps", MediaType.APPLICATION_POSTSCRIPT); ext(dm, "qt", MediaType.VIDEO_QUICKTIME); ext(dm, "rdf", MediaType.APPLICATION_RDF_XML); ext(dm, "rnc", MediaType.APPLICATION_RELAXNG_COMPACT); ext(dm, "rng", MediaType.APPLICATION_RELAXNG_XML); ext(dm, "rss", MediaType.APPLICATION_RSS); ext(dm, "rtf", MediaType.APPLICATION_RTF); ext(dm, "sav", MediaType.APPLICATION_SPSS_SAV); ext(dm, "sit", MediaType.APPLICATION_STUFFIT); ext(dm, "sldm", MediaType.APPLICATION_MSOFFICE_SLDM); ext(dm, "sldx", MediaType.APPLICATION_MSOFFICE_SLDX); ext(dm, "snd", MediaType.AUDIO_BASIC); ext(dm, "sps", MediaType.APPLICATION_SPSS_SPS); ext(dm, "sta", MediaType.APPLICATION_STATA_STA); ext(dm, "svg", MediaType.IMAGE_SVG); ext(dm, "swf", MediaType.APPLICATION_FLASH); ext(dm, "tar", MediaType.APPLICATION_TAR); ext(dm, "tex", MediaType.APPLICATION_TEX); ext(dm, "tif", MediaType.IMAGE_TIFF); ext(dm, "tiff", MediaType.IMAGE_TIFF); ext(dm, "tsv", MediaType.TEXT_TSV); ext(dm, "ulw", MediaType.AUDIO_BASIC); ext(dm, "utf16", CharacterSet.UTF_16); ext(dm, "utf8", CharacterSet.UTF_8); ext(dm, "vm", Encoding.VELOCITY); ext(dm, "vrml", MediaType.MODEL_VRML); ext(dm, "vxml", MediaType.APPLICATION_VOICEXML); ext(dm, "wadl", MediaType.APPLICATION_WADL); ext(dm, "wav", MediaType.AUDIO_WAV); ext(dm, "win", CharacterSet.WINDOWS_1252); ext(dm, "wrl", MediaType.MODEL_VRML); ext(dm, "xht", MediaType.APPLICATION_XHTML); ext(dm, "xls", MediaType.APPLICATION_EXCEL); ext(dm, "xlsx", MediaType.APPLICATION_MSOFFICE_XLSX); ext(dm, "xlsm", MediaType.APPLICATION_MSOFFICE_XLSM); ext(dm, "xltx", MediaType.APPLICATION_MSOFFICE_XLTX); ext(dm, "xltm", MediaType.APPLICATION_MSOFFICE_XLTM); ext(dm, "xlsb", MediaType.APPLICATION_MSOFFICE_XLSB); ext(dm, "xlam", MediaType.APPLICATION_MSOFFICE_XLAM); ext(dm, "xmi", MediaType.APPLICATION_XMI_XML); ext(dm, "xsd", MediaType.APPLICATION_W3C_SCHEMA); ext(dm, "xsl", MediaType.APPLICATION_W3C_XSLT); ext(dm, "xslt", MediaType.APPLICATION_W3C_XSLT); ext(dm, "xul", MediaType.APPLICATION_XUL); ext(dm, "z", MediaType.APPLICATION_COMPRESS); ext(dm, "zip", MediaType.APPLICATION_ZIP); ext(dm, "htm", MediaType.TEXT_HTML); ext(dm, "html", MediaType.TEXT_HTML); ext(dm, "json", MediaType.APPLICATION_JSON); ext(dm, "txt", MediaType.TEXT_PLAIN, true); ext(dm, "xhtml", MediaType.APPLICATION_XHTML); ext(dm, "xml", MediaType.TEXT_XML); ext(dm, "xml", MediaType.APPLICATION_XML); // Add all those mappings this.mappings.addAll(dm); } /** * Maps an extension to some metadata (media type, language or character * set) to an extension. * * @param extension * The extension name. * @param metadata * The metadata to map. */ public void addExtension(String extension, Metadata metadata) { addExtension(extension, metadata, false); } /** * Maps an extension to some metadata (media type, language or character * set) to an extension. * * @param extension * The extension name. * @param metadata * The metadata to map. * @param preferred * indicates if this mapping is the preferred one. */ public void addExtension(String extension, Metadata metadata, boolean preferred) { if (preferred) { // Add the mapping at the beginning of the list this.mappings.add(0, new MetadataExtension(extension, metadata)); } else { // Add the mapping at the end of the list this.mappings.add(new MetadataExtension(extension, metadata)); } } /** * clears the mappings for all extensions. */ public void clearExtensions() { this.mappings.clear(); } /** * Creates a new extension mapping. * * @param extensions * The extensions list to update. * @param extension * The extension name. * @param metadata * The associated metadata. * @param preferred * indicates if this mapping is the preferred one. * @return The new extension mapping. */ private void ext(List extensions, String extension, Metadata metadata) { ext(extensions, extension, metadata, false); } /** * Creates a new extension mapping. * * @param extensions * The extensions list to update. * @param extension * The extension name. * @param metadata * The associated metadata. * @param preferred * indicates if this mapping is the preferred one. * @return The new extension mapping. */ private void ext(List extensions, String extension, Metadata metadata, boolean preferred) { if (preferred) { // Add the mapping at the beginning of the list extensions.add(0, new MetadataExtension(extension, metadata)); } else { // Add the mapping at the end of the list extensions.add(new MetadataExtension(extension, metadata)); } } /** * Returns all the media types associated to this extension. It returns null * if the extension was not declared. * * @param extension * The extension name without any delimiter. * @return The list of media type associated to this extension. */ public List getAllMediaTypes(String extension) { List result = null; if (extension != null) { // Look for all registered convenient mapping. for (final MetadataExtension metadataExtension : this.mappings) { if (extension.equals(metadataExtension.getName()) && (metadataExtension.getMetadata() instanceof MediaType)) { if (result == null) { result = new ArrayList(); } result.add(metadataExtension.getMediaType()); } } } return result; } /** * Returns all the metadata associated to this extension. It returns null if * the extension was not declared. * * @param extension * The extension name without any delimiter. * @return The list of metadata associated to this extension. */ public List getAllMetadata(String extension) { List result = null; if (extension != null) { // Look for all registered convenient mapping. for (final MetadataExtension metadataExtension : this.mappings) { if (extension.equals(metadataExtension.getName())) { if (result == null) { result = new ArrayList(); } result.add(metadataExtension.getMetadata()); } } } return result; } /** * Returns the character set associated to this extension. It returns null * if the extension was not declared of it is corresponds to another type of * medatata such as a media type. If several metadata are associated to the * same extension then only the first matching metadata is returned. * * * @param extension * The extension name without any delimiter. * @return The character set associated to this extension. */ public CharacterSet getCharacterSet(String extension) { return getMetadata(extension, CharacterSet.class); } /** * Returns the default character set for textual representations. * * @return The default character set for textual representations. */ public CharacterSet getDefaultCharacterSet() { return this.defaultCharacterSet; } /** * Returns the default encoding for representations. * * @return The default encoding for representations. */ public Encoding getDefaultEncoding() { return this.defaultEncoding; } /** * Returns the default language for representations. * * @return The default language for representations. */ public Language getDefaultLanguage() { return this.defaultLanguage; } /** * Returns the default media type for representations. * * @return The default media type for representations. */ public MediaType getDefaultMediaType() { return this.defaultMediaType; } /** * Returns the encoding associated to this extension. It returns null if the * extension was not declared of it is corresponds to another type of * medatata such as a media type. If several metadata are associated to the * same extension then only the first matching metadata is returned. * * @param extension * The extension name without any delimiter. * @return The encoding associated to this extension. */ public Encoding getEncoding(String extension) { return getMetadata(extension, Encoding.class); } /** * Returns the first extension mapping to this metadata. * * @param metadata * The metadata to find. * @return The first extension mapping to this metadata. */ public String getExtension(Metadata metadata) { if (metadata != null) { // Look for the first registered convenient mapping. for (final MetadataExtension metadataExtension : this.mappings) { if (metadata.equals(metadataExtension.getMetadata())) { return metadataExtension.getName(); } } } return null; } /** * Returns the language associated to this extension. It returns null if the * extension was not declared of it is corresponds to another type of * medatata such as a media type. If several metadata are associated to the * same extension then only the first matching metadata is returned. * * @param extension * The extension name without any delimiter. * @return The language associated to this extension. */ public Language getLanguage(String extension) { return getMetadata(extension, Language.class); } /** * Returns the mediatype associated to this extension. It returns null if * the extension was not declared of it is corresponds to another type of * medatata such as a language. If several metadata are associated to the * same extension (ex: 'xml' for both 'text/xml' and 'application/xml') then * only the first matching metadata is returned. * * * @param extension * The extension name without any delimiter. * @return The media type associated to this extension. */ public MediaType getMediaType(String extension) { return getMetadata(extension, MediaType.class); } /** * Returns the metadata associated to this extension. It returns null if the * extension was not declared. If several metadata are associated to the * same extension (ex: 'xml' for both 'text/xml' and 'application/xml') then * only the first matching metadata is returned. * * @param extension * The extension name without any delimiter. * @return The metadata associated to this extension. */ public Metadata getMetadata(String extension) { if (extension != null) { // Look for the first registered convenient mapping. for (final MetadataExtension metadataExtension : this.mappings) { if (extension.equals(metadataExtension.getName())) { return metadataExtension.getMetadata(); } } } return null; } /** * Returns the metadata associated to this extension. It returns null if the * extension was not declared or is not of the target metadata type. * * @param * @param extension * The extension name without any delimiter. * @param metadataType * The target metadata type. * @return The metadata associated to this extension. */ public T getMetadata(String extension, Class metadataType) { Metadata metadata = getMetadata(extension); if (metadata != null && metadataType.isAssignableFrom(metadata.getClass())) { return metadataType.cast(metadata); } return null; } /** * Sets the default character set for local representations. * * @param defaultCharacterSet * The default character set for local representations. */ public void setDefaultCharacterSet(CharacterSet defaultCharacterSet) { this.defaultCharacterSet = defaultCharacterSet; } /** * Sets the default encoding for local representations. * * @param defaultEncoding * The default encoding for local representations. */ public void setDefaultEncoding(Encoding defaultEncoding) { this.defaultEncoding = defaultEncoding; } /** * Sets the default language for local representations. * * @param defaultLanguage * The default language for local representations. */ public void setDefaultLanguage(Language defaultLanguage) { this.defaultLanguage = defaultLanguage; } /** * Sets the default media type for local representations. * * @param defaultMediaType * The default media type for local representations. */ public void setDefaultMediaType(MediaType defaultMediaType) { this.defaultMediaType = defaultMediaType; } } restlet-2.0.14/org.restlet/src/org/restlet/service/ConnectorService.java0000664000175000017500000001243011757206346027035 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Application; import org.restlet.data.Protocol; import org.restlet.representation.Representation; /** * Application service declaring client and server connectors. This is useful at * deployment time to know which connectors an application expects to be able to * use.
    *
    * If you need to override the {@link #afterSend(Representation)} method for * example, just create a subclass and set it on your application with the * {@link Application#setConnectorService(ConnectorService)} method.
    *
    * Implementation note: the parent component will ensure that client connectors * won't automatically follow redirections. This will ensure a consistent * behavior and portability of applications. * * @author Jerome Louvel */ public class ConnectorService extends Service { /** The list of required client protocols. */ private final List clientProtocols; /** The list of required server protocols. */ private final List serverProtocols; /** * Constructor. */ public ConnectorService() { this.clientProtocols = new CopyOnWriteArrayList(); this.serverProtocols = new CopyOnWriteArrayList(); } /** * Call-back method invoked by the client or server connectors just after * sending the response to the target component. The default implementation * does nothing. * * @param entity * The optional entity about to be committed. */ public void afterSend(Representation entity) { // Do nothing by default. } /** * Call-back method invoked by the client or server connectors just before * sending the response to the target component. The default implementation * does nothing. * * @param entity * The optional entity about to be committed. */ public void beforeSend(Representation entity) { // Do nothing by default. } /** * Returns the modifiable list of required client protocols. You need to * update this list if you need the parent component to provide additional * client connectors. * * @return The list of required client protocols. */ public List getClientProtocols() { return this.clientProtocols; } /** * Returns the modifiable list of required server protocols. An empty list * means that all protocols are potentially supported (default case). You * should update this list to restrict the actual protocols supported by * your application. * * @return The list of required server protocols. */ public List getServerProtocols() { return this.serverProtocols; } /** * Sets the modifiable list of required client protocols. This method clears * the current list and adds all entries in the parameter list. * * @param clientProtocols * A list of required client protocols. */ public void setClientProtocols(List clientProtocols) { synchronized (getClientProtocols()) { if (clientProtocols != getClientProtocols()) { getClientProtocols().clear(); if (clientProtocols != null) { getClientProtocols().addAll(clientProtocols); } } } } /** * Sets the modifiable list of required server protocols. This method clears * the current list and adds all entries in the parameter list. * * @param serverProtocols * A list of required server protocols. */ public void setServerProtocols(List serverProtocols) { synchronized (getServerProtocols()) { if (serverProtocols != getServerProtocols()) { getServerProtocols().clear(); if (serverProtocols != null) { getServerProtocols().addAll(serverProtocols); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/service/accept.properties0000664000175000017500000000074111757206350026271 0ustar jamespagejamespage#Internet explorer agentName: msie acceptOld: acceptNew: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 #Opera agentName: opera acceptOld: acceptNew: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 #Safari agentName: safari acceptOld: acceptNew: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 #Chrome agentName: chrome acceptOld: acceptNew: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 restlet-2.0.14/org.restlet/src/org/restlet/service/DecoderService.java0000664000175000017500000000365611757206346026462 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import org.restlet.Context; import org.restlet.engine.application.Decoder; import org.restlet.routing.Filter; /** * Application service automatically decoding or uncompressing request entities. * * @author Jerome Louvel */ public class DecoderService extends Service { /** * Constructor. */ public DecoderService() { super(); } /** * Constructor. * * @param enabled * True if the service has been enabled. */ public DecoderService(boolean enabled) { super(enabled); } @Override public Filter createInboundFilter(Context context) { return new Decoder(context, true, false); } } restlet-2.0.14/org.restlet/src/org/restlet/service/ConverterService.java0000664000175000017500000002377511757206346027070 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.Engine; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.converter.ConverterUtils; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Application service converting between representation and regular Java * objects. The conversion can work in both directions.
    *
    * By default, the following conversions are supported. Additional ones can be * plugged into the engine. * * @author Jerome Louvel */ public class ConverterService extends Service { /** * Constructor. */ public ConverterService() { super(); } /** * Constructor. * * @param enabled * True if the service has been enabled. */ public ConverterService(boolean enabled) { super(enabled); } /** * Returns the list of object classes that can be converted from a given * variant. * * @param source * The source variant. * @return The list of object class that can be converted. */ public List> getObjectClasses(Variant source) { List> result = null; List> helperObjectClasses = null; for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { helperObjectClasses = ch.getObjectClasses(source); if (helperObjectClasses != null) { if (result == null) { result = new ArrayList>(); } result.addAll(helperObjectClasses); } } return result; } /** * Returns the list of variants that can be converted from a given object * class. * * @param source * The source class. * @param target * The expected representation metadata. * @return The list of variants that can be converted. */ public List getVariants(Class source, Variant target) { return ConverterUtils.getVariants(source, target); } /** * Converts a Representation into a regular Java object. * * @param source * The source representation to convert. * @return The converted Java object. * @throws IOException */ public Object toObject(Representation source) throws IOException { return toObject(source, null, null); } /** * Converts a Representation into a regular Java object. * * @param * The expected class of the Java object. * @param source * The source representation to convert. * @param target * The target class of the Java object. * @param resource * The parent resource. * @return The converted Java object. * @throws IOException */ public T toObject(Representation source, Class target, UniformResource resource) throws IOException { T result = null; if ((source != null) && source.isAvailable() && (source.getSize() != 0)) { ConverterHelper ch = ConverterUtils.getBestHelper(source, target, resource); if (ch != null) { Context.getCurrentLogger().fine( "The following converter was selected for the " + source + " representation: " + ch); result = ch.toObject(source, target, resource); if (result instanceof Representation) { Representation resultRepresentation = (Representation) result; // Copy the variant metadata resultRepresentation.setCharacterSet(source .getCharacterSet()); resultRepresentation.setMediaType(source.getMediaType()); resultRepresentation.getEncodings().addAll( source.getEncodings()); resultRepresentation.getLanguages().addAll( source.getLanguages()); } } else { Context.getCurrentLogger().warning( "Unable to find a converter for this representation : " + source); } } return result; } /** * Converts a regular Java object into a Representation. The converter will * use the preferred variant of the selected converter. * * @param source * The source object to convert. * @return The converted representation. */ public Representation toRepresentation(Object source) { return toRepresentation(source, null, null); } /** * Converts a regular Java object into a Representation. * * @param source * The source object to convert. * @param target * The target representation variant. * @param resource * The parent resource. * @return The converted representation. */ public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; ConverterHelper ch = ConverterUtils.getBestHelper(source, target, resource); if (ch != null) { try { Context.getCurrentLogger().fine( "The following converter was selected for the " + source + " object: " + ch); if (target == null) { List variants = ch.getVariants(source .getClass()); if ((variants != null) && !variants.isEmpty()) { if (resource != null) { target = resource.getClientInfo() .getPreferredVariant(variants, resource.getMetadataService()); } else { target = variants.get(0); } } else { target = new Variant(); } } result = ch.toRepresentation(source, target, resource); if (result != null) { // Copy the variant metadata if necessary if (result.getCharacterSet() == null) { result.setCharacterSet(target.getCharacterSet()); } if ((result.getMediaType() == null) || !result.getMediaType().isConcrete()) { if ((target.getMediaType() != null) && target.getMediaType().isConcrete()) { result.setMediaType(target.getMediaType()); } else if (resource != null) { result.setMediaType(resource.getMetadataService() .getDefaultMediaType()); } else { result.setMediaType(MediaType.APPLICATION_OCTET_STREAM); } } if (result.getEncodings().isEmpty()) { result.getEncodings().addAll(target.getEncodings()); } if (result.getLanguages().isEmpty()) { result.getLanguages().addAll(target.getLanguages()); } } } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to convert object to a representation", e); } } else { Context.getCurrentLogger().warning( "Unable to find a converter for this object : " + source); } return result; } /** * Updates the media type preferences with available conversion capabilities * for the given entity class. * * @param preferences * The media type preferences. * @param entity * The entity class to convert. */ public void updatePreferences(List> preferences, Class entity) { for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { ch.updatePreferences(preferences, entity); } } } restlet-2.0.14/org.restlet/src/org/restlet/Application.java0000664000175000017500000004533711757206346024401 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.engine.Engine; import org.restlet.engine.RestletHelper; import org.restlet.engine.application.ApplicationHelper; import org.restlet.engine.resource.AnnotationUtils; import org.restlet.resource.Finder; import org.restlet.security.Role; import org.restlet.service.ConnectorService; import org.restlet.service.ConverterService; import org.restlet.service.DecoderService; import org.restlet.service.MetadataService; import org.restlet.service.RangeService; import org.restlet.service.StatusService; import org.restlet.service.TunnelService; import org.restlet.util.ServiceList; /** * Restlet managing a coherent set of Resources and Services. Applications are * guaranteed to receive calls with their base reference set relatively to the * VirtualHost that served them. This class is both a descriptor able to create * the root Restlet and the actual Restlet that can be attached to one or more * VirtualHost instances.
    *
    * Applications also have many useful services associated. They are all enabled * by default and are available as properties that can be eventually overridden: *
      *
    • "connectorService" to declare necessary client and server connectors.
    • *
    • "converterService" to convert between regular objects and * representations.
    • *
    • "decoderService" to automatically decode or uncompress request entities.
    • *
    • "metadataService" to provide access to metadata and their associated * extension names.
    • *
    • "rangeService" to automatically exposes ranges of response entities.
    • *
    • "statusService" to provide common representations for exception status.
    • *
    • "taskService" to run tasks asynchronously.
    • *
    • "tunnelService" to tunnel method names or client preferences via query * parameters.
    • *
    * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class Application extends Restlet { private static final ThreadLocal CURRENT = new ThreadLocal(); /** * This variable is stored internally as a thread local variable and updated * each time a call enters an application. * * Warning: this method should only be used under duress. You should by * default prefer obtaining the current application using methods such as * {@link org.restlet.resource.Resource#getApplication()} * * @return The current context. */ public static Application getCurrent() { return CURRENT.get(); } /** * Sets the context to associated with the current thread. * * @param application * The thread's context. */ public static void setCurrent(Application application) { CURRENT.set(application); } /** Finder class to instantiate. */ private volatile Class finderClass; /** The helper provided by the implementation. */ private volatile RestletHelper helper; /** The modifiable list of roles. */ private final List roles; /** The inbound root Restlet. */ private volatile Restlet inboundRoot; /** The outbound root Restlet. */ private volatile Restlet outboundRoot; /** The list of services. */ private final ServiceList services; /** * Constructor. Note this constructor is convenient because you don't have * to provide a context like for {@link #Application(Context)}. Therefore * the context will initially be null. It's only when you attach the * application to a virtual host via one of its attach*() methods that a * proper context will be set. */ public Application() { this(null); } /** * Constructor. * * @param context * The context to use based on parent component context. This * context should be created using the * {@link Context#createChildContext()} method to ensure a proper * isolation with the other applications. */ public Application(Context context) { super(context); if (Engine.getInstance() != null) { this.helper = new ApplicationHelper(this); } this.outboundRoot = null; this.inboundRoot = null; this.roles = new CopyOnWriteArrayList(); this.services = new ServiceList(context); this.services.add(new TunnelService(true, true)); this.services.add(new StatusService()); this.services.add(new DecoderService()); this.services.add(new RangeService()); this.services.add(new ConnectorService()); this.services.add(new ConverterService()); this.services.add(new MetadataService()); this.services.add(new org.restlet.service.TaskService()); } /** * Creates a inbound root Restlet that will receive all incoming calls. In * general, instances of Router, Filter or Finder classes will be used as * initial application Restlet. The default implementation returns null by * default. This method is intended to be overridden by subclasses. * * @return The server root Restlet. */ public Restlet createInboundRoot() { return null; } /** * Creates a outbound root Restlet that will receive all outgoing calls from * ClientResource. In general, instances of Router, Filter or Finder classes * will be used as initial application Restlet. The default implementation * returns the {@link Context#getClientDispatcher()} by default. This method * is intended to be overridden by subclasses. * * @return The server root Restlet. */ public Restlet createOutboundRoot() { return (getContext() != null) ? getContext().getClientDispatcher() : null; } /** * Creates a inbound root Restlet that will receive all incoming calls. In * general, instances of Router, Filter or Handler classes will be used as * initial application Restlet. The default implementation returns null by * default. This method is intended to be overridden by subclasses. * * @return The server root Restlet. * @deprecated Override the {@link #createInboundRoot()} method instead. */ @Deprecated public Restlet createRoot() { return createInboundRoot(); } /** * Returns the connector service. The service is enabled by default. * * @return The connector service. */ public ConnectorService getConnectorService() { return getServices().get(ConnectorService.class); } /** * Returns the converter service. The service is enabled by default. * * @return The converter service. */ public ConverterService getConverterService() { return getServices().get(ConverterService.class); } /** * Returns the decoder service. The service is enabled by default. * * @return The decoder service. */ public DecoderService getDecoderService() { return getServices().get(DecoderService.class); } /** * Returns the finder class used to instantiate resource classes. By * default, it returns the {@link Finder} class. This property is leveraged * by {@link #setClientRoot(Class)} and {@link #setInboundRoot(Class)} * methods. * * @return the finder class to instantiate. */ public Class getFinderClass() { return finderClass; } /** * Returns the helper provided by the implementation. * * @return The helper provided by the implementation. */ private RestletHelper getHelper() { return this.helper; } /** * Returns the inbound root Restlet. * * @return The inbound root Restlet. */ public Restlet getInboundRoot() { if (this.inboundRoot == null) { synchronized (this) { if (this.inboundRoot == null) { this.inboundRoot = createRoot(); } } } return this.inboundRoot; } /** * Returns the metadata service. The service is enabled by default. * * @return The metadata service. */ public MetadataService getMetadataService() { return getServices().get(MetadataService.class); } /** * Returns the outbound root Restlet. * * @return The outbound root Restlet. */ public Restlet getOutboundRoot() { if (this.outboundRoot == null) { synchronized (this) { if (this.outboundRoot == null) { this.outboundRoot = createOutboundRoot(); } } } return this.outboundRoot; } /** * Returns the range service. * * @return The range service. */ public RangeService getRangeService() { return getServices().get(RangeService.class); } /** * Returns the role associated to the given name. * * @param name * The name of the role to find. * @return The role matched or null. */ public Role getRole(String name) { for (Role role : getRoles()) { if (role.getName().equals(name)) { return role; } } return null; } /** * Returns the modifiable list of roles. * * @return The modifiable list of roles. */ public List getRoles() { return roles; } /** * Returns the root inbound Restlet. Invokes the createRoot() method if no * inbound root has been set, and stores the Restlet created for future * uses. * * @return The root inbound Restlet. * @deprecated Use the {@link #getInboundRoot()} method instead. */ @Deprecated public synchronized Restlet getRoot() { return getInboundRoot(); } /** * Returns the modifiable list of services. * * @return The modifiable list of services. */ public ServiceList getServices() { return services; } /** * Returns the status service. The service is enabled by default. * * @return The status service. */ 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. */ public org.restlet.service.TaskService getTaskService() { return getServices().get(org.restlet.service.TaskService.class); } /** * Returns the tunnel service. The service is enabled by default. * * @return The tunnel service. */ public TunnelService getTunnelService() { return getServices().get(TunnelService.class); } @Override public void handle(Request request, Response response) { super.handle(request, response); if (getHelper() != null) { getHelper().handle(request, response); } } /** * Sets the client root Resource class. * * @param clientRootClass * The client root Resource class. */ public synchronized void setClientRoot(Class clientRootClass) { setOutboundRoot(Finder.createFinder(clientRootClass, getFinderClass(), getContext(), getLogger())); } /** * Sets the connector service. * * @param connectorService * The connector service. */ public void setConnectorService(ConnectorService connectorService) { getServices().set(connectorService); } @Override public void setContext(Context context) { super.setContext(context); getServices().setContext(context); } /** * Sets the converter service. * * @param converterService * The converter service. */ public void setConverterService(ConverterService converterService) { getServices().set(converterService); } /** * Sets the decoder service. * * @param decoderService * The decoder service. */ public void setDecoderService(DecoderService decoderService) { getServices().set(decoderService); } /** * Sets the finder class to instantiate. This property is leveraged by * {@link #setClientRoot(Class)} and {@link #setInboundRoot(Class)} methods. * * @param finderClass * The finder class to instantiate. */ public void setFinderClass(Class finderClass) { this.finderClass = finderClass; } /** * Sets the inbound root Resource class. * * @param inboundRootClass * The inbound root Resource class. */ public synchronized void setInboundRoot(Class inboundRootClass) { setInboundRoot(Finder.createFinder(inboundRootClass, getFinderClass(), getContext(), getLogger())); } /** * Sets the inbound root Restlet. * * @param inboundRoot * The inbound root Restlet. */ public synchronized void setInboundRoot(Restlet inboundRoot) { this.inboundRoot = inboundRoot; if ((inboundRoot != null) && (inboundRoot.getContext() == null)) { inboundRoot.setContext(getContext()); } } /** * Sets the metadata service. * * @param metadataService * The metadata service. */ public void setMetadataService(MetadataService metadataService) { getServices().set(metadataService); } /** * Sets the outbound root Restlet. * * @param outboundRoot * The outbound root Restlet. */ public synchronized void setOutboundRoot(Restlet outboundRoot) { this.outboundRoot = outboundRoot; if ((outboundRoot != null) && (outboundRoot.getContext() == null)) { outboundRoot.setContext(getContext()); } } /** * Sets the range service. * * @param rangeService * The range service. */ public void setRangeService(RangeService rangeService) { getServices().set(rangeService); } /** * Sets the modifiable list of roles. This method clears the current list * and adds all entries in the parameter list. * * @param roles * A list of roles. */ public void setRoles(List roles) { synchronized (getRoles()) { if (roles != getRoles()) { getRoles().clear(); if (roles != null) { getRoles().addAll(roles); } } } } /** * Sets the inbound root Resource class. * * @param inboundRootClass * The inbound root Resource class. * @deprecated Use the {@link #setInboundRoot(Class)} method instead. */ @Deprecated public synchronized void setRoot(Class inboundRootClass) { setInboundRoot(inboundRootClass); } /** * Sets the inbound root Restlet. * * @param inboundRoot * The inbound root Restlet. * @deprecated Use the {@link #setInboundRoot(Restlet)} method instead. */ @Deprecated public synchronized void setRoot(Restlet inboundRoot) { setInboundRoot(inboundRoot); } /** * Sets the status service. * * @param statusService * The status service. */ public void setStatusService(StatusService statusService) { getServices().set(statusService); } /** * Sets the task service. * * @param taskService * The task service. */ public void setTaskService(org.restlet.service.TaskService taskService) { getServices().set(taskService); } /** * Sets the tunnel service. * * @param tunnelService * The tunnel service. */ public void setTunnelService(TunnelService tunnelService) { getServices().set(tunnelService); } /** * Starts the application, all the enabled associated services then the * inbound and outbound roots. */ @Override public synchronized void start() throws Exception { if (isStopped()) { super.start(); if (getHelper() != null) { getHelper().start(); } getServices().start(); if (getInboundRoot() != null) { getInboundRoot().start(); } if (getOutboundRoot() != null) { getOutboundRoot().start(); } } } /** * Stops the application, the inbound and outbound roots then all the * enabled associated services. Finally, it clears the internal cache of * annotations. */ @Override public synchronized void stop() throws Exception { if (isStarted()) { if (getOutboundRoot() != null) { getOutboundRoot().stop(); } if (getInboundRoot() != null) { getInboundRoot().stop(); } getServices().stop(); if (getHelper() != null) { getHelper().stop(); } // Clear the annotations cache AnnotationUtils.clearCache(); super.stop(); } } } restlet-2.0.14/org.restlet/src/org/restlet/resource/0000775000175000017500000000000011757206350023101 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/resource/ClientResource.java0000664000175000017500000016176511757206346026717 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Uniform; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Range; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.util.Series; /** * Client-side resource. Acts like a proxy of a target resource.
    * This class changes the semantics of the {@link UniformResource#getRequest()} * and {@link UniformResource#getResponse()} methods. Since a clientResource may * receive severals responses for a single request (in case of interim * response), the {@link #getResponse()} method returns the last received * response object. The Request object returned by the {@link #getRequest()} is * actually a prototype which is cloned (except the representation) just before * the {@link #handle()} method is called.
    * Users must be aware that by most representations can only be read or written * once. Some others, such as {@link StringRepresentation} stored the entity in * memory which can be read several times but has the drawback to consume * memory.
    * Concurrency note: instances of the class are not designed to be shared among * several threads. If thread-safety is necessary, consider using the * lower-level {@link Client} class instead. * * @author Jerome Louvel */ public class ClientResource extends UniformResource { /** * Creates a client resource that proxy calls to the given Java interface * into Restlet method calls. It basically creates a new instance of * {@link ClientResource} and invokes the {@link #wrap(Class)} method. * * @param * @param context * The context. * @param reference * The target reference. * @param resourceInterface * The annotated resource interface class to proxy. * @return The proxy instance. */ public static T create(Context context, Reference reference, Class resourceInterface) { ClientResource clientResource = new ClientResource(context, reference); return clientResource.wrap(resourceInterface); } /** * Creates a client resource that proxy calls to the given Java interface * into Restlet method calls. It basically creates a new instance of * {@link ClientResource} and invokes the {@link #wrap(Class)} method. * * @param * @param resourceInterface * The annotated resource interface class to proxy. * @return The proxy instance. */ public static T create(Reference reference, Class resourceInterface) { return create(null, reference, resourceInterface); } /** * Creates a client resource that proxy calls to the given Java interface * into Restlet method calls. It basically creates a new instance of * {@link ClientResource} and invokes the {@link #wrap(Class)} method. * * @param * @param uri * The target URI. * @param resourceInterface * The annotated resource interface class to proxy. * @return The proxy instance. */ public static T create(String uri, Class resourceInterface) { return create(null, new Reference(uri), resourceInterface); } /** Indicates if redirections should be automatically followed. */ private volatile boolean followingRedirects; /** The next Restlet. */ private volatile Uniform next; /** Indicates if the next Restlet has been created. */ private volatile boolean nextCreated; /** Number of retry attempts before reporting an error. */ private volatile int retryAttempts; /** Delay in milliseconds between two retry attempts. */ private volatile long retryDelay; /** Indicates if idempotent requests should be retried on error. */ private volatile boolean retryOnError; /** * Empty constructor. */ protected ClientResource() { } /** * Constructor. * * @param resource * The client resource to copy. */ public ClientResource(ClientResource resource) { Request request = new Request(resource.getRequest()); Response response = new Response(request); this.next = resource.getNext(); this.followingRedirects = resource.isFollowingRedirects(); this.retryOnError = resource.isRetryOnError(); this.retryDelay = resource.getRetryDelay(); this.retryAttempts = resource.getRetryAttempts(); init(resource.getContext(), request, response); } /** * Constructor. * * @param context * The context. * @param uri * The target URI. */ public ClientResource(Context context, java.net.URI uri) { this(context, Method.GET, uri); } /** * Constructor. * * @param context * The context. * @param method * The method to call. * @param uri * The target URI. */ public ClientResource(Context context, Method method, java.net.URI uri) { this(context, method, new Reference(uri)); } /** * Constructor. * * @param context * The context. * @param method * The method to call. * @param reference * The target reference. */ public ClientResource(Context context, Method method, Reference reference) { this(context, new Request(method, reference), new Response(null)); } /** * Constructor. * * @param context * The context. * @param method * The method to call. * @param uri * The target URI. */ public ClientResource(Context context, Method method, String uri) { this(context, method, new Reference(uri)); } /** * Constructor. * * @param context * The context. * @param reference * The target reference. */ public ClientResource(Context context, Reference reference) { this(context, Method.GET, reference); } /** * Constructor. * * @param context * The current context. * @param request * The handled request. * @param response * The handled response. */ public ClientResource(Context context, Request request, Response response) { if (context == null) { context = Context.getCurrent(); } // Don't remove this line. // See other constructor ClientResource(Context, Method, Reference) response.setRequest(request); this.followingRedirects = true; this.retryOnError = true; this.retryDelay = 2000L; this.retryAttempts = 2; init(context, request, response); } /** * Constructor. * * @param context * The context. * @param uri * The target URI. */ public ClientResource(Context context, String uri) { this(context, Method.GET, uri); } /** * Constructor. * * @param uri * The target URI. */ public ClientResource(java.net.URI uri) { this(Context.getCurrent(), null, uri); } /** * Constructor. * * @param method * The method to call. * @param uri * The target URI. */ public ClientResource(Method method, java.net.URI uri) { this(Context.getCurrent(), method, uri); } /** * Constructor. * * @param method * The method to call. * @param reference * The target reference. */ public ClientResource(Method method, Reference reference) { this(Context.getCurrent(), method, reference); } /** * Constructor. * * @param method * The method to call. * @param uri * The target URI. */ public ClientResource(Method method, String uri) { this(Context.getCurrent(), method, uri); } /** * Constructor. * * @param reference * The target reference. */ public ClientResource(Reference reference) { this(Context.getCurrent(), null, reference); } /** * Constructor. * * @param request * The handled request. * @param response * The handled response. */ public ClientResource(Request request, Response response) { this(Context.getCurrent(), request, response); } /** * Constructor. * * @param uri * The target URI. */ public ClientResource(String uri) { this(Context.getCurrent(), null, uri); } /** * Creates a next Restlet is no one is set. By default, it creates a new * {@link Client} based on the protocol of the resource's URI reference. * * @return The created next Restlet or null. */ protected Uniform createNext() { Uniform result = null; // Prefer the outbound root result = getApplication().getOutboundRoot(); if ((result == null) && (getContext() != null)) { // Try using directly the client dispatcher result = getContext().getClientDispatcher(); } if (result == null) { // As a final option, try creating a client connector Protocol rProtocol = getProtocol(); Reference rReference = getReference(); Protocol protocol = (rProtocol != null) ? rProtocol : (rReference != null) ? rReference.getSchemeProtocol() : null; if (protocol != null) { result = new Client(protocol); } } return result; } /** * Creates a new request by cloning the given one. * * @param prototype * The prototype request. * @return The new response. */ protected Request createRequest(Request prototype) { return new Request(prototype); } /** * Creates a new response for the given request. * * @param request * The associated request. * @return The new response. */ protected Response createResponse(Request request) { return new Response(request); } /** * Deletes the target resource and all its representations. If a success * status is not returned, then a resource exception is thrown. * * @return The optional response entity. * @see HTTP * DELETE method */ public Representation delete() throws ResourceException { return handle(Method.DELETE); } /** * Deletes the target resource and all its representations. If a success * status is not returned, then a resource exception is thrown. * * @param * The expected type for the response entity. * @param resultClass * The expected class for the response entity object. * @return The response entity object. * @see HTTP * DELETE method */ public T delete(Class resultClass) throws ResourceException { return handle(Method.DELETE, resultClass); } /** * Deletes the target resource and all its representations. If a success * status is not returned, then a resource exception is thrown. * * @param mediaType * The media type of the representation to retrieve. * @return The representation matching the given media type. * @throws ResourceException * @see HTTP * DELETE method */ public Representation delete(MediaType mediaType) throws ResourceException { return handle(Method.DELETE, mediaType); } /** * Releases the resource by stopping any connector automatically created and * associated to the "next" property (see {@link #getNext()} method. */ @Override protected void doRelease() throws ResourceException { if ((getNext() != null) && this.nextCreated) { if (getNext() instanceof Restlet) { try { ((Restlet) getNext()).stop(); } catch (Exception e) { throw new ResourceException(e); } } setNext(null); } } /** * Attempts to {@link #release()} the resource. */ @Override protected void finalize() throws Throwable { release(); } /** * Represents the resource using content negotiation to select the best * variant based on the client preferences. Note that the client preferences * will be automatically adjusted, but only for this request. If you want to * change them once for all, you can use the {@link #getClientInfo()} * method.
    *
    * If a success status is not returned, then a resource exception is thrown. * * @return The best representation. * @throws ResourceException * @see HTTP * GET method */ public Representation get() throws ResourceException { return handle(Method.GET); } /** * Represents the resource in the given object class. Note that the client * preferences will be automatically adjusted, but only for this request. If * you want to change them once for all, you can use the * {@link #getClientInfo()} method.
    *
    * If a success status is not returned, then a resource exception is thrown. * * @param * The expected type for the response entity. * @param resultClass * The expected class for the response entity object. * @return The response entity object. * @throws ResourceException * @see HTTP * GET method */ public T get(Class resultClass) throws ResourceException { return handle(Method.GET, resultClass); } /** * Represents the resource using a given media type. Note that the client * preferences will be automatically adjusted, but only for this request. If * you want to change them once for all, you can use the * {@link #getClientInfo()} method.
    *
    * If a success status is not returned, then a resource exception is thrown. * * @param mediaType * The media type of the representation to retrieve. * @return The representation matching the given media type. * @throws ResourceException * @see HTTP * GET method */ public Representation get(MediaType mediaType) throws ResourceException { return handle(Method.GET, mediaType); } /** * Returns the child resource defined by its URI relatively to the current * resource. The child resource is defined in the sense of hierarchical * URIs. If the resource URI is not hierarchical, then an exception is * thrown. * * @param relativeRef * The URI reference of the child resource relatively to the * current resource seen as the parent resource. * @return The child resource. * @throws ResourceException */ public ClientResource getChild(Reference relativeRef) throws ResourceException { ClientResource result = null; if ((relativeRef != null) && relativeRef.isRelative()) { result = new ClientResource(this); result.setReference(new Reference(getReference().getTargetRef(), relativeRef).getTargetRef()); } else { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "The child URI is not relative."); } return result; } /** * Wraps the child client resource to proxy calls to the given Java * interface into Restlet method calls. The child resource is defined in the * sense of hierarchical URIs. If the resource URI is not hierarchical, then * an exception is thrown. * * @param * @param relativeRef * The URI reference of the child resource relatively to the * current resource seen as the parent resource. * @param resourceInterface * The annotated resource interface class to proxy. * @return The proxy instance. */ public T getChild(Reference relativeRef, Class resourceInterface) throws ResourceException { T result = null; ClientResource childResource = getChild(relativeRef); if (childResource != null) { result = childResource.wrap(resourceInterface); } return result; } /** * Returns the child resource defined by its URI relatively to the current * resource. The child resource is defined in the sense of hierarchical * URIs. If the resource URI is not hierarchical, then an exception is * thrown. * * @param relativeUri * The URI of the child resource relatively to the current * resource seen as the parent resource. * @return The child resource. * @throws ResourceException */ public ClientResource getChild(String relativeUri) throws ResourceException { return getChild(new Reference(relativeUri)); } /** * Wraps the child client resource to proxy calls to the given Java * interface into Restlet method calls. The child resource is defined in the * sense of hierarchical URIs. If the resource URI is not hierarchical, then * an exception is thrown. * * @param * @param relativeUri * The URI of the child resource relatively to the current * resource seen as the parent resource. * @param resourceInterface * The annotated resource interface class to proxy. * @return The proxy instance. */ public T getChild(String relativeUri, Class resourceInterface) throws ResourceException { return getChild(new Reference(relativeUri), resourceInterface); } /** * Returns the next Restlet. By default, it is the client dispatcher if a * context is available. * * @return The next Restlet or null. */ public Uniform getNext() { Uniform result = this.next; if (result == null) { synchronized (this) { if (result == null) { result = createNext(); if (result != null) { setNext(result); this.nextCreated = true; } } } } return result; } /** * Returns the callback invoked on response reception. If the value is not * null, then the associated request will be executed asynchronously. * * @return The callback invoked on response reception. */ public Uniform getOnResponse() { return getRequest().getOnResponse(); } /** * Returns the callback invoked after sending the request. * * @return The callback invoked after sending the request. */ public Uniform getOnSent() { return getRequest().getOnSent(); } /** * Returns the parent resource. The parent resource is defined in the sense * of hierarchical URIs. If the resource URI is not hierarchical, then an * exception is thrown. * * @return The parent resource. */ public ClientResource getParent() throws ResourceException { ClientResource result = null; if (getReference().isHierarchical()) { result = new ClientResource(this); result.setReference(getReference().getParentRef()); } else { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "The resource URI is not hierarchical."); } return result; } /** * Wraps the parent client resource to proxy calls to the given Java * interface into Restlet method calls. The parent resource is defined in * the sense of hierarchical URIs. If the resource URI is not hierarchical, * then an exception is thrown. * * @param * @param resourceInterface * The annotated resource interface class to proxy. * @return The proxy instance. */ public T getParent(Class resourceInterface) throws ResourceException { T result = null; ClientResource parentResource = getParent(); if (parentResource != null) { result = parentResource.wrap(resourceInterface); } return result; } /** * Returns the number of retry attempts before reporting an error. Default * value is 2. * * @return The number of retry attempts before reporting an error. */ public int getRetryAttempts() { return retryAttempts; } /** * Returns the delay in milliseconds between two retry attempts. Default * value is 2 seconds. * * @return The delay in milliseconds between two retry attempts. */ public long getRetryDelay() { return retryDelay; } /** * Handles the call by invoking the next handler. The prototype request is * retrieved via {@link #getRequest()} and cloned and the response is set as * the latest with {@link #setResponse(Response)}. If necessary the * {@link #setNext(Uniform)} method is called as well with a {@link Client} * instance matching the request protocol. * * @return The optional response entity. * @see #getNext() */ @Override public Representation handle() { Response response = handle(new Request(getRequest())); return (response == null) ? null : response.getEntity(); } /** * Handles the call by cloning the prototype request, setting the method and * entity. * * @param method * The request method to use. * @return The optional response entity. */ private Representation handle(Method method) { return handle(method, (Representation) null, getClientInfo()); } /** * Handles the call by cloning the prototype request, setting the method and * entity. * * @param * The expected type for the response entity. * @param method * The request method to use. * @param resultClass * The expected class for the response entity object. * @return The response entity object. * @throws ResourceException */ private T handle(Method method, Class resultClass) throws ResourceException { return handle(method, null, resultClass); } /** * Handles the call by cloning the prototype request, setting the method and * entity. * * @param method * The request method to use. * @param mediaType * The preferred result media type. * @return The optional response entity. */ private Representation handle(Method method, MediaType mediaType) { return handle(method, (Representation) null, mediaType); } /** * Handles an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param method * The request method to use. * @param entity * The object entity to post. * @param resultClass * The class of the response entity. * @return The response object entity. * @throws ResourceException */ private T handle(Method method, Object entity, Class resultClass) throws ResourceException { T result = null; org.restlet.service.ConverterService cs = getConverterService(); ClientInfo clientInfo = getClientInfo(); if (clientInfo.getAcceptedMediaTypes().isEmpty()) { cs.updatePreferences(clientInfo.getAcceptedMediaTypes(), resultClass); } Representation requestEntity = null; if (entity != null) { List variants = cs.getVariants( entity.getClass(), null); requestEntity = toRepresentation(entity, clientInfo.getPreferredVariant(variants, getMetadataService())); } result = toObject(handle(method, requestEntity, clientInfo), resultClass); return result; } /** * Handles the call by cloning the prototype request, setting the method and * entity. * * @param method * The request method to use. * @param entity * The request entity to set. * @param clientInfo * The client preferences. * @return The optional response entity. */ private Representation handle(Method method, Representation entity, ClientInfo clientInfo) { Representation result = null; // Prepare the request by cloning the prototype request Request request = new Request(getRequest()); request.setMethod(method); request.setEntity(entity); request.setClientInfo(clientInfo); // Actually handle the call Response response = handle(request); if (response.getStatus().isError()) { throw new ResourceException(response.getStatus()); } else { result = (response == null) ? null : response.getEntity(); } return result; } /** * Handles the call by cloning the prototype request, setting the method and * entity. * * @param method * The request method to use. * @param entity * The request entity to set. * @param mediaType * The preferred result media type. * @return The optional response entity. */ private Representation handle(Method method, Representation entity, MediaType mediaType) { return handle(method, entity, new ClientInfo(mediaType)); } /** * Handles the call by invoking the next handler. Then a new response is * created and the {@link #handle(Request, Response)} method is invoked and * the response set as the latest response with * {@link #setResponse(Response)}. * * @param request * The request to handle. * @return The response created. * @see #getNext() */ private Response handle(Request request) { Response response = createResponse(request); Uniform next = getNext(); if (next != null) { // Effectively handle the call handle(request, response, null, 0, next); // Update the last received response. setResponse(response); } else { getLogger() .warning( "Unable to process the call for a client resource. No next Restlet has been provided."); } return response; } /** * Handle the call and follow redirection for safe methods. * * @param request * The request to send. * @param response * The response to update. * @param references * The references that caused a redirection to prevent infinite * loops. * @param retryAttempt * The number of remaining attempts. * @param next * The next handler handling the call. */ private void handle(Request request, Response response, List references, int retryAttempt, Uniform next) { if (next != null) { // Actually handle the call next.handle(request, response); // Check for redirections if (isFollowingRedirects() && response.getStatus().isRedirection() && (response.getLocationRef() != null)) { boolean doRedirection = false; if (request.getMethod().isSafe()) { doRedirection = true; } else { if (Status.REDIRECTION_SEE_OTHER.equals(response .getStatus())) { // The user agent is redirected using the GET method request.setMethod(Method.GET); request.setEntity(null); doRedirection = true; } else if (Status.REDIRECTION_USE_PROXY.equals(response .getStatus())) { doRedirection = true; } } if (doRedirection) { Reference newTargetRef = response.getLocationRef(); if ((references != null) && references.contains(newTargetRef)) { getLogger().warning( "Infinite redirection loop detected with URI: " + newTargetRef); } else if (request.getEntity() != null && !request.isEntityAvailable()) { getLogger() .warning( "Unable to follow the redirection because the request entity isn't available anymore."); } else { if (references == null) { references = new ArrayList(); } // Add to the list of redirection reference // to prevent infinite loops references.add(request.getResourceRef()); request.setResourceRef(newTargetRef); handle(request, response, references, 0, next); } } } else if (isRetryOnError() && response.getStatus().isRecoverableError() && request.getMethod().isIdempotent() && (retryAttempt < getRetryAttempts()) && ((request.getEntity() == null) || request.getEntity() .isAvailable())) { getLogger().log( Level.INFO, "A recoverable error was detected (" + response.getStatus().getCode() + "), attempting again in " + getRetryDelay() + " ms."); // Wait before attempting again if (getRetryDelay() > 0) { try { Thread.sleep(getRetryDelay()); } catch (InterruptedException e) { getLogger().log(Level.FINE, "Retry delay sleep was interrupted", e); } } // Retry the call handle(request, response, references, ++retryAttempt, next); } } } /** * Indicates if there is a next Restlet. * * @return True if there is a next Restlet. */ public boolean hasNext() { return getNext() != null; } /** * Represents the resource using content negotiation to select the best * variant based on the client preferences. This method is identical to * {@link #get()} but doesn't return the actual content of the * representation, only its metadata.
    *
    * Note that the client preferences will be automatically adjusted, but only * for this request. If you want to change them once for all, you can use * the {@link #getClientInfo()} method.
    *
    * If a success status is not returned, then a resource exception is thrown. * * @return The best representation. * @throws ResourceException * @see HTTP * HEAD method */ public Representation head() throws ResourceException { return handle(Method.HEAD); } /** * Represents the resource using a given media type. This method is * identical to {@link #get(MediaType)} but doesn't return the actual * content of the representation, only its metadata.
    *
    * Note that the client preferences will be automatically adjusted, but only * for this request. If you want to change them once for all, you can use * the {@link #getClientInfo()} method.
    *
    * If a success status is not returned, then a resource exception is thrown. * * @param mediaType * The media type of the representation to retrieve. * @return The representation matching the given media type. * @throws ResourceException * @see HTTP * HEAD method */ public Representation head(MediaType mediaType) throws ResourceException { return handle(Method.HEAD, mediaType); } /** * Indicates if redirections are followed. * * @return True if redirections are followed. */ public boolean isFollowingRedirects() { return followingRedirects; } /** * Indicates if idempotent requests should be retried on error. Default * value is true. * * @return True if idempotent requests should be retried on error. */ public boolean isRetryOnError() { return retryOnError; } /** * Describes the resource using content negotiation to select the best * variant based on the client preferences. If a success status is not * returned, then a resource exception is thrown. * * @return The best description. * @throws ResourceException * @see HTTP * OPTIONS method */ public Representation options() throws ResourceException { return handle(Method.OPTIONS); } /** * Describes the resource using a given media type. If a success status is * not returned, then a resource exception is thrown. * * @param * The expected type for the response entity. * @param resultClass * The expected class for the response entity object. * @return The response entity object. * @throws ResourceException * @see HTTP * OPTIONS method */ public T options(Class resultClass) throws ResourceException { return handle(Method.OPTIONS, resultClass); } /** * Describes the resource using a given media type. If a success status is * not returned, then a resource exception is thrown. * * @param mediaType * The media type of the representation to retrieve. * @return The matched description or null. * @throws ResourceException * @see HTTP * OPTIONS method */ public Representation options(MediaType mediaType) throws ResourceException { return handle(Method.OPTIONS, mediaType); } /** * Posts an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param entity * The object entity to post. * @return The optional result entity. * @throws ResourceException * @see HTTP * POST method */ public Representation post(Object entity) throws ResourceException { return post(toRepresentation(entity, null)); } /** * Posts an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param entity * The object entity to post. * @param resultClass * The class of the response entity. * @return The response object entity. * @throws ResourceException * @see HTTP * POST method */ public T post(Object entity, Class resultClass) throws ResourceException { return handle(Method.POST, entity, resultClass); } /** * Posts an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param entity * The object entity to post. * @param mediaType * The media type of the representation to retrieve. * @return The response object entity. * @throws ResourceException * @see HTTP * POST method */ public Representation post(Object entity, MediaType mediaType) throws ResourceException { return handle(Method.POST, toRepresentation(entity, null), mediaType); } /** * Posts a representation. If a success status is not returned, then a * resource exception is thrown. * * @param entity * The posted entity. * @return The optional result entity. * @throws ResourceException * @see HTTP * POST method */ public Representation post(Representation entity) throws ResourceException { return handle(Method.POST, entity, getClientInfo()); } /** * Puts an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param entity * The object entity to put. * @return The optional result entity. * @throws ResourceException * @see HTTP * PUT method */ public Representation put(Object entity) throws ResourceException { return put(toRepresentation(entity, null)); } /** * Puts an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param entity * The object entity to put. * @param resultClass * The class of the response entity. * @return The response object entity. * @throws ResourceException * @see HTTP * PUT method */ public T put(Object entity, Class resultClass) throws ResourceException { return handle(Method.PUT, entity, resultClass); } /** * Puts an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param entity * The object entity to post. * @param mediaType * The media type of the representation to retrieve. * @return The response object entity. * @throws ResourceException * @see HTTP * PUT method */ public Representation put(Object entity, MediaType mediaType) throws ResourceException { return handle(Method.PUT, toRepresentation(entity, null), mediaType); } /** * Creates or updates a resource with the given representation as new state * to be stored. If a success status is not returned, then a resource * exception is thrown. * * @param entity * The request entity to store. * @return The optional result entity. * @throws ResourceException * @see HTTP * PUT method */ public Representation put(Representation entity) throws ResourceException { return handle(Method.PUT, entity, getClientInfo()); } /** * Sets the authentication response sent by a client to an origin server. * * @param challengeResponse * The authentication response sent by a client to an origin * server. * @see Request#setChallengeResponse(ChallengeResponse) */ public void setChallengeResponse(ChallengeResponse challengeResponse) { getRequest().setChallengeResponse(challengeResponse); } /** * Sets the authentication response sent by a client to an origin server * given a scheme, identifier and secret. * * @param scheme * The challenge scheme. * @param identifier * The user identifier, such as a login name or an access key. * @param secret * The user secret, such as a password or a secret key. */ public void setChallengeResponse(ChallengeScheme scheme, final String identifier, String secret) { setChallengeResponse(new ChallengeResponse(scheme, identifier, secret)); } /** * Sets the client-specific information. * * @param clientInfo * The client-specific information. * @see Request#setClientInfo(ClientInfo) */ public void setClientInfo(ClientInfo clientInfo) { getRequest().setClientInfo(clientInfo); } /** * Sets the conditions applying to this request. * * @param conditions * The conditions applying to this request. * @see Request#setConditions(Conditions) */ public void setConditions(Conditions conditions) { getRequest().setConditions(conditions); } /** * Sets the cookies provided by the client. * * @param cookies * The cookies provided by the client. * @see Request#setCookies(Series) */ public void setCookies(Series cookies) { getRequest().setCookies(cookies); } /** * Indicates if redirections are followed. * * @param followingRedirects * True if redirections are followed. */ public void setFollowingRedirects(boolean followingRedirects) { this.followingRedirects = followingRedirects; } /** * Sets the host reference. * * @param hostRef * The host reference. * @see Request#setHostRef(Reference) */ public void setHostRef(Reference hostRef) { getRequest().setHostRef(hostRef); } /** * Sets the host reference using an URI string. * * @param hostUri * The host URI. * @see Request#setHostRef(String) */ public void setHostRef(String hostUri) { getRequest().setHostRef(hostUri); } /** * Sets the method called. * * @param method * The method called. * @see Request#setMethod(Method) */ public void setMethod(Method method) { getRequest().setMethod(method); } /** * Sets the next handler such as a Restlet or a Filter. * * In addition, this method will set the context of the next Restlet if it * is null by passing a reference to its own context. * * @param next * The next handler. */ public void setNext(org.restlet.Uniform next) { if (next instanceof Restlet) { Restlet nextRestlet = (Restlet) next; if (nextRestlet.getContext() == null) { nextRestlet.setContext(getContext()); } } this.next = next; // If true, it must be updated after calling this method this.nextCreated = false; } /** * Sets the callback invoked on response reception. If the value is not * null, then the associated request will be executed asynchronously. * * @param onResponseCallback * The callback invoked on response reception. */ public void setOnResponse(Uniform onResponseCallback) { getRequest().setOnResponse(onResponseCallback); } /** * Sets the callback invoked after sending the request. * * @param onSentCallback * The callback invoked after sending the request. */ public void setOnSent(Uniform onSentCallback) { getRequest().setOnSent(onSentCallback); } /** * Sets the original reference requested by the client. * * @param originalRef * The original reference. * @see Request#setOriginalRef(Reference) */ public void setOriginalRef(Reference originalRef) { getRequest().setOriginalRef(originalRef); } /** * Sets the protocol used or to be used. * * @param protocol * The protocol used or to be used. */ public void setProtocol(Protocol protocol) { getRequest().setProtocol(protocol); } /** * Sets the ranges to return from the target resource's representation. * * @param ranges * The ranges. * @see Request#setRanges(List) */ public void setRanges(List ranges) { getRequest().setRanges(ranges); } /** * Sets the resource's reference. If the reference is relative, it will be * resolved as an absolute reference. Also, the context's base reference * will be reset. Finally, the reference will be normalized to ensure a * consistent handling of the call. * * @param reference * The resource reference. * @see Request#setResourceRef(Reference) */ public void setReference(Reference reference) { getRequest().setResourceRef(reference); } /** * Sets the resource's reference using an URI string. Note that the URI can * be either absolute or relative to the context's base reference. * * @param uri * The resource URI. * @see Request#setResourceRef(String) */ public void setReference(String uri) { getRequest().setResourceRef(uri); } /** * Sets the referrer reference if available. * * @param referrerRef * The referrer reference. * @see Request#setReferrerRef(Reference) */ public void setReferrerRef(Reference referrerRef) { getRequest().setReferrerRef(referrerRef); } /** * Sets the referrer reference if available using an URI string. * * @param referrerUri * The referrer URI. * @see Request#setReferrerRef(String) */ public void setReferrerRef(String referrerUri) { getRequest().setReferrerRef(referrerUri); } /** * Sets the number of retry attempts before reporting an error. * * @param retryAttempts * The number of retry attempts before reporting an error. */ public void setRetryAttempts(int retryAttempts) { this.retryAttempts = retryAttempts; } /** * Sets the delay in milliseconds between two retry attempts. The default * value is two seconds. * * @param retryDelay * The delay in milliseconds between two retry attempts. */ public void setRetryDelay(long retryDelay) { this.retryDelay = retryDelay; } /** * Indicates if idempotent requests should be retried on error. * * @param retryOnError * True if idempotent requests should be retried on error. */ public void setRetryOnError(boolean retryOnError) { this.retryOnError = retryOnError; } /** * Wraps the client resource to proxy calls to the given Java interface into * Restlet method calls. * * @param * @param resourceInterface * The annotated resource interface class to proxy. * @return The proxy instance. */ @SuppressWarnings("unchecked") public T wrap(Class resourceInterface) { T result = null; // Introspect the interface for Restlet annotations final List annotations = org.restlet.engine.resource.AnnotationUtils .getAnnotations(resourceInterface); final ClientResource clientResource = this; // Create the client resource proxy java.lang.reflect.InvocationHandler h = new java.lang.reflect.InvocationHandler() { @SuppressWarnings("rawtypes") public Object invoke(Object proxy, java.lang.reflect.Method javaMethod, Object[] args) throws Throwable { Object result = null; if (javaMethod.equals(Object.class.getMethod("toString"))) { // Help debug result = "ClientProxy for resource: " + clientResource; } else if (javaMethod.equals(ClientProxy.class .getMethod("getClientResource"))) { result = clientResource; } else { org.restlet.engine.resource.AnnotationInfo annotation = org.restlet.engine.resource.AnnotationUtils .getAnnotation(annotations, javaMethod); if (annotation != null) { Representation requestEntity = null; boolean isSynchronous = true; if ((args != null) && args.length > 0) { // Checks if the user has defined its own // callback. for (int i = 0; i < args.length; i++) { Object o = args[i]; if (o == null) { requestEntity = null; } else if (Result.class.isAssignableFrom(o .getClass())) { // Asynchronous mode where a callback // object is to be called. isSynchronous = false; // Get the kind of result expected. final Result rCallback = (Result) o; java.lang.reflect.Type[] genericParameterTypes = javaMethod .getGenericParameterTypes(); java.lang.reflect.Type genericParameterType = genericParameterTypes[i]; java.lang.reflect.ParameterizedType parameterizedType = (genericParameterType instanceof java.lang.reflect.ParameterizedType) ? (java.lang.reflect.ParameterizedType) genericParameterType : null; final Class actualType = (parameterizedType .getActualTypeArguments()[0] instanceof Class) ? (Class) parameterizedType .getActualTypeArguments()[0] : null; // Define the callback Uniform callback = new Uniform() { public void handle(Request request, Response response) { if (response.getStatus().isError()) { rCallback .onFailure(new ResourceException( response.getStatus())); } else { if (actualType != null) { rCallback .onSuccess(toObject( response.getEntity(), actualType)); } else { rCallback.onSuccess(null); } } } }; setOnResponse(callback); } else { requestEntity = toRepresentation(args[i], null); } } } // Clone the prototype request Request request = createRequest(getRequest()); // The Java method was annotated request.setMethod(annotation.getRestletMethod()); // Set the entity request.setEntity(requestEntity); // Updates the client preferences List responseVariants = annotation .getResponseVariants(getMetadataService(), getConverterService()); if (responseVariants != null) { request.setClientInfo(new ClientInfo( responseVariants)); } // Effectively handle the call Response response = handle(request); // Handle the response if (isSynchronous) { if (response.getStatus().isError()) { throw new ResourceException( response.getStatus()); } if (!annotation.getJavaOutputType().equals( void.class)) { result = toObject((response == null ? null : response.getEntity()), annotation.getJavaOutputType()); } } } } return result; } }; // Instantiate our dynamic proxy result = (T) java.lang.reflect.Proxy.newProxyInstance( org.restlet.engine.Engine.getInstance().getClassLoader(), new Class[] { ClientProxy.class, resourceInterface }, h); return result; } } restlet-2.0.14/org.restlet/src/org/restlet/resource/Delete.java0000664000175000017500000000512111757206346025152 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; import org.restlet.service.MetadataService; /** * Annotation for methods that remove representations. Its semantics is * equivalent to an HTTP DELETE method.
    *
    * Example: * *
     * @Delete()
     * public void removeAll();
     * 
     * @Delete("xml|json")
     * public Representation delete();
     * 
    * * @author Jerome Louvel */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("DELETE") public @interface Delete { /** * Specifies the media type extension of the response entity. If several * media types are supported, their extension can be specified separated by * "|" characters. Note that this isn't the full MIME type value, just the * extension name declared in {@link MetadataService}. For a list of all * predefined extensions, please check * {@link MetadataService#addCommonExtensions()}. New extension can be * registered using * {@link MetadataService#addExtension(String, org.restlet.data.Metadata)} * method. * * @return The result media types. */ String value() default ""; } restlet-2.0.14/org.restlet/src/org/restlet/resource/Result.java0000664000175000017500000000352011757206346025227 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; /** * Callback interface for asynchronous tasks. * * @param * The class of the result object returned in case of success. * @author Jerome Louvel */ public interface Result { /** * Method called back by the associated object when a failure is detected. * * @param caught * The exception or error caught. */ void onFailure(Throwable caught); /** * Method called back by the associated object in case of success. * * @param result * The result object. */ void onSuccess(T result); } restlet-2.0.14/org.restlet/src/org/restlet/resource/ClientProxy.java0000664000175000017500000000341611757206346026235 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; /** * Marker interface for RESTful resource proxies. This allows you to retrieve * and manipulate the underlying {@link ClientResource} of a dynamic client * proxy generated by the {@link ClientResource#create(String, Class)} method * for example, or by {@link ClientResource#getChild(String, Class)}. * * @author Jerome Louvel */ public interface ClientProxy { /** * Returns the wrapped client resource. * * @return The wrapped client resource. */ public ClientResource getClientResource(); } restlet-2.0.14/org.restlet/src/org/restlet/resource/Options.java0000664000175000017500000000513611757206346025411 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; import org.restlet.service.MetadataService; /** * Annotation for methods that describe a resource. Its semantics is equivalent * to an HTTP OPTIONS method.
    *
    * Example: * *
     * @Options
     * public ApplicationInfo describe();
     * 
     * @Options("wadl|html")
     * public Representation describe();
     * 
    * * @author Jerome Louvel */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("OPTIONS") public @interface Options { /** * Specifies the media type extension of the response entity. If several * media types are supported, their extension can be specified separated by * "|" characters. Note that this isn't the full MIME type value, just the * extension name declared in {@link MetadataService}. For a list of all * predefined extensions, please check * {@link MetadataService#addCommonExtensions()}. New extension can be * registered using * {@link MetadataService#addExtension(String, org.restlet.data.Metadata)} * method. * * @return The result media types. */ String value() default ""; } restlet-2.0.14/org.restlet/src/org/restlet/resource/Post.java0000664000175000017500000000623111757206346024700 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; import org.restlet.service.MetadataService; /** * Annotation for methods that accept submitted representations. Its semantics * is equivalent to an HTTP POST method. Note that your method must have one * input parameter if you want it to be selected for requests containing an * entity.
    *
    * Example: * *
     * @Post
     * public MyOutputBean accept(MyInputBean input);
     * 
     * @Post("json")
     * public String acceptJson(String value);
     * 
     * @Post("xml|json:xml|json")
     * public Representation accept(Representation xmlValue);
     * 
    * * @author Jerome Louvel */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("POST") public @interface Post { /** * Specifies the media type of the request and response entities as * extensions. If only one extension is provided, the extension applies to * both request and response entities. If two extensions are provided, * separated by a colon, then the first one is for the request entity and * the second one for the response entity.
    *
    * If several media types are supported, their extension can be specified * separated by "|" characters. Note that this isn't the full MIME type * value, just the extension name declared in {@link MetadataService}. For a * list of all predefined extensions, please check * {@link MetadataService#addCommonExtensions()}. New extension can be * registered using * {@link MetadataService#addExtension(String, org.restlet.data.Metadata)} * method. * * @return The media types of request and/or response entities. */ String value() default ""; } restlet-2.0.14/org.restlet/src/org/restlet/resource/Put.java0000664000175000017500000000621111757206346024521 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; import org.restlet.service.MetadataService; /** * Annotation for methods that store submitted representations. Its semantics is * equivalent to an HTTP PUT method. Note that your method must have one input * parameter if you want it to be selected for requests containing an entity.
    *
    * Example: * *
     * @Put
     * public MyOutputBean store(MyInputBean input);
     * 
     * @Put("json")
     * public String storeJson(String value);
     * 
     * @Put("json|xml:xml|json")
     * public Representation store(Representation value);
     * 
    * * @author Jerome Louvel */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("PUT") public @interface Put { /** * Specifies the media type of the request and response entities as * extensions. If only one extension is provided, the extension applies to * both request and response entities. If two extensions are provided, * separated by a colon, then the first one is for the request entity and * the second one for the response entity.
    *
    * If several media types are supported, their extension can be specified * separated by "|" characters. Note that this isn't the full MIME type * value, just the extension name declared in {@link MetadataService}. For a * list of all predefined extensions, please check * {@link MetadataService#addCommonExtensions()}. New extension can be * registered using * {@link MetadataService#addExtension(String, org.restlet.data.Metadata)} * method. * * @return The media types of request and/or response entities. */ String value() default ""; } restlet-2.0.14/org.restlet/src/org/restlet/resource/Resource.java0000664000175000017500000007137211757206346025552 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.util.ArrayList; import java.util.List; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Dimension; import org.restlet.data.Parameter; import org.restlet.data.ReferenceList; import org.restlet.data.Status; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.util.Series; /** * Intended conceptual target of a hypertext reference. "Any information that * can be named can be a resource: a document or image, a temporal service (e.g. * "today's weather in Los Angeles"), a collection of other resources, a * non-virtual object (e.g. a person), and so on. In other words, any concept * that might be the target of an author's hypertext reference must fit within * the definition of a resource. The only thing that is required to be static * for a resource is the semantics of the mapping, since the semantics is what * distinguishes one resource from another." Roy T. Fielding
    *
    * Another definition adapted from the URI standard (RFC 3986): a resource is * the conceptual mapping to a representation (also known as entity) or set of * representations, not necessarily the representation which corresponds to that * mapping at any particular instance in time. Thus, a resource can remain * constant even when its content (the representations to which it currently * corresponds) changes over time, provided that the conceptual mapping is not * changed in the process. In addition, a resource is always identified by a * URI.
    *
    * This is the point where the RESTful view of your Web application can be * integrated with your domain objects. Those domain objects can be implemented * using any technology, relational databases, object databases, transactional * components like EJB, etc.
    *
    * You just have to extend this class to override the REST methods you want to * support like {@link #acceptRepresentation(Representation)} for POST * processing, {@link #storeRepresentation(Representation)} for PUT processing * or {@link #removeRepresentations()} for DELETE processing.
    *
    * The common GET method is supported by the modifiable "variants" list property * and the {@link #represent(Variant)} method. This allows an easy and cheap * declaration of the available variants, in the constructor for example. Then * the creation of costly representations is delegated to the * {@link #represent(Variant)} method when actually needed.
    *
    * Concurrency note: typically created by Routers, Resource instances are the * final handlers of requests. Unlike the other processors in the Restlet chain, * a Resource instance is not reused by several calls and is only invoked by one * thread. Therefore, it doesn't have to be thread-safe.
    * * @see Source * dissertation * @see org.restlet.representation.Representation * @see org.restlet.resource.Finder * @author Jerome Louvel * @author Thierry Boileau * @author Konstantin Laufer (laufer@cs.luc.edu) * @deprecated Use the new {@link ServerResource} class instead. */ @Deprecated public class Resource extends Handler { /** Indicates if the resource is actually available. */ private volatile boolean available; /** * Indicates if the representations can be modified via the * {@link #handlePost()}, the {@link #handlePut()} or the * {@link #handleDelete()} methods. */ private volatile boolean modifiable; /** Indicates if the best content is automatically negotiated. */ private volatile boolean negotiateContent; /** * Indicates if the representations can be read via the {@link #handleGet()} * method. */ private volatile boolean readable; /** The modifiable list of variants. */ private volatile List variants; /** * Initializer block to ensure that the basic properties of the Resource are * initialized consistently across constructors. */ { this.available = true; this.modifiable = false; this.negotiateContent = true; this.readable = true; this.variants = null; } /** * Special constructor used by IoC frameworks. Note that the init() method * MUST be invoked right after the creation of the handler in order to keep * a behavior consistent with the normal three arguments constructor. */ public Resource() { } /** * Normal constructor. This constructor will invoke the parent constructor * by default. * * @param context * The parent context. * @param request * The request to handle. * @param response * The response to return. */ public Resource(Context context, Request request, Response response) { super(context, request, response); } /** * Accepts and processes a representation posted to the resource. The * default behavior is to set the response status to * {@link Status#SERVER_ERROR_INTERNAL}.
    *
    * This is the higher-level method that let you process POST requests. * * @param entity * The posted entity. */ public void acceptRepresentation(Representation entity) throws ResourceException { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Indicates if DELETE calls are allowed by checking the "modifiable" * property. * * @return True if the method is allowed. */ @Override public boolean allowDelete() { return isModifiable(); } /** * Indicates if GET calls are allowed by checking the "readable" property. * * @return True if the method is allowed. */ @Override public boolean allowGet() { return isReadable(); } /** * Indicates if POST calls are allowed by checking the "modifiable" * property. * * @return True if the method is allowed. */ @Override public boolean allowPost() { return isModifiable(); } /** * Indicates if PUT calls are allowed by checking the "modifiable" property. * * @return True if the method is allowed. */ @Override public boolean allowPut() { return isModifiable(); } /** * Returns the preferred variant according to the client preferences * specified in the request. * * @return The preferred variant. */ public Variant getPreferredVariant() { Variant result = null; final List variants = getVariants(); if ((variants != null) && (!variants.isEmpty())) { // Compute the preferred variant. Get the default language // preference from the Application (if any). result = getRequest().getClientInfo().getPreferredVariant( variants, (getApplication() == null) ? null : getApplication() .getMetadataService()); } return result; } /** * Returns a full representation for a given variant previously returned via * the getVariants() method. The default implementation directly returns the * variant in case the variants are already full representations. In all * other cases, you will need to override this method in order to provide * your own implementation.
    *
    * * This method is very useful for content negotiation when it is too costly * to initialize all the potential representations. It allows a resource to * simply expose the available variants via the getVariants() method and to * actually server the one selected via this method. * * @param variant * The variant whose full representation must be returned. * @return The full representation for the variant. * @see #getVariants() */ private Representation getRepresentation(Variant variant) { Representation result = null; try { result = represent(variant); } catch (ResourceException re) { getResponse().setStatus(re.getStatus()); } return result; } /** * Returns the modifiable list of variants. Creates a new instance if no one * has been set. A variant can be a purely descriptive representation, with * no actual content that can be served. It can also be a full * representation in case a resource has only one variant or if the * initialization cost is very low.
    *
    * Note that the order in which the variants are inserted in the list * matters. For example, if the client has no preference defined, or if the * acceptable variants have the same quality level for the client, the first * acceptable variant in the list will be returned.
    *
    * It is recommended to not override this method and to simply use it at * construction time to initialize the list of available variants. * Overriding it may reconstruct the list for each call which can be * expensive. * * @return The list of variants. * @see #represent(Variant) */ public List getVariants() { // Lazy initialization with double-check. List v = this.variants; if (v == null) { synchronized (this) { v = this.variants; if (v == null) { this.variants = v = new ArrayList(); } } } return v; } /** * Handles a DELETE call by invoking the {@link #removeRepresentations()} * method. It also automatically support conditional DELETEs. */ @Override public void handleDelete() { boolean canDelete = true; if (getRequest().getConditions().hasSome()) { Variant preferredVariant = null; if (isNegotiateContent()) { preferredVariant = getPreferredVariant(); } else { final List variants = getVariants(); if (variants.size() == 1) { preferredVariant = variants.get(0); } else { getResponse().setStatus( Status.CLIENT_ERROR_PRECONDITION_FAILED); canDelete = false; } } // The conditions have to be checked // even if there is no preferred variant. if (canDelete) { final Status status = getRequest().getConditions().getStatus( getRequest().getMethod(), getRepresentation(preferredVariant)); if (status != null) { getResponse().setStatus(status); canDelete = false; } } } if (canDelete) { try { removeRepresentations(); } catch (ResourceException re) { getResponse().setStatus(re.getStatus()); } } } /** * Handles a GET call by automatically returning the best representation * available. The content negotiation is automatically supported based on * the client's preferences available in the request. This feature can be * turned off using the "negotiateContent" property.
    *
    * If the resource's "available" property is set to false, the method * immediately returns with a {@link Status#CLIENT_ERROR_NOT_FOUND} status.
    *
    * The negotiated representation is obtained by calling the * {@link #getPreferredVariant()}. If a variant is successfully selected, * then the {@link #represent(Variant)} method is called to get the actual * representation corresponding to the metadata in the variant.
    *
    * If no variant matching the client preferences is available, the response * status is set to {@link Status#CLIENT_ERROR_NOT_ACCEPTABLE} and the list * of available representations is returned in the response entity as a * textual list of URIs (only if the variants have an identifier properly * set).
    *
    * If the content negotiation is turned off and only one variant is defined * in the "variants" property, then its representation is returned by * calling the {@link #represent(Variant)} method. If several variants are * available, then the list of available representations is returned in the * response entity as a textual list of URIs (only if the variants have an * identifier properly set).
    *
    * If no variant is defined in the "variants" property, the response status * is set to {@link Status#CLIENT_ERROR_NOT_FOUND}.
    * If it is disabled and multiple variants are available for the target * resource, then a 300 (Multiple Choices) status will be returned with the * list of variants URI if available. Conditional GETs are also * automatically supported. */ @Override public void handleGet() { if (!isAvailable()) { // Resource not existing or not available to the current client getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { // The variant that may need to meet the request conditions Representation selectedRepresentation = null; final List variants = getVariants(); if ((variants == null) || (variants.isEmpty())) { // Resource not found getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); getLogger() .warning( "A resource should normally have at least one variant added by calling getVariants().add() in the constructor. Check your resource \"" + getRequest().getResourceRef() + "\"."); } else if (isNegotiateContent()) { final Variant preferredVariant = getPreferredVariant(); if (preferredVariant == null) { // No variant was found matching the client preferences getResponse().setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE); // The list of all variants is transmitted to the client final ReferenceList refs = new ReferenceList( variants.size()); for (final Variant variant : variants) { if (variant.getIdentifier() != null) { refs.add(variant.getIdentifier()); } } getResponse().setEntity(refs.getTextRepresentation()); } else { // Set the variant dimensions used for content negotiation getResponse().getDimensions().clear(); getResponse().getDimensions().add(Dimension.CHARACTER_SET); getResponse().getDimensions().add(Dimension.ENCODING); getResponse().getDimensions().add(Dimension.LANGUAGE); getResponse().getDimensions().add(Dimension.MEDIA_TYPE); // Set the negotiated representation as response entity getResponse() .setEntity(getRepresentation(preferredVariant)); } selectedRepresentation = getResponse().getEntity(); } else { if (variants.size() == 1) { getResponse().setEntity(getRepresentation(variants.get(0))); selectedRepresentation = getResponse().getEntity(); } else { final ReferenceList variantRefs = new ReferenceList(); for (final Variant variant : variants) { if (variant.getIdentifier() != null) { variantRefs.add(variant.getIdentifier()); } else { getLogger() .warning( "A resource with multiple variants should provide an identifier for each variant when content negotiation is turned off"); } } if (variantRefs.size() > 0) { // Return the list of variants getResponse().setStatus( Status.REDIRECTION_MULTIPLE_CHOICES); getResponse().setEntity( variantRefs.getTextRepresentation()); } else { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } } if (selectedRepresentation == null) { if ((getResponse().getStatus() == null) || (getResponse().getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT .equals(getResponse().getStatus()))) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { // Keep the current status as the developer might prefer a // special status like 'method not authorized'. } } else { // The given representation (even if null) must meet the request // conditions (if any). if (getRequest().getConditions().hasSome()) { final Status status = getRequest().getConditions() .getStatus(getRequest().getMethod(), selectedRepresentation); if (status != null) { getResponse().setStatus(status); getResponse().setEntity(null); } } } } } /** * Handles a POST call by invoking the * {@link #acceptRepresentation(Representation)} method. It also logs a * trace if there is no entity posted. */ @Override public void handlePost() { if (!getRequest().isEntityAvailable()) { getLogger() .fine("POST request received without any entity. Continuing processing."); } try { acceptRepresentation(getRequest().getEntity()); } catch (ResourceException re) { getResponse().setStatus(re.getStatus()); } } /** * Handles a PUT call by invoking the * {@link #storeRepresentation(Representation)} method. It also handles * conditional PUTs and forbids partial PUTs as they are not supported yet. * Finally, it prevents PUT with no entity by setting the response status to * {@link Status#CLIENT_ERROR_BAD_REQUEST} following the HTTP * specifications. */ @SuppressWarnings("unchecked") @Override public void handlePut() { boolean canPut = true; if (getRequest().getConditions().hasSome()) { Variant preferredVariant = null; if (isNegotiateContent()) { preferredVariant = getPreferredVariant(); } else { final List variants = getVariants(); if (variants.size() == 1) { preferredVariant = variants.get(0); } else { getResponse().setStatus( Status.CLIENT_ERROR_PRECONDITION_FAILED); canPut = false; } } // The conditions have to be checked // even if there is no preferred variant. if (canPut) { final Status status = getRequest().getConditions().getStatus( getRequest().getMethod(), getRepresentation(preferredVariant)); if (status != null) { getResponse().setStatus(status); canPut = false; } } } if (canPut) { // Check the Content-Range HTTP Header // in order to prevent usage of partial PUTs Object oHeaders = getRequest().getAttributes().get( HeaderConstants.ATTRIBUTE_HEADERS); if (oHeaders != null) { Series headers = (Series) oHeaders; if (headers.getFirst("Content-Range", true) != null) { getResponse() .setStatus( new Status( Status.SERVER_ERROR_NOT_IMPLEMENTED, "The Content-Range header is not understood")); canPut = false; } } } if (canPut) { try { storeRepresentation(getRequest().getEntity()); } catch (ResourceException re) { getResponse().setStatus(re.getStatus()); } // HTTP specification says that PUT may return // the list of allowed methods updateAllowedMethods(); } } /** * Initialize the resource with its context. If you override this method, * make sure that you don't forget to call super.init() first, otherwise * your Resource won't behave properly. * * @param context * The parent context. * @param request * The request to handle. * @param response * The response to return. */ @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); } /** * Indicates if the resource is actually available. By default this property * is true but it can be set to false if the resource doesn't exist at all * or if it isn't visible to a specific client. The {@link #handleGet()} * method will set the response's status to * {@link Status#CLIENT_ERROR_NOT_FOUND} if this property is false. * * @return True if the resource is available. */ public boolean isAvailable() { return this.available; } /** * Indicates if the representations can be modified via the * {@link #handlePost()}, the {@link #handlePut()} or the * {@link #handleDelete()} methods. * * @return True if representations can be modified. */ public boolean isModifiable() { return this.modifiable; } /** * Indicates if the best content is automatically negotiated. Default value * is true. * * @return True if the best content is automatically negotiated. */ public boolean isNegotiateContent() { return this.negotiateContent; } /** * Indicates if the representations can be read via the {@link #handleGet()} * method. * * @return True if the representations can be read. */ public boolean isReadable() { return this.readable; } /** * Removes all the representations of the resource and effectively the * resource itself. The default behavior is to set the response status to * {@link Status#SERVER_ERROR_INTERNAL}.
    *
    * This is the higher-level method that let you process DELETE requests. */ public void removeRepresentations() throws ResourceException { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Returns the preferred representation according to the client preferences * specified in the request. By default it calls the * {@link #represent(Variant)} method with the preferred variant returned by * {@link #getPreferredVariant()}. * * @return The preferred representation. * @see #getPreferredVariant() * @throws ResourceException */ public Representation represent() throws ResourceException { return represent(getPreferredVariant()); } /** * Returns a full representation for a given variant previously returned via * the getVariants() method. The default implementation directly returns the * variant in case the variants are already full representations. In all * other cases, you will need to override this method in order to provide * your own implementation.
    *
    * * This method is very useful for content negotiation when it is too costly * to initialize all the potential representations. It allows a resource to * simply expose the available variants via the getVariants() method and to * actually server the one selected via this method. * * @param variant * The variant whose full representation must be returned. * @return The full representation for the variant. * @see #getVariants() */ public Representation represent(Variant variant) throws ResourceException { Representation result = null; if (variant instanceof Representation) { result = (Representation) variant; } return result; } /** * Indicates if the resource is actually available. By default this property * is true but it can be set to false if the resource doesn't exist at all * or if it isn't visible to a specific client. The {@link #handleGet()} * method will set the response's status to * {@link Status#CLIENT_ERROR_NOT_FOUND} if this property is false. * * @param available * True if the resource is actually available. */ public void setAvailable(boolean available) { this.available = available; } /** * Indicates if the representations can be modified via the * {@link #handlePost()}, the {@link #handlePut()} or the * {@link #handleDelete()} methods. * * @param modifiable * Indicates if the representations can be modified. */ public void setModifiable(boolean modifiable) { this.modifiable = modifiable; } /** * Indicates if the returned representation is automatically negotiated. * Default value is true. * * @param negotiateContent * True if content negotiation is enabled. */ public void setNegotiateContent(boolean negotiateContent) { this.negotiateContent = negotiateContent; } /** * Indicates if the representations can be read via the {@link #handleGet()} * method. * * @param readable * Indicates if the representations can be read. */ public void setReadable(boolean readable) { this.readable = readable; } /** * Sets the modifiable list of variants. * * @param variants * The modifiable list of variants. */ public void setVariants(List variants) { this.variants = variants; } /** * Stores a representation put to the resource and replaces all existing * representations of the resource. If the resource doesn't exist yet, it * should create it and use the entity as its initial representation. The * default behavior is to set the response status to * {@link Status#SERVER_ERROR_INTERNAL}.
    *
    * This is the higher-level method that let you process PUT requests. * * @param entity */ public void storeRepresentation(Representation entity) throws ResourceException { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } } restlet-2.0.14/org.restlet/src/org/restlet/resource/Finder.java0000664000175000017500000005065411757206350025165 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Method; import org.restlet.data.Status; /** * Restlet that can find the target server resource that will effectively handle * incoming calls. By default, based on a given {@link ServerResource} (or the * now deprecated {@link Handler}) subclass available via the * {@link #getTargetClass()} method, it automatically instantiates for each * incoming call the target resource class using its default constructor and * invoking the {@link ServerResource#init(Context, Request, Response)} method.
    *
    * Once the target has been created, the call is automatically dispatched to the * {@link ServerResource#handle()} method (or for {@link Handler} subclasses to * the handle*() method (where the '*' character corresponds to the method name) * if the corresponding allow*() method returns true).
    *
    * Once the call is handled, the {@link ServerResource#release()} method is * invoked to permit clean-up actions.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class Finder extends Restlet { /** * Creates a new finder instance based on the "targetClass" property. * * @param targetClass * The target Resource class to attach. * @param finderClass * The optional finder class to instantiate. * @param logger * The logger. * @return The new finder instance. */ @SuppressWarnings("deprecation") public static Finder createFinder(Class targetClass, Class finderClass, Context context, Logger logger) { Finder result = null; if (Resource.class.isAssignableFrom(targetClass) || ServerResource.class.isAssignableFrom(targetClass)) { if (finderClass != null) { try { final Constructor constructor = finderClass .getConstructor(Context.class, Class.class); if (constructor != null) { result = constructor.newInstance(context, targetClass); } } catch (Exception e) { if (logger != null) { logger.log(Level.WARNING, "Exception while instantiating the finder.", e); } } } else { result = new Finder(context, targetClass); } } else { if (logger != null) { logger .log( Level.WARNING, "Cannot create a Finder for the given target class, since it is neither a subclass of Resource nor a subclass of ServerResource."); } } return result; } /** Target {@link Handler} or {@link ServerResource} subclass. */ private volatile Class targetClass; /** * Constructor. */ public Finder() { this(null); } /** * Constructor. * * @param context * The context. */ public Finder(Context context) { super(context); this.targetClass = null; } /** * Constructor. * * @param context * The context. * @param targetClass * The target handler class. It must be either a subclass of * {@link Handler} or of {@link ServerResource}. */ public Finder(Context context, Class targetClass) { super(context); this.targetClass = targetClass; } /** * Indicates if a method is allowed on a target handler. * * @param method * The method to test. * @param target * The target handler. * @return True if a method is allowed on a target handler. */ @SuppressWarnings("deprecation") private boolean allow(Method method, Handler target) { boolean result = false; if (target != null) { if (method.equals(Method.GET)) { result = target.allowGet(); } else if (method.equals(Method.POST)) { result = target.allowPost(); } else if (method.equals(Method.PUT)) { result = target.allowPut(); } else if (method.equals(Method.DELETE)) { result = target.allowDelete(); } else if (method.equals(Method.HEAD)) { result = target.allowHead(); } else if (method.equals(Method.OPTIONS)) { result = target.allowOptions(); } else { // Dynamically introspect the target handler to detect a // matching "allow" method. final java.lang.reflect.Method allowMethod = getAllowMethod( method, target); if (allowMethod != null) { result = (Boolean) invoke(target, allowMethod); } } } return result; } /** * Creates a new instance of a given {@link ServerResource} subclass. Note * that Error and RuntimeException thrown by {@link ServerResource} * constructors are re-thrown by this method. Other exception are caught and * logged. * * @param request * The request to handle. * @param response * The response to update. * @return The created handler or null. */ public ServerResource create(Class targetClass, Request request, Response response) { ServerResource result = null; if (targetClass != null) { try { // Invoke the default constructor result = targetClass.newInstance(); } catch (Exception e) { getLogger() .log( Level.WARNING, "Exception while instantiating the target server resource.", e); } } return result; } /** * Creates a new instance of the {@link ServerResource} subclass designated * by the "targetClass" property. The default behavior is to invoke the * {@link #create(Class, Request, Response)} with the "targetClass" property * as a parameter. * * @param request * The request to handle. * @param response * The response to update. * @return The created handler or null. */ @SuppressWarnings("unchecked") public ServerResource create(Request request, Response response) { ServerResource result = null; if ((getTargetClass() != null) && ServerResource.class.isAssignableFrom(getTargetClass())) { result = create((Class) getTargetClass(), request, response); } return result; } /** * Creates a new instance of a given handler class. Note that Error and * RuntimeException thrown by Handler constructors are re-thrown by this * method. Other exception are caught and logged. * * @param request * The request to handle. * @param response * The response to update. * @return The created handler or null. * @deprecated Use {@link #create(Request, Response)} instead. */ @Deprecated protected Handler createTarget(Class targetClass, Request request, Response response) { Handler result = null; if (targetClass != null) { try { Constructor constructor; try { // Invoke the constructor with Context, Request and Response // parameters constructor = targetClass.getConstructor(Context.class, Request.class, Response.class); result = (Handler) constructor.newInstance(getContext(), request, response); } catch (NoSuchMethodException nsme) { // Invoke the default constructor then the init(Context, // Request, Response) method. constructor = targetClass.getConstructor(); if (constructor != null) { result = (Handler) constructor.newInstance(); result.init(getContext(), request, response); } } } catch (InvocationTargetException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } else if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { getLogger() .log( Level.WARNING, "Exception while instantiating the target handler.", e); } } catch (Exception e) { getLogger().log(Level.WARNING, "Exception while instantiating the target handler.", e); } } return result; } /** * Creates a new instance of the handler class designated by the * "targetClass" property. The default behavior is to invoke the * {@link #createTarget(Class, Request, Response)} with the "targetClass" * property as a parameter. * * @param request * The request to handle. * @param response * The response to update. * @return The created handler or null. * @deprecated Use {@link #create(Request, Response)} instead. */ @Deprecated @SuppressWarnings("unchecked") protected Handler createTarget(Request request, Response response) { Handler result = null; if ((getTargetClass() != null) && Handler.class.isAssignableFrom(getTargetClass())) { result = createTarget((Class) getTargetClass(), request, response); } return result; } /** * Finds the target {@link ServerResource} if available. The default * behavior is to invoke the {@link #create(Request, Response)} method. * * @param request * The request to handle. * @param response * The response to update. * @return The target handler if available or null. */ public ServerResource find(Request request, Response response) { return create(request, response); } /** * Finds the target {@link Handler} if available. The default behavior is to * invoke the {@link #createTarget(Request, Response)} method. * * @param request * The request to handle. * @param response * The response to update. * @return The target handler if available or null. * @deprecated Use {@link #find(Request, Response)} instead. */ @Deprecated public Handler findTarget(Request request, Response response) { return createTarget(request, response); } /** * Returns the allow method matching the given method name. * * @param method * The method to match. * @param target * The target handler. * @return The allow method matching the given method name. */ @SuppressWarnings("deprecation") private java.lang.reflect.Method getAllowMethod(Method method, Handler target) { return getMethod("allow", method, target); } /** * Returns the handle method matching the given method name. * * @param method * The method to match. * @return The handle method matching the given method name. */ @SuppressWarnings("deprecation") private java.lang.reflect.Method getHandleMethod(Handler target, Method method) { return getMethod("handle", method, target); } /** * Returns the method matching the given prefix and method name. * * @param prefix * The method prefix to match (ex: "allow" or "handle"). * @param method * The method to match. * @return The method matching the given prefix and method name. */ private java.lang.reflect.Method getMethod(String prefix, Method method, Object target, Class... classes) { java.lang.reflect.Method result = null; final StringBuilder sb = new StringBuilder(); final String methodName = method.getName().toLowerCase(); if ((methodName != null) && (methodName.length() > 0)) { sb.append(prefix); sb.append(Character.toUpperCase(methodName.charAt(0))); sb.append(methodName.substring(1)); } try { result = target.getClass().getMethod(sb.toString(), classes); } catch (SecurityException e) { getLogger().log( Level.WARNING, "Couldn't access the " + prefix + " method for \"" + method + "\"", e); } catch (NoSuchMethodException e) { getLogger().log( Level.INFO, "Couldn't find the " + prefix + " method for \"" + method + "\"", e); } return result; } /** * Returns the target handler class which must be either a subclass of * {@link Handler} or of {@link ServerResource}. * * @return the target Handler class. */ public Class getTargetClass() { return this.targetClass; } /** * Handles a call. * * @param request * The request to handle. * @param response * The response to update. */ @SuppressWarnings("deprecation") @Override public void handle(Request request, Response response) { super.handle(request, response); if (isStarted()) { Handler targetHandler = findTarget(request, response); if (targetHandler != null) { if (!response.getStatus().equals(Status.SUCCESS_OK)) { // Probably during the instantiation of the target // handler, or earlier the status was changed from the // default one. Don't go further. } else { Method method = request.getMethod(); if (method == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (!allow(method, targetHandler)) { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); targetHandler.updateAllowedMethods(); } else { if (method.equals(Method.GET)) { targetHandler.handleGet(); } else if (method.equals(Method.HEAD)) { targetHandler.handleHead(); } else if (method.equals(Method.POST)) { targetHandler.handlePost(); } else if (method.equals(Method.PUT)) { targetHandler.handlePut(); } else if (method.equals(Method.DELETE)) { targetHandler.handleDelete(); } else if (method.equals(Method.OPTIONS)) { targetHandler.handleOptions(); } else { final java.lang.reflect.Method handleMethod = getHandleMethod( targetHandler, method); if (handleMethod != null) { invoke(targetHandler, handleMethod); } else { response .setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } } } } } else { ServerResource targetResource = find(request, response); if (targetResource == null) { // If the current status is a success but we couldn't // find the target handler for the request's resource // URI, then we set the response status to 404 (Not // Found). getLogger().warning( "No target resource was defined for this finder: " + toString()); response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { targetResource.init(getContext(), request, response); if ((response == null) || response.getStatus().isSuccess()) { targetResource.handle(); } else { // Probably during the instantiation of the target // server resource, or earlier the status was // changed from the default one. Don't go further. } targetResource.release(); } } } } /** * Invokes a method with the given arguments. * * @param target * The target object. * @param method * The method to invoke. * @param args * The arguments to pass. * @return Invocation result. */ private Object invoke(Object target, java.lang.reflect.Method method, Object... args) { Object result = null; if (method != null) { try { result = method.invoke(target, args); } catch (Exception e) { getLogger().log( Level.WARNING, "Couldn't invoke the handle method for \"" + method + "\"", e); } } return result; } /** * Sets the target handler class which must be either a subclass of * {@link Handler} or of {@link ServerResource}. * * @param targetClass * The target handler class. It must be either a subclass of * {@link Handler} or of {@link ServerResource}. */ public void setTargetClass(Class targetClass) { this.targetClass = targetClass; } } restlet-2.0.14/org.restlet/src/org/restlet/resource/ResourceException.java0000664000175000017500000001256611757206346027431 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import org.restlet.data.Status; /** * Encapsulates a response status and the optional cause as a checked exception. * * @author Jerome Louvel */ public class ResourceException extends RuntimeException { private static final long serialVersionUID = 1L; /** The status associated to this exception. */ private final Status status; /** * Constructor. * * @param code * The specification code of the encapsulated status. */ public ResourceException(final int code) { this(new Status(code)); } /** * Constructor. * * @param code * The specification code of the encapsulated status. * @param name * The name of the encapsulated status. * @param description * The description of the encapsulated status. * @param uri * The URI of the specification describing the method. */ public ResourceException(final int code, final String name, final String description, final String uri) { this(new Status(code, name, description, uri)); } /** * Constructor. * * @param code * The specification code of the encapsulated status. * @param name * The name of the encapsulated status. * @param description * The description of the encapsulated status. * @param uri * The URI of the specification describing the method. * @param cause * The wrapped cause error or exception. */ public ResourceException(final int code, final String name, final String description, final String uri, final Throwable cause) { this(new Status(code, cause, name, description, uri), cause); } /** * Constructor. * * @param code * The specification code of the encapsulated status. * @param cause * The wrapped cause error or exception. */ public ResourceException(final int code, final Throwable cause) { this(new Status(code, cause), cause); } /** * Constructor. * * @param status * The status to associate. */ public ResourceException(Status status) { this(status, (Throwable) ((status == null) ? null : status .getThrowable())); } /** * Constructor. * * @param status * The status to copy. * @param description * The description of the encapsulated status. */ public ResourceException(final Status status, final String description) { this(new Status(status, description)); } /** * Constructor. * * @param status * The status to copy. * @param description * The description of the encapsulated status. * @param cause * The wrapped cause error or exception. */ public ResourceException(final Status status, final String description, final Throwable cause) { this(new Status(status, cause, description), cause); } /** * Constructor. * * @param status * The status to associate. * @param cause * The wrapped cause error or exception. */ public ResourceException(final Status status, final Throwable cause) { super((status == null) ? null : status.getName(), cause); this.status = status; } /** * Constructor that set the status to * {@link org.restlet.data.Status#SERVER_ERROR_INTERNAL} including the * related error or exception. * * @param cause * The wrapped cause error or exception. */ public ResourceException(final Throwable cause) { this(new Status(Status.SERVER_ERROR_INTERNAL, cause), cause); } /** * Returns the status associated to this exception. * * @return The status associated to this exception. */ public Status getStatus() { return this.status; } @Override public String toString() { return getStatus().toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/resource/package.html0000664000175000017500000000033711757206350025365 0ustar jamespagejamespage Client and server resource classes.

    @since Restlet 1.0 @see User Guide - Resource package restlet-2.0.14/org.restlet/src/org/restlet/resource/ServerResource.java0000664000175000017500000015422011757206346026733 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Uniform; import org.restlet.data.ChallengeRequest; import org.restlet.data.ClientInfo; import org.restlet.data.CookieSetting; import org.restlet.data.Dimension; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.ServerInfo; import org.restlet.data.Status; import org.restlet.engine.resource.AnnotationInfo; import org.restlet.engine.resource.AnnotationUtils; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.RepresentationInfo; import org.restlet.representation.Variant; import org.restlet.routing.Filter; import org.restlet.routing.Router; import org.restlet.service.MetadataService; import org.restlet.util.Series; /** * Base class for server-side resources. It is a full replacement for the * deprecated {@link Resource} class. It acts as a wrapper to a given call, * including the incoming {@link Request} and the outgoing {@link Response}.
    *
    * It's life cycle is managed by a {@link Finder} created either explicitly or * more likely implicitly when your {@link ServerResource} subclass is attached * to a {@link Filter} or a {@link Router} via the {@link Filter#setNext(Class)} * or {@link Router#attach(String, Class)} methods for example. After * instantiation using the default constructor, the final * {@link #init(Context, Request, Response)} method is invoked, setting the * context, request and response. You can intercept this by overriding the * {@link #doInit()} method. Then, if the response status is still a success, * the {@link #handle()} method is invoked to actually handle the call. Finally, * the final {@link #release()} method is invoked to do the necessary clean-up, * which you can intercept by overriding the {@link #doRelease()} method. During * this life cycle, if any exception is caught, then the * {@link #doCatch(Throwable)} method is invoked.
    *
    * Note that when an annotated method manually sets the response entity, if this * entity is available then it will be preserved and the result of the annotated * method ignored.
    *
    * In addition, there are two ways to declare representation variants, one is * based on the {@link #getVariants()} method and another one on the annotated * methods. Both approaches can't however be used at the same time for now.
    *
    * Concurrency note: contrary to the {@link org.restlet.Uniform} class and its * main {@link Restlet} subclass where a single instance can handle several * calls concurrently, one instance of {@link ServerResource} is created for * each call handled and accessed by only one thread at a time. * * @author Jerome Louvel */ public abstract class ServerResource extends UniformResource { /** Indicates if annotations are supported. */ private volatile boolean annotated; /** Indicates if conditional handling is enabled. */ private volatile boolean conditional; /** Indicates if the identified resource exists. */ private volatile boolean existing; /** Indicates if content negotiation of response entities is enabled. */ private volatile boolean negotiated; /** Modifiable list of variants. */ private volatile List variants; /** * Initializer block to ensure that the basic properties are initialized * consistently across constructors. */ { this.annotated = true; this.conditional = true; this.existing = true; this.negotiated = true; this.variants = null; } /** * Default constructor. Note that the * {@link #init(Context, Request, Response)}() method will be invoked right * after the creation of the resource. */ public ServerResource() { } /** * Ask the connector to abort the related network connection, for example * immediately closing the socket. */ public void abort() { getResponse().abort(); } /** * Asks the response to immediately commit making it ready to be sent back * to the client. Note that all server connectors don't necessarily support * this feature. */ public void commit() { getResponse().commit(); } /** * Deletes the resource and all its representations. This method is only * invoked if content negotiation has been disabled as indicated by the * {@link #isNegotiated()}, otherwise the {@link #delete(Variant)} method is * invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The optional response entity. * @throws ResourceException * @see HTTP DELETE method */ protected Representation delete() throws ResourceException { Representation result = null; AnnotationInfo annotationInfo = getAnnotation(Method.DELETE); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Deletes the resource and all its representations. A variant parameter is * passed to indicate which representation should be returned if any.
    *
    * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the {@link #delete()} * method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @param variant * The variant of the response entity. * @return The optional response entity. * @throws ResourceException * @see #get(Variant) * @see HTTP DELETE method */ protected Representation delete(Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Describes the available variants to help client-side content negotiation. * Return null by default. * * @return The description of available variants. */ protected Representation describeVariants() { Representation result = null; // The list of all variants is transmitted to the client // final ReferenceList refs = new ReferenceList(variants.size()); // for (final Variant variant : variants) { // if (variant.getIdentifier() != null) { // refs.add(variant.getIdentifier()); // } // } // // result = refs.getTextRepresentation(); return result; } /** * Handles a call by first verifying the optional request conditions and * continue the processing if possible. Note that in order to evaluate those * conditions, {@link #getInfo()} or {@link #getInfo(Variant)} methods might * be invoked. * * @return The response entity. * @throws ResourceException */ protected Representation doConditionalHandle() throws ResourceException { Representation result = null; if (getConditions().hasSome()) { RepresentationInfo resultInfo = null; if (existing) { if (isNegotiated()) { resultInfo = doGetInfo(getPreferredVariant(getVariants(Method.GET))); } else { resultInfo = doGetInfo(); } if (resultInfo == null) { if ((getStatus() == null) || (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT .equals(getStatus()))) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { // Keep the current status as the developer might prefer // a special status like 'method not authorized'. } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { setStatus(status); } } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { setStatus(status); } } if ((Method.GET.equals(getMethod()) || Method.HEAD .equals(getMethod())) && resultInfo instanceof Representation) { result = (Representation) resultInfo; } else if ((getStatus() != null) && getStatus().isSuccess()) { // Conditions were passed successfully, continue the normal // processing. if (isNegotiated()) { // Reset the list of variants, as the method differs. getVariants().clear(); result = doNegotiatedHandle(); } else { result = doHandle(); } } } else { if (isNegotiated()) { result = doNegotiatedHandle(); } else { result = doHandle(); } } return result; } /** * Returns a descriptor of the response entity returned by a * {@link Method#GET} call. * * @return The response entity. * @throws ResourceException */ private RepresentationInfo doGetInfo() throws ResourceException { RepresentationInfo result = null; AnnotationInfo annotationInfo = getAnnotation(Method.GET); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { result = getInfo(); } return result; } /** * Returns a descriptor of the response entity returned by a negotiated * {@link Method#GET} call. * * @param variant * The selected variant descriptor. * @return The response entity descriptor. * @throws ResourceException */ private RepresentationInfo doGetInfo(Variant variant) throws ResourceException { RepresentationInfo result = null; if (variant != null) { if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else if (variant instanceof RepresentationInfo) { result = (RepresentationInfo) variant; } else { result = getInfo(variant); } } else { result = doGetInfo(); } return result; } /** * Effectively handles a call without content negotiation of the response * entity. The default behavior is to dispatch the call to one of the * {@link #get()}, {@link #post(Representation)}, * {@link #put(Representation)}, {@link #delete()}, {@link #head()} or * {@link #options()} methods. * * @return The response entity. * @throws ResourceException */ protected Representation doHandle() throws ResourceException { Representation result = null; Method method = getMethod(); if (method == null) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (method.equals(Method.PUT)) { result = put(getRequestEntity()); } else if (isExisting()) { if (method.equals(Method.GET)) { result = get(); } else if (method.equals(Method.POST)) { result = post(getRequestEntity()); } else if (method.equals(Method.DELETE)) { result = delete(); } else if (method.equals(Method.HEAD)) { result = head(); } else if (method.equals(Method.OPTIONS)) { result = options(); } else { result = doHandle(method, getRequestEntity()); } } else { setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } return result; } /** * Effectively handles a call with content negotiation of the response * entity using an annotated method. * * @param annotationInfo * The annotation descriptor. * @param variant * The response variant expected (can be null). * @return The response entity. * @throws ResourceException */ private Representation doHandle(AnnotationInfo annotationInfo, Variant variant) throws ResourceException { Representation result = null; Class[] parameterTypes = annotationInfo.getJavaInputTypes(); // Invoke the annotated method and get the resulting object. Object resultObject = null; try { if (parameterTypes.length > 0) { List parameters = new ArrayList(); Object parameter = null; for (Class parameterType : parameterTypes) { if (Variant.class.equals(parameterType)) { parameters.add(variant); } else { if (getRequestEntity() != null && getRequestEntity().isAvailable() && getRequestEntity().getSize() != 0) { // Assume there is content to be read. // NB: it does not handle the case where the size is // unknown, but there is no content. parameter = toObject(getRequestEntity(), parameterType); if (parameter == null) { throw new ResourceException( Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } } else { parameter = null; } parameters.add(parameter); } } resultObject = annotationInfo.getJavaMethod().invoke(this, parameters.toArray()); } else { resultObject = annotationInfo.getJavaMethod().invoke(this); } } catch (IllegalArgumentException e) { throw new ResourceException(e); } catch (IllegalAccessException e) { throw new ResourceException(e); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof ResourceException) { throw (ResourceException) e.getTargetException(); } throw new ResourceException(e.getTargetException()); } if (resultObject != null) { result = toRepresentation(resultObject, variant); } return result; } /** * Handles a call and checks the request's method and entity. If the method * is not supported, the response status is set to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. If the request's entity * is no supported, the response status is set to * {@link Status#CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE}. * * @param method * The request method. * @param entity * The request entity (can be null, or unavailable). * @return The response entity. * @throws ResourceException */ private Representation doHandle(Method method, Representation entity) { Representation result = null; if (getAnnotation(method) != null) { // We know the method is supported, let's check the entity. AnnotationInfo annotationInfo = getAnnotation(method, entity); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { // The request entity is not supported. setStatus(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Effectively handles a call with content negotiation of the response * entity. The default behavior is to dispatch the call to one of the * {@link #get(Variant)}, {@link #post(Representation,Variant)}, * {@link #put(Representation,Variant)}, {@link #delete(Variant)}, * {@link #head(Variant)} or {@link #options(Variant)} methods. * * @param variant * The response variant expected. * @return The response entity. * @throws ResourceException */ protected Representation doHandle(Variant variant) throws ResourceException { Representation result = null; Method method = getMethod(); if (method == null) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (method.equals(Method.PUT)) { result = put(getRequestEntity(), variant); } else if (isExisting()) { if (method.equals(Method.GET)) { if (variant instanceof Representation) { result = (Representation) variant; } else { result = get(variant); } } else if (method.equals(Method.POST)) { result = post(getRequestEntity(), variant); } else if (method.equals(Method.DELETE)) { result = delete(variant); } else if (method.equals(Method.HEAD)) { if (variant instanceof Representation) { result = (Representation) variant; } else { result = head(variant); } } else if (method.equals(Method.OPTIONS)) { if (variant instanceof Representation) { result = (Representation) variant; } else { result = options(variant); } } else if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant) .getAnnotationInfo(), variant); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } else { setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } return result; } /** * Effectively handles a call with content negotiation of the response * entity. The default behavior is to dispatch the call to call a matching * annotated method or one of the {@link #get(Variant)}, * {@link #post(Representation,Variant)}, * {@link #put(Representation,Variant)}, {@link #delete(Variant)}, * {@link #head(Variant)} or {@link #options(Variant)} methods.
    *
    * If no acceptable variant is found, the * {@link Status#CLIENT_ERROR_NOT_ACCEPTABLE} status is set. * * @return The response entity. * @throws ResourceException */ protected Representation doNegotiatedHandle() throws ResourceException { Representation result = null; if ((getVariants() != null) && (!getVariants().isEmpty())) { Variant preferredVariant = getClientInfo().getPreferredVariant( getVariants(), getMetadataService()); if (preferredVariant == null) { // No variant was found matching the client preferences setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE); result = describeVariants(); } else { // Update the variant dimensions used for content negotiation updateDimensions(); result = doHandle(preferredVariant); } } else { // No variant declared for this method. result = doHandle(); } return result; } /** * Returns a full representation. This method is only invoked if content * negotiation has been disabled as indicated by the {@link #isNegotiated()} * , otherwise the {@link #get(Variant)} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The resource's representation. * @throws ResourceException * @see HTTP * GET method */ protected Representation get() throws ResourceException { Representation result = null; AnnotationInfo annotationInfo = getAnnotation(Method.GET); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Returns a full representation for a given variant. A variant parameter is * passed to indicate which representation should be returned if any.
    *
    * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the {@link #get()} * method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
    * * @param variant * The variant whose full representation must be returned. * @return The resource's representation. * @see #get(Variant) * @throws ResourceException */ protected Representation get(Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Returns the first annotation descriptor matching the given method. * * @param method * The method to match. * @return The annotation descriptor. */ private AnnotationInfo getAnnotation(Method method) { return getAnnotation(method, null); } /** * Returns the first annotation descriptor matching the given method. * * @param method * The method to match. * @param entity * The request entity or null. * @return The annotation descriptor. */ private AnnotationInfo getAnnotation(Method method, Representation entity) { if (isAnnotated()) { return AnnotationUtils.getAnnotation(getAnnotations(), method, entity, getMetadataService(), getConverterService()); } return null; } /** * Returns the annotation descriptors. * * @return The annotation descriptors. */ private List getAnnotations() { return isAnnotated() ? AnnotationUtils.getAnnotations(getClass()) : null; } /** * Returns information about the resource's representation. Those metadata * are important for conditional method processing. The advantage over the * complete {@link Representation} class is that it is much lighter to * create. This method is only invoked if content negotiation has been * disabled as indicated by the {@link #isNegotiated()}, otherwise the * {@link #getInfo(Variant)} method is invoked.
    *
    * The default behavior is to invoke the {@link #get()} method. * * @return Information about the resource's representation. * @throws ResourceException */ protected RepresentationInfo getInfo() throws ResourceException { return get(); } /** * Returns information about the resource's representation. Those metadata * are important for conditional method processing. The advantage over the * complete {@link Representation} class is that it is much lighter to * create. A variant parameter is passed to indicate which representation * should be returned if any.
    *
    * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #getInfo(Variant)} method is invoked.
    *
    * The default behavior is to invoke the {@link #get(Variant)} method. * * @param variant * The variant whose representation information must be returned. * @return Information about the resource's representation. * @throws ResourceException */ protected RepresentationInfo getInfo(Variant variant) throws ResourceException { return get(variant); } /** * Returns the callback invoked after sending the response. * * @return The callback invoked after sending the response. */ public Uniform getOnSent() { return getResponse().getOnSent(); } /** * Returns the preferred variant among a list of available variants. The * selection is based on the client preferences using the * {@link ClientInfo#getPreferredVariant(List, MetadataService)} method. * * @param variants * The available variants. * @return The preferred variant. */ protected Variant getPreferredVariant(List variants) { Variant result = null; // If variants were found, select the best matching one if ((variants != null) && (!variants.isEmpty())) { result = getClientInfo().getPreferredVariant( variants, (getApplication() == null) ? null : getApplication() .getMetadataService()); } return result; } /** * Returns a modifiable list of exposed variants for the current request * method. You can declare variants manually by updating the result list , * by overriding this method. By default, the variants will be provided * based on annotated methods. * * @return The modifiable list of variants. */ public List getVariants() { return getVariants(getMethod()); } /** * Returns a modifiable list of exposed variants for the given method. You * can declare variants manually by updating the result list , by overriding * this method. By default, the variants will be provided based on annotated * methods. * * @param method * The method. * @return The modifiable list of variants. */ protected List getVariants(Method method) { List result = this.variants; if (result == null) { result = new ArrayList(); // Add annotation-based variants in priority if (isAnnotated() && hasAnnotations()) { List annoVariants = null; method = (Method.HEAD.equals(method)) ? Method.GET : method; for (AnnotationInfo annotationInfo : getAnnotations()) { if (annotationInfo.isCompatible(method, getRequestEntity(), getMetadataService(), getConverterService())) { annoVariants = annotationInfo.getResponseVariants( getMetadataService(), getConverterService()); if (annoVariants != null) { for (Variant v : annoVariants) { result.add(new VariantInfo(v, annotationInfo)); } } } } } this.variants = result; } return result; } /** * Handles any call to this resource. The default implementation check the * {@link #isConditional()} and {@link #isNegotiated()} method to determine * which one of the {@link #doConditionalHandle()}, * {@link #doNegotiatedHandle()} and {@link #doHandle()} methods should be * invoked. It also catches any {@link ResourceException} thrown and updates * the response status using the * {@link #setStatus(Status, Throwable, String)} method.
    *
    * After handling, if the status is set to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}, then * {@link #updateAllowedMethods()} is invoked to give the resource a chance * to inform the client about the allowed methods. * * @return The response entity. */ @Override public Representation handle() { Representation result = null; // If the resource is not available after initialization and if this a // retrieval method, then return a "not found" response. if (!isExisting() && getMethod().isSafe()) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { try { if (isConditional()) { result = doConditionalHandle(); } else if (isNegotiated()) { result = doNegotiatedHandle(); } else { result = doHandle(); } if (!getResponse().isEntityAvailable()) { // If the user manually set the entity, keep it getResponse().setEntity(result); } if (Status.CLIENT_ERROR_METHOD_NOT_ALLOWED.equals(getStatus())) { updateAllowedMethods(); } else if (Method.GET.equals(getMethod()) && Status.SUCCESS_OK.equals(getStatus()) && (getResponseEntity() == null || !getResponseEntity() .isAvailable())) { getLogger() .fine( "A response with a 200 (Ok) status should have an entity. Changing the status to 204 (No content)."); setStatus(Status.SUCCESS_NO_CONTENT); } } catch (Throwable t) { doCatch(t); } } return result; } /** * Indicates if annotations were defined on this resource. * * @return True if annotations were defined on this resource. */ private boolean hasAnnotations() { return (getAnnotations() != null) && (!getAnnotations().isEmpty()); } /** * Returns a representation whose metadata will be returned to the client. * This method is only invoked if content negotiation has been disabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #head(Variant)} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The resource's representation. * @throws ResourceException * @see HTTP * GET method */ protected Representation head() throws ResourceException { return get(); } /** * Returns a representation whose metadata will be returned to the client. A * variant parameter is passed to indicate which representation should be * returned if any.
    *
    * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the {@link #head()} * method is invoked.
    *
    * The default implementation directly returns the variant if it is already * an instance of {@link Representation}. In other cases, you need to * override this method in order to provide your own implementation. * * * @param variant * The variant whose full representation must be returned. * @return The resource's representation. * @see #get(Variant) * @throws ResourceException */ protected Representation head(Variant variant) throws ResourceException { return get(variant); } /** * Indicates if annotations are supported. The default value is true. * * @return True if annotations are supported. */ public boolean isAnnotated() { return annotated; } /** * Indicates if the response should be automatically committed. When * processing a request on the server-side, setting this property to 'false' * let you ask to the server connector to wait before sending the response * back to the client when the initial calling thread returns. This will let * you do further updates to the response and manually calling * {@link #commit()} later on, using another thread. * * @return True if the response should be automatically committed. */ public boolean isAutoCommitting() { return getResponse().isAutoCommitting(); } /** * Indicates if the response has already been committed. * * @return True if the response has already been committed. */ public boolean isCommitted() { return getResponse().isCommitted(); } /** * Indicates if conditional handling is enabled. The default value is true. * * @return True if conditional handling is enabled. */ public boolean isConditional() { return conditional; } /** * Indicates if the identified resource exists. The default value is true. * * @return True if the identified resource exists. */ public boolean isExisting() { return existing; } /** * Indicates if the authenticated client user associated to the current * request is in the given role name. * * @param roleName * The role name to test. * @return True if the authenticated subject is in the given role. */ public boolean isInRole(String roleName) { return getClientInfo().getRoles().contains( getApplication().getRole(roleName)); } /** * Indicates if content negotiation of response entities is enabled. The * default value is true. * * @return True if content negotiation of response entities is enabled. */ public boolean isNegotiated() { return this.negotiated; } /** * Indicates the communication options available for this resource. This * method is only invoked if content negotiation has been disabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #options(Variant)} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The optional response entity. */ protected Representation options() throws ResourceException { Representation result = null; AnnotationInfo annotationInfo = getAnnotation(Method.OPTIONS); // Updates the list of allowed methods updateAllowedMethods(); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Indicates the communication options available for this resource. A * variant parameter is passed to indicate which representation should be * returned if any.
    *
    * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #options()} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
    * * @param variant * The variant of the response entity. * @return The optional response entity. * @see #get(Variant) */ protected Representation options(Variant variant) throws ResourceException { Representation result = null; // Updates the list of allowed methods updateAllowedMethods(); if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Posts a representation to the resource at the target URI reference. This * method is only invoked if content negotiation has been disabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #post(Representation, Variant)} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @param entity * The posted entity. * @return The optional response entity. * @throws ResourceException * @see #get(Variant) * @see HTTP * POST method */ protected Representation post(Representation entity) throws ResourceException { return doHandle(Method.POST, entity); } /** * Posts a representation to the resource at the target URI reference. A * variant parameter is passed to indicate which representation should be * returned if any.
    *
    * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #post(Representation)} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
    * * @param entity * The posted entity. * @param variant * The variant of the response entity. * @return The optional result entity. * @throws ResourceException * @see HTTP POST method */ protected Representation post(Representation entity, Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Creates or updates a resource with the given representation as new state * to be stored. This method is only invoked if content negotiation has been * disabled as indicated by the {@link #isNegotiated()}, otherwise the * {@link #put(Representation, Variant)} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @param entity * The representation to store. * @return The optional result entity. * @throws ResourceException * @see HTTP * PUT method */ protected Representation put(Representation entity) throws ResourceException { return doHandle(Method.PUT, entity); } /** * Creates or updates a resource with the given representation as new state * to be stored. A variant parameter is passed to indicate which * representation should be returned if any.
    *
    * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #put(Representation)} method is invoked.
    *
    * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
    * * @param representation * The representation to store. * @param variant * The variant of the response entity. * @return The optional result entity. * @throws ResourceException * @see #get(Variant) * @see HTTP PUT method */ protected Representation put(Representation representation, Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target URI reference. */ public void redirectPermanent(Reference targetRef) { if (getResponse() != null) { getResponse().redirectPermanent(targetRef); } } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request.
    *
    * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectPermanent(String targetUri) { if (getResponse() != null) { getResponse().redirectPermanent(targetUri); } } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource. * * @param targetRef * The target reference. */ public void redirectSeeOther(Reference targetRef) { if (getResponse() != null) { getResponse().redirectSeeOther(targetRef); } } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource.
    *
    * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectSeeOther(String targetUri) { if (getResponse() != null) { getResponse().redirectSeeOther(targetUri); } } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target reference. */ public void redirectTemporary(Reference targetRef) { if (getResponse() != null) { getResponse().redirectTemporary(targetRef); } } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request.
    *
    * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectTemporary(String targetUri) { if (getResponse() != null) { getResponse().redirectTemporary(targetUri); } } /** * Sets the set of methods allowed on the requested resource. The set * instance set must be thread-safe (use {@link CopyOnWriteArraySet} for * example. * * @param allowedMethods * The set of methods allowed on the requested resource. * @see Response#setAllowedMethods(Set) */ public void setAllowedMethods(Set allowedMethods) { if (getResponse() != null) { getResponse().setAllowedMethods(allowedMethods); } } /** * Indicates if annotations are supported. The default value is true. * * @param annotated * Indicates if annotations are supported. */ public void setAnnotated(boolean annotated) { this.annotated = annotated; } /** * Indicates if the response should be automatically committed. * * @param autoCommitting * True if the response should be automatically committed */ public void setAutoCommitting(boolean autoCommitting) { getResponse().setAutoCommitting(autoCommitting); } /** * Sets the list of authentication requests sent by an origin server to a * client. The list instance set must be thread-safe (use * {@link CopyOnWriteArrayList} for example. * * @param requests * The list of authentication requests sent by an origin server * to a client. * @see Response#setChallengeRequests(List) */ public void setChallengeRequests(List requests) { if (getResponse() != null) { getResponse().setChallengeRequests(requests); } } /** * Indicates if the response has already been committed. * * @param committed * True if the response has already been committed. */ public void setCommitted(boolean committed) { getResponse().setCommitted(committed); } /** * Indicates if conditional handling is enabled. The default value is true. * * @param conditional * True if conditional handling is enabled. */ public void setConditional(boolean conditional) { this.conditional = conditional; } /** * Sets the cookie settings provided by the server. * * @param cookieSettings * The cookie settings provided by the server. * @see Response#setCookieSettings(Series) */ public void setCookieSettings(Series cookieSettings) { if (getResponse() != null) { getResponse().setCookieSettings(cookieSettings); } } /** * Sets the set of dimensions on which the response entity may vary. The set * instance set must be thread-safe (use {@link CopyOnWriteArraySet} for * example. * * @param dimensions * The set of dimensions on which the response entity may vary. * @see Response#setDimensions(Set) */ public void setDimensions(Set dimensions) { if (getResponse() != null) { getResponse().setDimensions(dimensions); } } /** * Indicates if the identified resource exists. The default value is true. * * @param exists * Indicates if the identified resource exists. */ public void setExisting(boolean exists) { this.existing = exists; } /** * Sets the reference that the client should follow for redirections or * resource creations. * * @param locationRef * The reference to set. * @see Response#setLocationRef(Reference) */ public void setLocationRef(Reference locationRef) { if (getResponse() != null) { getResponse().setLocationRef(locationRef); } } /** * Sets the reference that the client should follow for redirections or * resource creations. If you pass a relative location URI, it will be * resolved with the current base reference of the request's resource * reference (see {@link Request#getResourceRef()} and * {@link Reference#getBaseRef()}. * * @param locationUri * The URI to set. * @see Response#setLocationRef(String) */ public void setLocationRef(String locationUri) { if (getResponse() != null) { getResponse().setLocationRef(locationUri); } } /** * Indicates if content negotiation of response entities is enabled. The * default value is true. * * @param negotiateContent * True if content negotiation of response entities is enabled. */ public void setNegotiated(boolean negotiateContent) { this.negotiated = negotiateContent; } /** * Sets the callback invoked after sending the response. * * @param onSentCallback * The callback invoked after sending the response. */ public void setOnSent(Uniform onSentCallback) { getResponse().setOnSent(onSentCallback); } /** * Sets the server-specific information. * * @param serverInfo * The server-specific information. * @see Response#setServerInfo(ServerInfo) */ public void setServerInfo(ServerInfo serverInfo) { if (getResponse() != null) { getResponse().setServerInfo(serverInfo); } } /** * Sets the status. * * @param status * The status to set. * @see Response#setStatus(Status) */ public void setStatus(Status status) { if (getResponse() != null) { getResponse().setStatus(status); } } /** * Sets the status. * * @param status * The status to set. * @param message * The status message. * @see Response#setStatus(Status, String) */ public void setStatus(Status status, String message) { if (getResponse() != null) { getResponse().setStatus(status, message); } } /** * Sets the status. * * @param status * The status to set. * @param throwable * The related error or exception. * @see Response#setStatus(Status, Throwable) */ public void setStatus(Status status, Throwable throwable) { if (getResponse() != null) { getResponse().setStatus(status, throwable); } } /** * Sets the status. * * @param status * The status to set. * @param throwable * The related error or exception. * @param message * The status message. * @see Response#setStatus(Status, Throwable, String) */ public void setStatus(Status status, Throwable throwable, String message) { if (getResponse() != null) { getResponse().setStatus(status, throwable, message); } } /** * Invoked when the list of allowed methods needs to be updated. The * {@link #getAllowedMethods()} or the {@link #setAllowedMethods(Set)} * methods should be used. The default implementation lists the annotated * methods. */ public void updateAllowedMethods() { getAllowedMethods().clear(); List annotations = getAnnotations(); if (annotations != null) { for (AnnotationInfo annotationInfo : annotations) { if (!getAllowedMethods().contains( annotationInfo.getRestletMethod())) { getAllowedMethods().add(annotationInfo.getRestletMethod()); } } } } /** * Update the dimensions that were used for content negotiation. By default, * it adds the {@link Dimension#CHARACTER_SET}, {@link Dimension#ENCODING}, * {@link Dimension#LANGUAGE}and {@link Dimension#MEDIA_TYPE} constants. */ protected void updateDimensions() { getDimensions().add(Dimension.CHARACTER_SET); getDimensions().add(Dimension.ENCODING); getDimensions().add(Dimension.LANGUAGE); getDimensions().add(Dimension.MEDIA_TYPE); } } restlet-2.0.14/org.restlet/src/org/restlet/resource/Handler.java0000664000175000017500000003411011757206346025325 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Application; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.routing.Template; /** * Final handler of calls typically created by Finders. Handler instances allow * the processing of a call in a thread-safe context. This is different from the * Uniform subclasses like Restlet, Filter and Router which can be invoked by * multiple threads at the same time. However, as they offer a rather low-level * API and its subclass {@link org.restlet.resource.Resource} is often preferred * for concrete handlers.
    *
    * This class exposes a different set of handle*() and allow*() Java methods for * each type of Uniform method supported by your handler. It has a predefined * set for common methods like GET, POST, PUT, DELETE, HEAD and OPTIONS. * Extension methods like MOVE or PATCH are automatically supported using Java * introspection. The actual dispatching of the call to those methods is * dynamically done by the {@link org.restlet.resource.Finder} class.
    *
    * The HEAD method has a default implementation based on the GET method and the * OPTIONS method automatically updates the list of allowed methods in the * response, as required by the HTTP specification.
    *
    * Also, you can declare which REST methods are allowed by your Handler by * overriding the matching allow*() method. By default, allowOptions() returns * true, but all other allow*() methods will return false. Therefore, if you * want to accept MOVE method calls, just override allowMove() and return true. * Again, the invoking Finder will be able to detect this method and know * whether or not your Handler should be invoked. It is also used by the * handleOptions() method to return the list of allowed methods.
    *
    * Concurrency note: typically created by Finders, Handler instances are the * final handlers of requests. Unlike the other processors in the Restlet chain, * a Handler instance is not reused by several calls and is only invoked by one * thread. Therefore, it doesn't have to be thread-safe.
    * * @see org.restlet.resource.Finder * @author Jerome Louvel * @deprecated Use the new {@link ServerResource} class instead. */ @Deprecated public abstract class Handler { /** * Workaround limitation in Java reflection. * * @param method * The method to invoke, potentially in a protected class * @return The equivalent method in a public ancestor class. * @throws NoSuchMethodException * @see Bug * #4071957 */ private static java.lang.reflect.Method getAncestorMethod( java.lang.reflect.Method method) throws NoSuchMethodException { while (!java.lang.reflect.Modifier.isPublic(method.getDeclaringClass() .getModifiers())) { method = method.getDeclaringClass().getSuperclass().getMethod( method.getName(), method.getParameterTypes()); } return method; } /** The parent context. */ private volatile Context context; /** The handled request. */ private volatile Request request; /** The returned response. */ private volatile Response response; /** * Special constructor used by IoC frameworks. Note that the init() method * MUST be invoked right after the creation of the handler in order to keep * a behavior consistent with the normal three arguments constructor. */ public Handler() { } /** * Normal constructor. * * @param context * The parent context. * @param request * The request to handle. * @param response * The response to return. */ public Handler(Context context, Request request, Response response) { this.context = context; this.request = request; this.response = response; } /** * Indicates if DELETE calls are allowed. The default value is false. * * @return True if the method is allowed. */ public boolean allowDelete() { return false; } /** * Indicates if GET calls are allowed. The default value is false. * * @return True if the method is allowed. */ public boolean allowGet() { return false; } /** * Indicates if HEAD calls are allowed. The default behavior is to call * allowGet(). * * @return True if the method is allowed. */ public boolean allowHead() { return allowGet(); } /** * Indicates if OPTIONS calls are allowed. The default value is true. * * @return True if the method is allowed. */ public boolean allowOptions() { return true; } /** * Indicates if POST calls are allowed. The default value is false. * * @return True if the method is allowed. */ public boolean allowPost() { return false; } /** * Indicates if PUT calls are allowed. The default value is false. * * @return True if the method is allowed. */ public boolean allowPut() { return false; } /** * Generates a reference based on a template URI. Note that you can leverage * all the variables defined in the Template class as they will be resolved * using the resource's request and response properties. * * @param uriTemplate * The URI template to use for generation. * @return The generated reference. */ public Reference generateRef(String uriTemplate) { final Template tplt = new Template(uriTemplate); tplt.setLogger(getLogger()); return new Reference(tplt.format(getRequest(), getResponse())); } /** * Returns the set of allowed methods. * * @return The set of allowed methods. */ public Set getAllowedMethods() { final Set result = new HashSet(); updateAllowedMethods(result); return result; } /** * Returns the parent application if it exists, or null. * * @return The parent application if it exists, or null. */ public Application getApplication() { return Application.getCurrent(); } /** * Returns the context. * * @return The context. */ public Context getContext() { return (this.context != null) ? this.context : Context.getCurrent(); } /** * Returns the logger to use. * * @return The logger to use. */ public Logger getLogger() { return (getContext() != null) ? getContext().getLogger() : Context .getCurrentLogger(); } /** * Returns the optional matrix of the request's target resource reference as * a form (series of parameters). * * @return The parsed query. * @see Reference#getMatrixAsForm() */ public Form getMatrix() { return getRequest().getResourceRef().getMatrixAsForm(); } /** * Returns the parsed query of the request's target resource reference as a * form (series of parameters). * * @return The parsed query. * @see Reference#getQueryAsForm() */ public Form getQuery() { return getRequest().getResourceRef().getQueryAsForm(); } /** * Returns the request. * * @return the request. */ public Request getRequest() { return this.request; } /** * Returns the response. * * @return the response. */ public Response getResponse() { return this.response; } /** * Handles a DELETE call. The default behavior, to be overridden by * subclasses, is to set the status to {@link Status#SERVER_ERROR_INTERNAL}. */ public void handleDelete() { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Handles a GET call. The default behavior, to be overridden by subclasses, * is to set the status to {@link Status#SERVER_ERROR_INTERNAL}. */ public void handleGet() { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Handles a HEAD call. The default behavior is to invoke the handleGet() * method. This is the expected behavior of the HTTP 1.1 specification for * example. Note that the server connectors will take care of never sending * back to the client the response entity bodies. */ public void handleHead() { handleGet(); } /** * Handles an OPTIONS call introspecting the target resource (as provided by * the 'findTarget' method). The default implementation is based on the HTTP * specification which says that OPTIONS should return the list of allowed * methods in the Response headers. */ public void handleOptions() { updateAllowedMethods(); getResponse().setStatus(Status.SUCCESS_OK); } /** * Handles a POST call. The default behavior, to be overridden by * subclasses, is to set the status to {@link Status#SERVER_ERROR_INTERNAL}. */ public void handlePost() { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Handles a PUT call. The default behavior, to be overridden by subclasses, * is to set the status to {@link Status#SERVER_ERROR_INTERNAL}. */ public void handlePut() { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Initialize the resource with its context. If you override this method, * make sure that you don't forget to call super.init() first, otherwise * your Resource won't behave properly. * * @param context * The parent context. * @param request * The request to handle. * @param response * The response to return. */ public void init(Context context, Request request, Response response) { this.context = context; this.request = request; this.response = response; } /** * Invokes a method with the given arguments. * * @param method * The method to invoke. * @param args * The arguments to pass. * @return Invocation result. */ private Object invoke(java.lang.reflect.Method method, Object... args) { Object result = null; if (method != null) { try { result = method.invoke(this, args); } catch (Exception e) { getLogger().log( Level.WARNING, "Couldn't invoke the handle method for \"" + method + "\"", e); } } return result; } /** * Sets the parent context. * * @param context * The parent context. */ public void setContext(Context context) { this.context = context; } /** * Sets the request to handle. * * @param request * The request to handle. */ public void setRequest(Request request) { this.request = request; } /** * Sets the response to update. * * @param response * The response to update. */ public void setResponse(Response response) { this.response = response; } /** * Updates the set of allowed methods on the response. */ public void updateAllowedMethods() { updateAllowedMethods(getResponse().getAllowedMethods()); } /** * Updates the set of methods with the ones allowed by this resource * instance. * * @param allowedMethods * The set to update. */ private void updateAllowedMethods(Set allowedMethods) { for (final java.lang.reflect.Method orig_classMethod : getClass() .getMethods()) { java.lang.reflect.Method classMethod; try { classMethod = getAncestorMethod(orig_classMethod); if (classMethod.getName().startsWith("allow") && (classMethod.getParameterTypes().length == 0)) { if ((Boolean) invoke(classMethod)) { final Method allowedMethod = Method.valueOf(classMethod .getName().substring(5)); allowedMethods.add(allowedMethod); } } } catch (NoSuchMethodException e) { getLogger().log(Level.FINE, "Unable to find a public version of this method.", e); } } } } restlet-2.0.14/org.restlet/src/org/restlet/resource/UniformResource.java0000664000175000017500000005044511757206346027110 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.CookieSetting; import org.restlet.data.Dimension; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Range; import org.restlet.data.Reference; import org.restlet.data.ServerInfo; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.service.MetadataService; import org.restlet.service.StatusService; import org.restlet.util.Series; /** * Base resource class exposing the uniform REST interface. Intended conceptual * target of a hypertext reference. An uniform resource encapsulates a * {@link Context}, a {@link Request} and a {@link Response}, corresponding to a * specific target resource.
    *
    * It also defines a precise life cycle. First, the instance is created and the * final {@link #init(Context, Request, Response)} method is invoked, with a * chance for the developer to do some additional initialization by overriding * the {@link #doInit()} method.
    *
    * Then, the abstract {@link #handle()} method can be invoked. For concrete * behavior, see the {@link ClientResource} and {@link ServerResource} * subclasses. Note that the state of the resource can be changed several times * and the {@link #handle()} method called more than once, but always by the * same thread.
    *
    * Finally, the final {@link #release()} method can be called to clean-up the * resource, with a chance for the developer to do some additional clean-up by * overriding the {@link #doRelease()} method.
    *
    * Note also that throwable raised such as {@link Error} and {@link Exception} * can be caught in a single point by overriding the {@link #doCatch(Throwable)} * method.
    *
    * "The central feature that distinguishes the REST architectural style from * other network-based styles is its emphasis on a uniform interface between * components. By applying the software engineering principle of generality to * the component interface, the overall system architecture is simplified and * the visibility of interactions is improved. Implementations are decoupled * from the services they provide, which encourages independent evolvability." * Roy T. Fielding
    *
    * Concurrency note: contrary to the {@link org.restlet.Uniform} class and its * main {@link Restlet} subclass where a single instance can handle several * calls concurrently, one instance of {@link UniformResource} is created for * each call handled and accessed by only one thread at a time. * * @see Source * dissertation * @author Jerome Louvel */ public abstract class UniformResource { /** The current context. */ private volatile Context context; /** The handled request. */ private volatile Request request; /** The handled response. */ private volatile Response response; /** * Invoked when an error or an exception is caught during initialization, * handling or releasing. By default, updates the responses's status with * the result of * {@link org.restlet.service.StatusService#getStatus(Throwable, UniformResource)} * . * * @param throwable * The caught error or exception. */ protected void doCatch(Throwable throwable) { Level level = Level.INFO; Status status = null; if (throwable instanceof ResourceException) { ResourceException re = (ResourceException) throwable; if (re.getCause() != null) { // What is most interesting is the embedded cause throwable = re.getCause(); status = getStatusService().getStatus(throwable, this); } else { status = re.getStatus(); } } else { status = getStatusService().getStatus(throwable, this); } if (status.isServerError()) { level = Level.WARNING; } else if (status.isConnectorError()) { level = Level.INFO; } else if (status.isClientError()) { level = Level.FINE; } getLogger().log(level, "Exception or error caught in resource", throwable); if (getResponse() != null) { getResponse().setStatus(status); } } /** * Set-up method that can be overridden in order to initialize the state of * the resource. By default it does nothing. * * @see #init(Context, Request, Response) */ protected void doInit() throws ResourceException { } /** * Clean-up method that can be overridden in order to release the state of * the resource. By default it does nothing. * * @see #release() */ protected void doRelease() throws ResourceException { } /** * Returns the set of methods allowed for the current client by the * resource. The result can vary based on the client's user agent, * authentication and authorization data provided by the client. * * @return The set of allowed methods. */ public Set getAllowedMethods() { return getResponse() == null ? null : getResponse().getAllowedMethods(); } /** * Returns the parent application if it exists, or instantiates a new one if * needed. * * @return The parent application if it exists, or a new one. */ public org.restlet.Application getApplication() { org.restlet.Application result = org.restlet.Application.getCurrent(); return (result == null) ? new org.restlet.Application(getContext()) : result; } /** * Returns the list of authentication requests sent by an origin server to a * client. If none is available, an empty list is returned. * * @return The list of authentication requests. * @see Response#getChallengeRequests() */ public List getChallengeRequests() { return getResponse() == null ? null : getResponse() .getChallengeRequests(); } /** * Returns the authentication response sent by a client to an origin server. * * @return The authentication response sent by a client to an origin server. * @see Request#getChallengeResponse() */ public ChallengeResponse getChallengeResponse() { return getRequest() == null ? null : getRequest() .getChallengeResponse(); } /** * Returns the client-specific information. Creates a new instance if no one * has been set. * * @return The client-specific information. * @see Request#getClientInfo() */ public ClientInfo getClientInfo() { return getRequest() == null ? null : getRequest().getClientInfo(); } /** * Returns the modifiable conditions applying to this request. Creates a new * instance if no one has been set. * * @return The conditions applying to this call. * @see Request#getConditions() */ public Conditions getConditions() { return getRequest() == null ? null : getRequest().getConditions(); } /** * Returns the current context. * * @return The current context. */ public Context getContext() { return context; } /** * Returns the application's converter service or create a new one. * * @return The converter service. */ public org.restlet.service.ConverterService getConverterService() { org.restlet.service.ConverterService result = null; result = getApplication().getConverterService(); if (result == null) { result = new org.restlet.service.ConverterService(); } return result; } /** * Returns the modifiable series of cookies provided by the client. Creates * a new instance if no one has been set. * * @return The cookies provided by the client. * @see Request#getCookies() */ public Series getCookies() { return getRequest() == null ? null : getRequest().getCookies(); } /** * Returns the modifiable series of cookie settings provided by the server. * Creates a new instance if no one has been set. * * @return The cookie settings provided by the server. * @see Response#getCookieSettings() */ public Series getCookieSettings() { return getResponse() == null ? null : getResponse().getCookieSettings(); } /** * Returns the modifiable set of selecting dimensions on which the response * entity may vary. If some server-side content negotiation is done, this * set should be properly updated, other it can be left empty. Creates a new * instance if no one has been set. * * @return The set of dimensions on which the response entity may vary. * @see Response#getDimensions() */ public Set getDimensions() { return getResponse() == null ? null : getResponse().getDimensions(); } /** * Returns the host reference. This may be different from the resourceRef's * host, for example for URNs and other URIs that don't contain host * information. * * @return The host reference. * @see Request#getHostRef() */ public Reference getHostRef() { return getRequest() == null ? null : getRequest().getHostRef(); } /** * Returns the reference that the client should follow for redirections or * resource creations. * * @return The redirection reference. * @see Response#getLocationRef() */ public Reference getLocationRef() { return getResponse() == null ? null : getResponse().getLocationRef(); } /** * Returns the logger. * * @return The logger. */ public Logger getLogger() { return getContext() != null ? getContext().getLogger() : Context .getCurrentLogger(); } /** * Returns the resource reference's optional matrix. * * @return The resource reference's optional matrix. * @see Reference#getMatrixAsForm() */ public Form getMatrix() { return getReference() == null ? null : getReference().getMatrixAsForm(); } /** * Returns the maximum number of intermediaries. * * @return The maximum number of intermediaries. */ public int getMaxForwards() { return getRequest() == null ? null : getRequest().getMaxForwards(); } /** * Returns the application's metadata service or create a new one. * * @return The metadata service. */ public MetadataService getMetadataService() { MetadataService result = null; result = getApplication().getMetadataService(); if (result == null) { result = new MetadataService(); } return result; } /** * Returns the method. * * @return The method. * @see Request#getMethod() */ public Method getMethod() { return getRequest() == null ? null : getRequest().getMethod(); } /** * Returns the original reference as requested by the client. Note that this * property is not used during request routing. * * @return The original reference. * @see Request#getOriginalRef() */ public Reference getOriginalRef() { return getRequest() == null ? null : getRequest().getOriginalRef(); } /** * Returns the protocol by first returning the resourceRef.schemeProtocol * property if it is set, or the baseRef.schemeProtocol property otherwise. * * @return The protocol or null if not available. * @see Request#getProtocol() */ public Protocol getProtocol() { return getRequest() == null ? null : getRequest().getProtocol(); } /** * Returns the resource reference's optional query. * * @return The resource reference's optional query. * @see Reference#getQueryAsForm() */ public Form getQuery() { return getReference() == null ? null : getReference().getQueryAsForm(); } /** * Returns the ranges to return from the target resource's representation. * * @return The ranges to return. * @see Request#getRanges() */ public List getRanges() { return getRequest() == null ? null : getRequest().getRanges(); } /** * Returns the URI reference. * * @return The URI reference. */ public Reference getReference() { return getRequest() == null ? null : getRequest().getResourceRef(); } /** * Returns the referrer reference if available. * * @return The referrer reference. */ public Reference getReferrerRef() { return getRequest() == null ? null : getRequest().getReferrerRef(); } /** * Returns the handled request. * * @return The handled request. */ public Request getRequest() { return request; } /** * Returns the request attributes. * * @return The request attributes. * @see Request#getAttributes() */ public Map getRequestAttributes() { return getRequest() == null ? null : getRequest().getAttributes(); } /** * Returns the request entity representation. * * @return The request entity representation. */ public Representation getRequestEntity() { return getRequest() == null ? null : getRequest().getEntity(); } /** * Returns the handled response. * * @return The handled response. */ public Response getResponse() { return response; } /** * Returns the response attributes. * * @return The response attributes. * @see Response#getAttributes() */ public Map getResponseAttributes() { return getResponse() == null ? null : getResponse().getAttributes(); } /** * Returns the response entity representation. * * @return The response entity representation. */ public Representation getResponseEntity() { return getResponse() == null ? null : getResponse().getEntity(); } /** * Returns the application root reference. * * @return The application root reference. * @see Request#getRootRef() */ public Reference getRootRef() { return getRequest() == null ? null : getRequest().getRootRef(); } /** * Returns the server-specific information. Creates a new instance if no one * has been set. * * @return The server-specific information. * @see Response#getServerInfo() */ public ServerInfo getServerInfo() { return getResponse() == null ? null : getResponse().getServerInfo(); } /** * Returns the status. * * @return The status. * @see Response#getStatus() */ public Status getStatus() { return getResponse() == null ? null : getResponse().getStatus(); } /** * Returns the application's status service or create a new one. * * @return The status service. */ public StatusService getStatusService() { StatusService result = null; result = getApplication().getStatusService(); if (result == null) { result = new StatusService(); } return result; } /** * Handles the call composed of the current context, request and response. * * @return The optional response entity. */ public abstract Representation handle(); /** * Initialization method setting the environment of the current resource * instance. It the calls the {@link #doInit()} method that can be * overridden. * * @param context * The current context. * @param request * The handled request. * @param response * The handled response. */ public final void init(Context context, Request request, Response response) { this.context = context; this.request = request; this.response = response; try { doInit(); } catch (Throwable t) { doCatch(t); } } /** * Indicates if the message was or will be exchanged confidentially, for * example via a SSL-secured connection. * * @return True if the message is confidential. * @see Request#isConfidential() */ public boolean isConfidential() { return getRequest() == null ? null : getRequest().isConfidential(); } /** * Releases the resource by calling {@link #doRelease()}. */ public final void release() { try { doRelease(); } catch (Throwable t) { doCatch(t); } } /** * Sets the handled request. * * @param request * The handled request. */ public void setRequest(Request request) { this.request = request; } /** * Sets the handled response. * * @param response * The handled response. */ public void setResponse(Response response) { this.response = response; } /** * Converts a representation into a Java object. Leverages the * {@link org.restlet.service.ConverterService}. * * @param * The expected class of the Java object. * @param source * The source representation to convert. * @param target * The target class of the Java object. * @return The converted Java object. * @throws ResourceException */ protected T toObject(Representation source, Class target) throws ResourceException { T result = null; if (source != null) { try { org.restlet.service.ConverterService cs = getConverterService(); result = cs.toObject(source, target, this); } catch (Exception e) { throw new ResourceException(e); } } return result; } /** * Converts an object into a representation based on client preferences. * * @param source * The object to convert. * @param target * The target representation variant. * @return The wrapper representation. */ protected Representation toRepresentation(Object source, Variant target) { Representation result = null; if (source != null) { org.restlet.service.ConverterService cs = getConverterService(); result = cs.toRepresentation(source, target, this); } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/resource/Directory.java0000664000175000017500000003315711757206346025726 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.ReferenceList; import org.restlet.engine.local.DirectoryServerResource; import org.restlet.engine.util.AlphaNumericComparator; import org.restlet.engine.util.AlphabeticalComparator; import org.restlet.representation.Representation; import org.restlet.representation.Variant; /** * Finder mapping a directory of local resources. Those resources have * representations accessed by the file system, the class loaders or other URI * accessible protocols. Here is some sample code illustrating how to attach a * directory to a router:
    * *
     * Directory directory = new Directory(getContext(), "file:///user/data/files/");
     * Router router = new Router(getContext());
     * router.attach("/static/", directory);
     * 
    * * An automatic content negotiation mechanism (similar to the one in Apache HTTP * server) is used to select the best representation of a resource based on the * available variants and on the client capabilities and preferences.
    *
    * The directory can be used in read-only or modifiable mode. In the latter * case, you just need to set the "modifiable" property to true. The currently * supported methods are PUT and DELETE.
    *
    * When no index is available in a given directory, a representation can be * automatically generated by the * {@link #getIndexRepresentation(Variant, ReferenceList)} method, unless the * "listingAllowed" property is turned off. You can even customize the way the * index entries are sorted by using the {@link #setComparator(Comparator)} * method. The default sorting uses the friendly Alphanum algorithm based on * David Koelle's original * idea, using a different and faster implementation contributed by Rob * Heittman.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see User * Guide - Serving static files * @author Jerome Louvel */ public class Directory extends Finder { /** The reference comparator to sort index pages. */ private volatile Comparator comparator; /** * Indicates if the sub-directories are deeply accessible (true by default). */ private volatile boolean deeplyAccessible; /** The index name, without extensions (ex: "index" or "home"). */ private volatile String indexName; /** * Indicates if the display of directory listings is allowed when no index * file is found. */ private volatile boolean listingAllowed; /** * Indicates if modifications to local resources are allowed (false by * default). */ private volatile boolean modifiable; /** Indicates if the best content is automatically negotiated. */ private volatile boolean negotiatingContent; /** The absolute root reference (file, clap URI). */ private volatile Reference rootRef; /** * Constructor. * * @param context * The context. * @param rootLocalReference * The root URI. */ public Directory(Context context, Reference rootLocalReference) { super(context); // First, let's normalize the root reference to prevent any issue with // relative paths inside the reference leading to listing issues. final String rootIdentifier = rootLocalReference.getTargetRef() .getIdentifier(); if (rootIdentifier.endsWith("/")) { this.rootRef = new Reference(rootIdentifier); } else { // We don't take the risk of exposing directory "file:///C:/AA" // if only "file:///C:/A" was intended this.rootRef = new Reference(rootIdentifier + "/"); } this.comparator = new AlphaNumericComparator(); this.deeplyAccessible = true; this.indexName = "index"; this.listingAllowed = false; this.modifiable = false; this.negotiatingContent = true; setTargetClass(DirectoryServerResource.class); } /** * Constructor. * * @param context * The context. * @param rootUri * The absolute root URI.
    *
    * If you serve files from the file system, use file:// URIs and * make sure that you register a FILE connector with your parent * Component. On Windows, make sure that you add enough slash * characters at the beginning, for example: file:///c:/dir/file
    *
    * If you serve files from a class loader, use clap:// URIs and * make sure that you register a CLAP connector with your parent * Component.
    *
    */ public Directory(Context context, String rootUri) { this(context, new Reference(rootUri)); } /** * Returns the reference comparator used to sort index pages. The default * implementation used a friendly alphanum sorting. * * @return The reference comparator. * @see #setAlphaNumComparator() */ public Comparator getComparator() { return this.comparator; } /** * Returns the index name, without extensions. Returns "index" by default. * * @return The index name. */ public String getIndexName() { return this.indexName; } /** * Returns an actual index representation for a given variant. * * @param variant * The selected variant. * @param indexContent * The directory index to represent. * @return The actual index representation. */ public Representation getIndexRepresentation(Variant variant, ReferenceList indexContent) { Representation result = null; if (variant.getMediaType().equals(MediaType.TEXT_HTML)) { result = indexContent.getWebRepresentation(); } else if (variant.getMediaType().equals(MediaType.TEXT_URI_LIST)) { result = indexContent.getTextRepresentation(); } return result; } /** * Returns the variant representations of a directory index. This method can * be subclassed in order to provide alternative representations. * * By default it returns a simple HTML document and a textual URI list as * variants. Note that a new instance of the list is created for each call. * * @param indexContent * The list of references contained in the directory index. * @return The variant representations of a directory. */ public List getIndexVariants(ReferenceList indexContent) { final List result = new ArrayList(); result.add(new Variant(MediaType.TEXT_HTML)); result.add(new Variant(MediaType.TEXT_URI_LIST)); return result; } /** * Returns the root URI from which the relative resource URIs will be looked * up. * * @return The root URI. */ public Reference getRootRef() { return this.rootRef; } @Override public void handle(Request request, Response response) { request.getAttributes().put("org.restlet.directory", this); super.handle(request, response); } /** * Indicates if the sub-directories are deeply accessible (true by default). * * @return True if the sub-directories are deeply accessible. */ public boolean isDeeplyAccessible() { return this.deeplyAccessible; } /** * Indicates if the display of directory listings is allowed when no index * file is found. * * @return True if the display of directory listings is allowed when no * index file is found. */ public boolean isListingAllowed() { return this.listingAllowed; } /** * Indicates if modifications to local resources (most likely files) are * allowed. Returns false by default. * * @return True if modifications to local resources are allowed. */ public boolean isModifiable() { return this.modifiable; } /** * Indicates if the best content is automatically negotiated. Default value * is true. * * @return True if the best content is automatically negotiated. * @deprecated Use {@link #isNegotiatingContent()} instead. */ @Deprecated public boolean isNegotiateContent() { return this.negotiatingContent; } /** * Indicates if the best content is automatically negotiated. Default value * is true. * * @return True if the best content is automatically negotiated. */ public boolean isNegotiatingContent() { return isNegotiateContent(); } /** * Sets the reference comparator based on classic alphabetical order. * * @see #setComparator(Comparator) */ public void setAlphaComparator() { setComparator(new AlphabeticalComparator()); } /** * Sets the reference comparator based on the more friendly "Alphanum * Algorithm" created by David Koelle. The internal implementation used is * based on an optimized public domain implementation provided by Rob * Heittman from the Solertium Corporation. * * @see The original * Alphanum Algorithm from David Koelle * @see #setComparator(Comparator) */ public void setAlphaNumComparator() { setComparator(new AlphabeticalComparator()); } /** * Sets the reference comparator used to sort index pages. * * @param comparator * The reference comparator. */ public void setComparator(Comparator comparator) { this.comparator = comparator; } /** * Indicates if the sub-directories are deeply accessible (true by default). * * @param deeplyAccessible * True if the sub-directories are deeply accessible. */ public void setDeeplyAccessible(boolean deeplyAccessible) { this.deeplyAccessible = deeplyAccessible; } /** * Sets the index name, without extensions. * * @param indexName * The index name. */ public void setIndexName(String indexName) { this.indexName = indexName; } /** * Indicates if the display of directory listings is allowed when no index * file is found. * * @param listingAllowed * True if the display of directory listings is allowed when no * index file is found. */ public void setListingAllowed(boolean listingAllowed) { this.listingAllowed = listingAllowed; } /** * Indicates if modifications to local resources are allowed. * * @param modifiable * True if modifications to local resources are allowed. */ public void setModifiable(boolean modifiable) { this.modifiable = modifiable; } /** * Indicates if the best content is automatically negotiated. Default value * is true. * * @param negotiatingContent * True if the best content is automatically negotiated. * @deprecated Use {@link #setNegotiatingContent(boolean)} instead. */ @Deprecated public void setNegotiateContent(boolean negotiatingContent) { this.negotiatingContent = negotiatingContent; } /** * Indicates if the best content is automatically negotiated. Default value * is true. * * @param negotiatingContent * True if the best content is automatically negotiated. */ public void setNegotiatingContent(boolean negotiatingContent) { setNegotiateContent(negotiatingContent); } /** * Sets the root URI from which the relative resource URIs will be lookep * up. * * @param rootRef * The root URI. */ public void setRootRef(Reference rootRef) { this.rootRef = rootRef; } } restlet-2.0.14/org.restlet/src/org/restlet/resource/Get.java0000664000175000017500000000521711757206346024475 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.restlet.engine.Method; import org.restlet.service.MetadataService; /** * Annotation for methods that retrieve a resource representation. Its semantics * is equivalent to an HTTP GET method.
    *
    * Example: * *
     * @Get
     * public MyBean represent();
     * 
     * @Get("json")
     * public String toJson();
     * 
     * @Get("xml|html")
     * public Representation represent();
     * 
    * * @author Jerome Louvel */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Method("GET") public @interface Get { /** * Specifies the media type extension of the response entity. If several * media types are supported, their extension can be specified separated by * "|" characters. Note that this isn't the full MIME type value, just the * extension name declared in {@link MetadataService}. For a list of all * predefined extensions, please check * {@link MetadataService#addCommonExtensions()}. New extension can be * registered using * {@link MetadataService#addExtension(String, org.restlet.data.Metadata)} * method. * * @return The result media types. */ String value() default ""; } restlet-2.0.14/org.restlet/src/org/restlet/Client.java0000664000175000017500000001644711757206346023354 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.Arrays; import java.util.List; import org.restlet.data.Protocol; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.engine.RestletHelper; /** * Connector acting as a generic client. It internally uses one of the available * connector helpers registered with the Restlet engine.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel */ public class Client extends Connector { /** * The number of milliseconds the client should wait for a response before * aborting the request and setting its status to an error status. */ private volatile int connectTimeout = 0; /** The helper provided by the implementation. */ private final RestletHelper helper; /** * Constructor. * * @param context * The context. * @param protocols * The connector protocols. */ public Client(Context context, List protocols) { this(context, protocols, null); } /** * Constructor. * * @param context * The context. * @param protocols * The connector protocols. * @param helperClass * Optional helper class name. */ public Client(Context context, List protocols, String helperClass) { super(context, protocols); if ((protocols != null) && (protocols.size() > 0)) { if (Engine.getInstance() != null) { this.helper = Engine.getInstance().createHelper(this, helperClass); } else { this.helper = null; } } else { this.helper = null; } } /** * Constructor. * * @param context * The context. * @param protocol * The connector protocol. */ public Client(Context context, Protocol protocol) { this(context, (protocol == null) ? null : Arrays.asList(protocol), null); } /** * Constructor. * * @param protocols * The connector protocols. */ public Client(List protocols) { this(null, protocols, null); } /** * Constructor. * * @param protocol * The connector protocol. */ public Client(Protocol protocol) { this(null, protocol); } /** * Constructor. * * @param protocolName * The connector protocol. */ public Client(String protocolName) { this(Protocol.valueOf(protocolName)); } /** * Returns the connection timeout in milliseconds. The default value is 0, * meaning an infinite timeout. * * @return The connection timeout. */ public int getConnectTimeout() { return this.connectTimeout; } /** * Returns the helper provided by the implementation. * * @return The helper provided by the implementation. */ private RestletHelper getHelper() { return this.helper; } /** * Handles a call. * * @param request * The request to handle. * @return The returned response. */ public final Response handle(Request request) { Response response = new Response(request); handle(request, response); return response; } @Override public void handle(Request request, Response response) { super.handle(request, response); if (getHelper() != null) { getHelper().handle(request, response); } else { StringBuilder sb = new StringBuilder(); sb .append("No available client connector supports the required protocol: "); sb.append("'").append(request.getProtocol().getName()).append("'."); sb .append(" Please add the JAR of a matching connector to your classpath."); response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, sb.toString()); } } /** * Handles a call. * * @param request * The request to handle. * @param response * The response to update. * @param onResponseCallback * The callback invoked upon response reception. */ public void handle(Request request, Response response, Uniform onResponseCallback) { request.setOnResponse(onResponseCallback); handle(request, response); } /** * Handles a call. * * @param request * The request to handle. * @param onReceivedCallback * The callback invoked upon request reception. */ public final void handle(Request request, Uniform onReceivedCallback) { Response response = new Response(request); handle(request, response, onReceivedCallback); } /** * Indicates the underlying connector helper is available. * * @return True if the underlying connector helper is available. */ @Override public boolean isAvailable() { return getHelper() != null; } /** * Sets the connection timeout in milliseconds. The default value is 0, * meaning an infinite timeout. * * @param connectTimeout * The connection timeout. */ public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } @Override public synchronized void start() throws Exception { if (isStopped()) { super.start(); if (getHelper() != null) { getHelper().start(); } } } @Override public synchronized void stop() throws Exception { if (isStarted()) { if (getHelper() != null) { getHelper().stop(); } super.stop(); } } } restlet-2.0.14/org.restlet/src/org/restlet/data/0000775000175000017500000000000011757206350022163 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/data/Form.java0000664000175000017500000001771111757206346023745 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.io.IOException; import java.util.List; import org.restlet.engine.util.FormUtils; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.util.Series; /** * Form which is a specialized modifiable list of parameters. * * @see User * Guide - Getting parameter values * @author Jerome Louvel */ public class Form extends Series { /** * Empty constructor. */ public Form() { super(); } /** * Constructor. * * @param initialCapacity * The initial list capacity. */ public Form(int initialCapacity) { super(initialCapacity); } /** * Constructor. * * @param delegate * The delegate list. */ public Form(List delegate) { super(delegate); } /** * Constructor. * * @param webForm * The URL encoded Web form. * @throws IOException */ public Form(Representation webForm) { FormUtils.parse(this, webForm); } /** * Constructor. Uses UTF-8 as the character set for encoding non-ASCII * characters. * * @param queryString * The Web form parameters as a string. * @throws IOException */ public Form(String queryString) { this(queryString, CharacterSet.UTF_8); } /** * Constructor. Uses UTF-8 as the character set for encoding non-ASCII * characters. * * @param parametersString * The parameters string to parse. * @param separator * The separator character to append between parameters. * @throws IOException */ public Form(String parametersString, char separator) { this(parametersString, CharacterSet.UTF_8, separator); } /** * Constructor. * * @param queryString * The Web form parameters as a string. * @param characterSet * The supported character encoding. * @throws IOException */ public Form(String queryString, CharacterSet characterSet) { this(queryString, characterSet, '&'); } /** * Constructor. * * @param parametersString * The parameters string to parse. * @param characterSet * The supported character encoding. * @param separator * The separator character to append between parameters. * @throws IOException */ public Form(String parametersString, CharacterSet characterSet, char separator) { FormUtils.parse(this, parametersString, characterSet, true, separator); } @Override public Parameter createEntry(String name, String value) { return new Parameter(name, value); } @Override public Series createSeries(List delegate) { if (delegate != null) { return new Form(delegate); } return new Form(); } /** * Encodes the form using the standard URI encoding mechanism and the UTF-8 * character set. * * @return The encoded form. * @throws IOException */ public String encode() throws IOException { return encode(CharacterSet.UTF_8); } /** * URL encodes the form. The '&' character is used as a separator. * * @param characterSet * The supported character encoding. * @return The encoded form. * @throws IOException */ public String encode(CharacterSet characterSet) throws IOException { return encode(characterSet, '&'); } /** * URL encodes the form. * * @param characterSet * The supported character encoding. * @param separator * The separator character to append between parameters. * @return The encoded form. * @throws IOException */ public String encode(CharacterSet characterSet, char separator) throws IOException { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < size(); i++) { if (i > 0) { sb.append(separator); } get(i).encode(sb, characterSet); } return sb.toString(); } /** * Formats the form as a matrix path string. Uses UTF-8 as the character set * for encoding non-ASCII characters. * * @return The form as a matrix string. * @see Matrix URIs * by Tim Berners Lee */ public String getMatrixString() { return getMatrixString(CharacterSet.UTF_8); } /** * Formats the form as a query string. * * @param characterSet * The supported character encoding. * @return The form as a matrix string. * @see Matrix URIs * by Tim Berners Lee */ public String getMatrixString(CharacterSet characterSet) { try { return encode(characterSet, ';'); } catch (IOException ioe) { return null; } } /** * Formats the form as a query string. Uses UTF-8 as the character set for * encoding non-ASCII characters. * * @return The form as a query string. */ public String getQueryString() { return getQueryString(CharacterSet.UTF_8); } /** * Formats the form as a query string. * * @param characterSet * The supported character encoding. * @return The form as a query string. */ public String getQueryString(CharacterSet characterSet) { try { return encode(characterSet); } catch (IOException ioe) { return null; } } /** * Returns the form as a Web representation * (MediaType.APPLICATION_WWW_FORM). Uses UTF-8 as the character set for * encoding non-ASCII characters. * * @return The form as a Web representation. */ public Representation getWebRepresentation() { return getWebRepresentation(CharacterSet.UTF_8); } /** * Returns the form as a Web representation * (MediaType.APPLICATION_WWW_FORM). * * @param characterSet * The supported character encoding. * @return The form as a Web representation. */ public Representation getWebRepresentation(CharacterSet characterSet) { return new StringRepresentation(getQueryString(characterSet), MediaType.APPLICATION_WWW_FORM, null, characterSet); } } restlet-2.0.14/org.restlet/src/org/restlet/data/ServerInfo.java0000664000175000017500000001202211757206346025112 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Server specific data related to a call. * * @author Jerome Louvel */ public final class ServerInfo { /** Indicates if the server accepts range requests for a resource. */ private volatile boolean acceptingRanges; /** The IP address. */ private volatile String address; /** The agent name. */ private volatile String agent; /** The port number. */ private volatile int port; /** * Constructor. */ public ServerInfo() { this.address = null; this.agent = null; this.port = -1; this.acceptingRanges = false; } /** * Returns the IP address. * * @return The IP address. */ public String getAddress() { return this.address; } /** * Returns the agent name (ex: "Restlet-Framework/2.0"). Note that when used * with HTTP connectors, this property maps to the "Server" header. * * @return The agent name. */ public String getAgent() { return this.agent; } /** * Returns the port number which received the call. If no port is specified, * -1 is returned. * * @return The port number which received the call. */ public int getPort() { return this.port; } /** * Return true if the server accepts range requests for a resource, with the * "byte" range unit. Note that when used with HTTP connectors, this * property maps to the "Accept-Ranges" header. * * @return True if the server accepts range requests for a resource. */ public boolean isAcceptingRanges() { return isAcceptRanges(); } /** * Return true if the server accepts range requests for a resource, with the * "byte" range unit. Note that when used with HTTP connectors, this * property maps to the "Accept-Ranges" header. * * @return True if the server accepts range requests for a resource. * @deprecated Use {@link #isAcceptingRanges()} instead. */ @Deprecated public boolean isAcceptRanges() { return acceptingRanges; } /** * Indicates if the server accepts range requests for a resource, with the * "byte" range unit. Note that when used with HTTP connectors, this * property maps to the "Accept-Ranges" header. * * @param acceptingRanges * True if the server accepts range requests for a resource. */ public void setAcceptingRanges(boolean acceptingRanges) { setAcceptRanges(acceptingRanges); } /** * Indicates if the server accepts range requests for a resource, with the * "byte" range unit. Note that when used with HTTP connectors, this * property maps to the "Accept-Ranges" header. * * @param acceptingRanges * True if the server accepts range requests for a resource. * @deprecated Use {@link #setAcceptingRanges(boolean)} instead. */ @Deprecated public void setAcceptRanges(boolean acceptingRanges) { this.acceptingRanges = acceptingRanges; } /** * Sets the IP address which received the call. * * @param address * The IP address which received the call. */ public void setAddress(String address) { this.address = address; } /** * Sets the agent name (ex: "Restlet-Framework/2.0"). Note that when used * with HTTP connectors, this property maps to the "Server" header. * * @param agent * The agent name. */ public void setAgent(String agent) { this.agent = agent; } /** * Sets the port number which received the call. * * @param port * The port number which received the call. */ public void setPort(int port) { this.port = port; } } restlet-2.0.14/org.restlet/src/org/restlet/data/Range.java0000664000175000017500000001316011757206346024070 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Describes a range of bytes. * * @author Jerome Louvel */ public class Range { /** * Index for the first byte of an entity. */ public final static long INDEX_FIRST = 0; /** * Index for the last byte of an entity. */ public final static long INDEX_LAST = -1; /** * Maximum size available from the index. */ public final static long SIZE_MAX = -1; /** * Index from which to start the range. If the index is superior or equal to * zero, the index will define the start of the range. If its value is * {@value #INDEX_LAST} (-1), then it defines the end of the range. The * default value is {@link #INDEX_FIRST} (0), starting at the first byte. */ private volatile long index; /** * Size of the range in number of bytes. If the size is the maximum * available from the index, then use the {@value #SIZE_MAX} constant. */ private volatile long size; /** * Default constructor defining a range starting on the first byte and with * a maximum size, i.e. covering the whole entity. */ public Range() { this(INDEX_FIRST, SIZE_MAX); } /** * Constructor defining a range starting on the first byte and with the * given size. * * @param size * Size of the range in number of bytes. */ public Range(long size) { this(INDEX_FIRST, size); } /** * Constructor. * * @param index * Index from which to start the range * @param size * Size of the range in number of bytes. */ public Range(long index, long size) { this.index = index; this.size = size; } @Override public boolean equals(Object object) { return (object instanceof Range) && ((Range) object).getIndex() == getIndex() && ((Range) object).getSize() == getSize(); } /** * Returns the index from which to start the range. If the index is superior * or equal to zero, the index will define the start of the range. If its * value is {@value #INDEX_LAST} (-1), then it defines the end of the range. * The default value is {@link #INDEX_FIRST} (0), starting at the first * byte. * * @return The index from which to start the range. */ public long getIndex() { return index; } /** * Returns the size of the range in number of bytes. If the size is the * maximum available from the index, then use the {@value #SIZE_MAX} * constant. * * @return The size of the range in number of bytes. */ public long getSize() { return size; } /** * Indicates if the given index is included in the range. * * @param position * The position to test. * @param totalSize * * @return True if the given index is included in the range, false * otherwise. */ public boolean isIncluded(long position, long totalSize) { boolean result = false; if (getIndex() == INDEX_LAST) { // The range starts from the end result = (0 <= position) && (position < totalSize); if (result) { result = position >= (totalSize - getSize()); } } else { // The range starts from the beginning result = position >= getIndex(); if (result && (getSize() != SIZE_MAX)) { result = position < getIndex() + getSize(); } } return result; } /** * Sets the index from which to start the range. If the index is superior or * equal to zero, the index will define the start of the range. If its value * is {@value #INDEX_LAST} (-1), then it defines the end of the range. The * default value is {@link #INDEX_FIRST} (0), starting at the first byte * * @param index * The index from which to start the range. */ public void setIndex(long index) { this.index = index; } /** * Sets the size of the range in number of bytes. If the size is the maximum * available from the index, then use the {@value #SIZE_MAX} constant. * * @param size * The size of the range in number of bytes. */ public void setSize(long size) { this.size = size; } } restlet-2.0.14/org.restlet/src/org/restlet/data/CharacterSet.java0000664000175000017500000002623611757206346025414 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Character set used to encode characters in textual representations. * * @author Jerome Louvel */ public final class CharacterSet extends Metadata { /** All character sets acceptable. */ public static final CharacterSet ALL = new CharacterSet("*", "All character sets"); /** * The ISO/IEC 8859-1 (Latin 1) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_1 = new CharacterSet( "ISO-8859-1", "ISO/IEC 8859-1 or Latin 1 character set"); /** * The ISO/IEC 8859-2 (Latin 2) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_2 = new CharacterSet( "ISO-8859-2", "ISO/IEC 8859-2 or Latin 2 character set"); /** * The ISO/IEC 8859-3 (Latin 3) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_3 = new CharacterSet( "ISO-8859-3", "ISO/IEC 8859-3 or Latin 3 character set"); /** * The ISO/IEC 8859-4 (Latin 4) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_4 = new CharacterSet( "ISO-8859-4", "ISO/IEC 8859-4 or Latin 4 character set"); /** * The ISO/IEC 8859-5 (Cyrillic) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_5 = new CharacterSet( "ISO-8859-5", "ISO/IEC 8859-5 or Cyrillic character set"); /** * The ISO/IEC 8859-6 (Arabic) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_6 = new CharacterSet( "ISO-8859-6", "ISO/IEC 8859-6 or Arabic character set"); /** * The ISO/IEC 8859-7 (Greek) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_7 = new CharacterSet( "ISO-8859-7", "ISO/IEC 8859-7 or Greek character set"); /** * The ISO/IEC 8859-8 (Hebrew) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_8 = new CharacterSet( "ISO-8859-8", "ISO/IEC 8859-8 or Hebrew character set"); /** * The ISO/IEC 8859-9 (Latin 5) character set. * * @see Wikipedia page */ public static final CharacterSet ISO_8859_9 = new CharacterSet( "ISO-8859-9", "ISO/IEC 8859-9 or Latin 5 character set"); /** * The ISO/IEC 8859-10 (Latin 6) character set. * * @see Wikipedia * page */ public static final CharacterSet ISO_8859_10 = new CharacterSet( "ISO-8859-10", "ISO/IEC 8859-10 or Latin 6 character set"); /** * The Macintosh ("Mac OS Roman") character set. * * @see Wikipedia * page */ public static final CharacterSet MACINTOSH = new CharacterSet("macintosh", "Mac OS Roman character set"); /** * The US-ASCII character set. * * @see Wikipedia page */ public static final CharacterSet US_ASCII = new CharacterSet("US-ASCII", "US ASCII character set"); /** * The UTF-16 character set. * * @see Wikipedia page */ public static final CharacterSet UTF_16 = new CharacterSet("UTF-16", "UTF 16 character set"); /** * The UTF-8 character set. * * @see Wikipedia page */ public static final CharacterSet UTF_8 = new CharacterSet("UTF-8", "UTF 8 character set"); /** * The Windows-1252 ('ANSI') character set. * * @see Wikipedia * page * */ public static final CharacterSet WINDOWS_1252 = new CharacterSet( "windows-1252", "Windows 1232 character set"); /** * The default character set of the JVM. * * @see java.nio.charset.Charset#defaultCharset() */ public static final CharacterSet DEFAULT = new CharacterSet( java.nio.charset.Charset.defaultCharset()); /** * Handles mapping between Java character set names and IANA preferred name. * For example, "MACROMAN" is not an official IANA name and "ISO-8859-6" is * preferred over "arabic". * * @param name * The character set name. * @return The IANA character set name. */ private static String getIanaName(String name) { if (name != null) { name = name.toUpperCase(); if (name.equalsIgnoreCase("MACROMAN")) { name = MACINTOSH.getName(); } else if (name.equalsIgnoreCase("ASCII")) { name = US_ASCII.getName(); } else if (name.equalsIgnoreCase("latin1")) { name = ISO_8859_1.getName(); } else if (name.equalsIgnoreCase("latin2")) { name = ISO_8859_2.getName(); } else if (name.equalsIgnoreCase("latin3")) { name = ISO_8859_3.getName(); } else if (name.equalsIgnoreCase("latin4")) { name = ISO_8859_4.getName(); } else if (name.equalsIgnoreCase("cyrillic")) { name = ISO_8859_5.getName(); } else if (name.equalsIgnoreCase("arabic")) { name = ISO_8859_6.getName(); } else if (name.equalsIgnoreCase("greek")) { name = ISO_8859_7.getName(); } else if (name.equalsIgnoreCase("hebrew")) { name = ISO_8859_8.getName(); } else if (name.equalsIgnoreCase("latin5")) { name = ISO_8859_9.getName(); } else if (name.equalsIgnoreCase("latin6")) { name = ISO_8859_10.getName(); } } return name; } /** * Returns the character set associated to a name. If an existing constant * exists then it is returned, otherwise a new instance is created. * * @param name * The name. * @return The associated character set. */ public static CharacterSet valueOf(String name) { CharacterSet result = null; name = getIanaName(name); if ((name != null) && !name.equals("")) { if (name.equalsIgnoreCase(ALL.getName())) { result = ALL; } else if (name.equalsIgnoreCase(ISO_8859_1.getName())) { result = ISO_8859_1; } else if (name.equalsIgnoreCase(US_ASCII.getName())) { result = US_ASCII; } else if (name.equalsIgnoreCase(UTF_8.getName())) { result = UTF_8; } else if (name.equalsIgnoreCase(UTF_16.getName())) { result = UTF_16; } else if (name.equalsIgnoreCase(WINDOWS_1252.getName())) { result = WINDOWS_1252; } else if (name.equalsIgnoreCase(MACINTOSH.getName())) { result = MACINTOSH; } else { result = new CharacterSet(name); } } return result; } /** * Constructor. * * @param charset * The character set. */ public CharacterSet(final java.nio.charset.Charset charset) { this(charset.name(), charset.displayName()); } /** * Constructor. * * @param name * The name. */ public CharacterSet(String name) { this(name == null ? null : name.toUpperCase(), "Character set or range of character sets"); } /** * Constructor. * * @param name * The name. * @param description * The description. */ public CharacterSet(String name, String description) { super(getIanaName(name), description); } /** {@inheritDoc} */ @Override public boolean equals(Object object) { return (object instanceof CharacterSet) && getName() .equalsIgnoreCase(((CharacterSet) object).getName()); } @Override public Metadata getParent() { return equals(ALL) ? null : ALL; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().toLowerCase().hashCode(); } /** * Indicates if a given character set is included in the current one. The * test is true if both character sets are equal or if the given character * set is within the range of the current one. For example, ALL includes all * character sets. A null character set is considered as included into the * current one. *

    * Examples: *

      *
    • ALL.includes(UTF_16) -> true
    • *
    • UTF_16.includes(ALL) -> false
    • *
    * * @param included * The character set to test for inclusion. * @return True if the given character set is included in the current one. * @see #isCompatible(Metadata) */ public boolean includes(Metadata included) { return equals(ALL) || (included == null) || equals(included); } /** * Returns the NIO charset matching the character set name. * * @return The NIO charset. */ public java.nio.charset.Charset toCharset() { return java.nio.charset.Charset.forName(getName()); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Disposition.java0000664000175000017500000001521511757206346025343 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.Date; import org.restlet.engine.util.DateUtils; import org.restlet.util.Series; /** * Describes the presentation of a single entity especially in the case of * multipart documents. This is an equivalent of the HTTP "Content-Disposition" * header. * * @see Content-Disposition header * @see The Content-Disposition * Header Field * * @author Thierry Boileau */ public class Disposition { /** The creation date parameter name as presented by the RFC 2183. */ public static final String NAME_CREATION_DATE = "creation-date"; /** The filename parameter name as presented by the RFC 2183. */ public static final String NAME_FILENAME = "filename"; /** The modification date parameter name as presented by the RFCc 2183. */ public static final String NAME_MODIFICATION_DATE = "modification-date"; /** The read date parameter name as presented by the RFC 2183. */ public static final String NAME_READ_DATE = "read-date"; /** The size parameter name as presented by the RFC 2183. */ public static final String NAME_SIZE = "size"; /** * Indicates that the part is intended to be separated from the full * message. */ public static final String TYPE_ATTACHMENT = "attachment"; /** * Indicates that the part is intended to be displayed automatically upon * display of the full message. */ public static final String TYPE_INLINE = "inline"; /** Indicates that the part is not intended to be displayed. */ public static final String TYPE_NONE = "none"; /** The list of disposition parameters. */ private Series parameters; /** The disposition type. */ private String type; /** * Constructor. Instantiated with the TYPE_NONE type. */ public Disposition() { this(Disposition.TYPE_NONE); } /** * Constructor. * * @param type * The disposition type. */ public Disposition(String type) { super(); this.type = type; } /** * Constructor. * * @param type * The disposition type. * @param parameters * The list of disposition parameters. */ public Disposition(String type, Series parameters) { this(type); this.parameters = parameters; } /** * Adds a Date parameter. * * @param name * The name of the parameter. * @param value * Its value as a date. */ public void addDate(String name, Date value) { getParameters().add(name, DateUtils.format(value, DateUtils.FORMAT_RFC_822.get(0))); } /** * Returns the value of the "filename" parameter. * * @return The value of the "filename" parameter. */ public String getFilename() { return getParameters().getFirstValue(NAME_FILENAME, true); } /** * Returns the list of disposition parameters. * * @return The list of disposition parameters. */ public Series getParameters() { if (this.parameters == null) { this.parameters = new Form(); } return this.parameters; } /** * Returns the disposition type. * * @return The disposition type. */ public String getType() { return type; } /** * Sets the creation date parameter. * * @param value * The creation date. */ public void setCreationDate(Date value) { setDate(NAME_CREATION_DATE, value); } /** * Sets a Date parameter. * * @param name * The name of the parameter. * @param value * Its value as a date. */ public void setDate(String name, Date value) { getParameters().set(name, DateUtils.format(value, DateUtils.FORMAT_RFC_822.get(0)), true); } /** * Sets the value of the "filename" parameter. * * @param fileName * The file name value. */ public void setFilename(String fileName) { getParameters().set(Disposition.NAME_FILENAME, fileName, true); } /** * Sets the modification date parameter. * * @param value * The modification date. */ public void setModificationDate(Date value) { setDate(NAME_MODIFICATION_DATE, value); } /** * Sets the list of disposition parameters. * * @param parameters * The list of disposition parameters. */ public void setParameters(Series parameters) { this.parameters = parameters; } /** * Sets the read date parameter. * * @param value * The read date. */ public void setReadDate(Date value) { setDate(NAME_READ_DATE, value); } /** * Sets the value of the "size" parameter. * * @param size * The size. */ public void setSize(long size) { getParameters().set(Disposition.NAME_SIZE, Long.toString(size), true); } /** * Sets the disposition type. * * @param type * The disposition type. */ public void setType(String type) { this.type = type; } } restlet-2.0.14/org.restlet/src/org/restlet/data/AuthenticationInfo.java0000664000175000017500000002005111757206346026624 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.engine.util.SystemUtils; /** * Preemptive authentication information. Sent by an origin server to a client * after a successful digest authentication attempt.
    *
    * Note that when used with HTTP connectors, this class maps to the * "Authentication-Info" header. * * @see HTTP * Authentication - The Authentication-Info Header * * @author Kelly McLaughlin * @author Jerome Louvel */ public class AuthenticationInfo { /** The next nonce value. */ private volatile String nextServerNonce; /** The nonce-count value. */ private volatile int nonceCount; /** The client nonce. */ private volatile String clientNonce; /** The quality of protection. */ private volatile String quality; /** The optional response digest for mutual authentication. */ private volatile String responseDigest; /** * Default constructor. * * @param nextNonce * The next nonce value. */ // public AuthenticationInfo(String nextNonce) { // this(nextNonce, 0, ); // } /** * Constructor. * * @param nextNonce * The next nonce value. * @param nonceCount * The nonce-count value. * @param cnonce * The cnonce value. * @param quality * The quality of protection. * @param responseDigest * The optional response digest for mutual authentication. */ public AuthenticationInfo(String nextNonce, int nonceCount, String cnonce, String quality, String responseDigest) { this.nextServerNonce = nextNonce; this.nonceCount = nonceCount; this.clientNonce = cnonce; this.quality = quality; this.responseDigest = responseDigest; } /** {@inheritDoc} */ @Override public final boolean equals(final Object obj) { boolean result = (obj == this); // if obj == this no need to go further if (!result) { // if obj isn't a challenge request or is null don't evaluate // further if (obj instanceof AuthenticationInfo) { final AuthenticationInfo that = (AuthenticationInfo) obj; if (getNextServerNonce() != null) { result = getNextServerNonce().equals( that.getNextServerNonce()); } else { result = (that.getNextServerNonce() == null); } if (result) { result = (getNonceCount() == that.getNonceCount()); } if (result) { if (getClientNonce() != null) { result = getClientNonce().equals(that.getClientNonce()); } else { result = (that.getClientNonce() == null); } } if (result) { if (getQuality() != null) { result = getQuality().equals(that.getQuality()); } else { result = (that.getQuality() == null); } } if (result) { if (getResponseDigest() != null) { result = getResponseDigest().equals( that.getResponseDigest()); } else { result = (that.getResponseDigest() == null); } } } } return result; } /** * Returns the client nonce. * * @return The client nonce. */ public String getClientNonce() { return this.clientNonce; } /** * Returns the next server nonce. This is the nonce the server wishes the * client to use for a future authentication response * * @return The next nonce value. */ public String getNextServerNonce() { return this.nextServerNonce; } /** * Returns the nonce-count value. * * @return The nonce-count value. */ public int getNonceCount() { return this.nonceCount; } /** * Returns the quality of protection. The value can be * {@link ChallengeMessage#QUALITY_AUTHENTICATION} for authentication or * {@link ChallengeMessage#QUALITY_AUTHENTICATION_INTEGRITY} for * authentication with integrity protection. * * @return The quality of protection. */ public String getQuality() { return this.quality; } /** * Returns the optional response digest for mutual authentication. Note that * when used with HTTP connectors, this property maps to the * "response-digest" value in the "response-auth" directive of the * "Authentication-Info" header. * * @return The optional response digest for mutual authentication. */ public String getResponseDigest() { return this.responseDigest; } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(getNextServerNonce(), getNonceCount(), getClientNonce(), getQuality(), getResponseDigest()); } /** * Sets the client nonce. * * @param clientNonce * The client nonce. */ public void setClientNonce(String clientNonce) { this.clientNonce = clientNonce; } /** * Sets the next server nonce. This is the nonce the server wishes the * client to use for a future authentication response * * @param nextNonce * The next nonce. */ public void setNextServerNonce(String nextNonce) { this.nextServerNonce = nextNonce; } /** * Sets the nonce-count value. * * @param nonceCount * The nonceCount value. */ public void setNonceCount(int nonceCount) { this.nonceCount = nonceCount; } /** * Sets the quality of protection. The value can be * {@link ChallengeMessage#QUALITY_AUTHENTICATION} for authentication or * {@link ChallengeMessage#QUALITY_AUTHENTICATION_INTEGRITY} for * authentication with integrity protection. * * @param qop * The quality of protection. */ public void setQuality(String qop) { this.quality = qop; } /** * Sets the optional response digest for mutual authentication. Note that * when used with HTTP connectors, this property maps to the * "response-digest" value in the "response-auth" directive of the * "Authentication-Info" header. * * @param responseDigest * The response digest. */ public void setResponseDigest(String responseDigest) { this.responseDigest = responseDigest; } } restlet-2.0.14/org.restlet/src/org/restlet/data/Tag.java0000664000175000017500000001477011757206346023557 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.logging.Level; import org.restlet.Context; import org.restlet.representation.RepresentationInfo; /** * Validation tag equivalent to an HTTP entity tag (E-Tag). "A strong entity tag * may be shared by two entities of a resource only if they are equivalent by * octet equality.
    *
    * A weak entity tag may be shared by two entities of a resource only if the * entities are equivalent and could be substituted for each other with no * significant change in semantics." * * @see RepresentationInfo#getTag() * @see HTTP * Entity Tags * @see HTTP * Entity Tag Cache Validators * @author Jerome Louvel */ public final class Tag { /** Tag matching any other tag, used in call's condition data. */ public static final Tag ALL = Tag.parse("*"); /** * Parses a tag formatted as defined by the HTTP standard. * * @param httpTag * The HTTP tag string; if it starts with 'W/' the tag will be * marked as weak and the data following the 'W/' used as the * tag; otherwise it should be surrounded with quotes (e.g., * "sometag"). * @return A new tag instance. * @see HTTP * Entity Tags */ public static Tag parse(String httpTag) { Tag result = null; boolean weak = false; String httpTagCopy = httpTag; if (httpTagCopy.startsWith("W/")) { weak = true; httpTagCopy = httpTagCopy.substring(2); } if (httpTagCopy.startsWith("\"") && httpTagCopy.endsWith("\"")) { result = new Tag( httpTagCopy.substring(1, httpTagCopy.length() - 1), weak); } else if (httpTagCopy.equals("*")) { result = new Tag("*", weak); } else { Context.getCurrentLogger().log(Level.WARNING, "Invalid tag format detected: " + httpTagCopy); } return result; } /** The name. */ private volatile String name; /** The tag weakness. */ private final boolean weak; /** * Default constructor. The opaque tag is set to null and the weakness * indicator is set to true. */ public Tag() { this(null, true); } /** * Constructor of weak tags. * * @param opaqueTag * The tag value. */ public Tag(final String opaqueTag) { this(opaqueTag, true); } /** * Constructor. * * @param opaqueTag * The tag value. * @param weak * The weakness indicator. */ public Tag(final String opaqueTag, boolean weak) { this.name = opaqueTag; this.weak = weak; } /** * Indicates if both tags are equal. * * @param object * The object to compare to. * @return True if both tags are equal. */ @Override public boolean equals(final Object object) { return equals(object, true); } /** * Indicates if both tags are equal. * * @param object * The object to compare to. * @param checkWeakness * the equality test takes care or not of the weakness. * * @return True if both tags are equal. */ public boolean equals(final Object object, boolean checkWeakness) { boolean result = (object != null) && (object instanceof Tag); if (result) { final Tag that = (Tag) object; if (checkWeakness) { result = (that.isWeak() == isWeak()); } if (result) { if (getName() == null) { result = (that.getName() == null); } else { result = getName().equals(that.getName()); } } } return result; } /** * Returns tag formatted as an HTTP tag string. * * @return The formatted HTTP tag string. * @see HTTP * Entity Tags */ public String format() { if (getName().equals("*")) { return "*"; } final StringBuilder sb = new StringBuilder(); if (isWeak()) { sb.append("W/"); } return sb.append('"').append(getName()).append('"').toString(); } /** * Returns the name, corresponding to an HTTP opaque tag value. * * @return The name, corresponding to an HTTP opaque tag value. */ public String getName() { return this.name; } /** {@inheritDoc} */ @Override public int hashCode() { return format().hashCode(); } /** * Indicates if the tag is weak. * * @return True if the tag is weak, false if the tag is strong. */ public boolean isWeak() { return this.weak; } /** * Returns the name. * * @return The name. */ @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/data/CookieSetting.java0000664000175000017500000002315611757206346025611 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.Response; import org.restlet.engine.util.SystemUtils; /** * Cookie setting provided by a server. This allows a server side application to * add, modify or remove a cookie on the client.
    *
    * Note that when used with HTTP connectors, this class maps to the "Set-Cookie" * and "Set-Cookie2" headers. * * @see Response#getCookieSettings() * @author Jerome Louvel */ public final class CookieSetting extends Cookie { /** * Indicates whether to restrict cookie access to untrusted parties. * Currently this toggles the non-standard but widely supported HttpOnly * cookie parameter. */ private volatile boolean accessRestricted; /** The user's comment. */ private volatile String comment; /** * The maximum age in seconds. Use 0 to discard an existing cookie. */ private volatile int maxAge; /** Indicates if cookie should only be transmitted by secure means. */ private volatile boolean secure; /** * Default constructor. */ public CookieSetting() { this(0, null, null); } /** * Constructor. * * @param version * The cookie's version. * @param name * The cookie's name. * @param value * The cookie's value. */ public CookieSetting(int version, String name, String value) { this(version, name, value, null, null); } /** * Constructor. * * @param version * The cookie's version. * @param name * The cookie's name. * @param value * The cookie's value. * @param path * The cookie's path. * @param domain * The cookie's domain name. */ public CookieSetting(int version, String name, String value, String path, String domain) { this(version, name, value, path, domain, null, -1, false, false); } /** * Constructor. * * @param version * The cookie's version. * @param name * The cookie's name. * @param value * The cookie's value. * @param path * The cookie's path. * @param domain * The cookie's domain name. * @param comment * The cookie's comment. * @param maxAge * Sets the maximum age in seconds.
    * Use 0 to immediately discard an existing cookie.
    * Use -1 to discard the cookie at the end of the session * (default). * @param secure * Indicates if cookie should only be transmitted by secure * means. */ public CookieSetting(int version, String name, String value, String path, String domain, String comment, int maxAge, boolean secure) { this(version, name, value, path, domain, comment, maxAge, secure, false); } /** * Constructor. * * @param version * The cookie's version. * @param name * The cookie's name. * @param value * The cookie's value. * @param path * The cookie's path. * @param domain * The cookie's domain name. * @param comment * The cookie's comment. * @param maxAge * Sets the maximum age in seconds.
    * Use 0 to immediately discard an existing cookie.
    * Use -1 to discard the cookie at the end of the session * (default). * @param secure * Indicates if cookie should only be transmitted by secure * means. * @param accessRestricted * Indicates whether to restrict cookie access to untrusted * parties. Currently this toggles the non-standard but widely * supported HttpOnly cookie parameter. */ public CookieSetting(int version, String name, String value, String path, String domain, String comment, int maxAge, boolean secure, boolean accessRestricted) { super(version, name, value, path, domain); this.comment = comment; this.maxAge = maxAge; this.secure = secure; this.accessRestricted = accessRestricted; } /** * Preferred constructor. * * @param name * The cookie's name. * @param value * The cookie's value. */ public CookieSetting(String name, String value) { this(0, name, value, null, null); } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { boolean result = (obj == this); // if obj == this no need to go further if (!result) { // test for equality at Cookie level i.e. name and value. if (super.equals(obj)) { // if obj isn't a cookie setting or is null don't evaluate // further if (obj instanceof CookieSetting) { final CookieSetting that = (CookieSetting) obj; result = (this.maxAge == that.maxAge) && (this.secure == that.secure); if (result) // if "maxAge" and "secure" properties are equal // test comments { if (!(this.comment == null)) // compare comments // taking care of nulls { result = (this.comment.equals(that.comment)); } else { result = (that.comment == null); } } } } } return result; } /** * Returns the comment for the user. * * @return The comment for the user. */ public String getComment() { return this.comment; } /** * Returns the description of this REST element. * * @return The description of this REST element. */ public String getDescription() { return "Cookie setting"; } /** * Returns the maximum age in seconds. Use 0 to immediately discard an * existing cookie. Use -1 to discard the cookie at the end of the session * (default). * * @return The maximum age in seconds. */ public int getMaxAge() { return this.maxAge; } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(super.hashCode(), getComment(), getMaxAge(), isSecure()); } /** * Indicates if cookie access is restricted for untrusted parties. Currently * this toggles the non-standard but widely supported HttpOnly cookie * parameter. * * @return accessRestricted True if cookie access should be restricted */ public boolean isAccessRestricted() { return this.accessRestricted; } /** * Indicates if cookie should only be transmitted by secure means. * * @return True if cookie should only be transmitted by secure means. */ public boolean isSecure() { return this.secure; } /** * Indicates whether to restrict cookie access to untrusted parties. * Currently this toggles the non-standard but widely supported HttpOnly * cookie parameter. * * @param accessRestricted * True if cookie access should be restricted */ public void setAccessRestricted(boolean accessRestricted) { this.accessRestricted = accessRestricted; } /** * Sets the comment for the user. * * @param comment * The comment for the user. */ public void setComment(String comment) { this.comment = comment; } /** * Sets the maximum age in seconds. Use 0 to immediately discard an existing * cookie. Use -1 to discard the cookie at the end of the session (default). * * @param maxAge * The maximum age in seconds. */ public void setMaxAge(int maxAge) { this.maxAge = maxAge; } /** * Indicates if cookie should only be transmitted by secure means. * * @param secure * True if cookie should only be transmitted by secure means. */ public void setSecure(boolean secure) { this.secure = secure; } } restlet-2.0.14/org.restlet/src/org/restlet/data/Encoding.java0000664000175000017500000001306111757206346024562 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Modifier of a representation's media type. Useful to apply compression * without losing the identity of the underlying media type. * * @author Jerome Louvel */ public final class Encoding extends Metadata { /** All encodings acceptable. */ public static final Encoding ALL = new Encoding("*", "All encodings"); /** The common Unix file compression. */ public static final Encoding COMPRESS = new Encoding("compress", "Common Unix compression"); /** The zlib format defined by RFC 1950 and 1951. */ public static final Encoding DEFLATE = new Encoding("deflate", "Deflate compression using the zlib format"); /** The FreeMarker encoding. */ public static final Encoding FREEMARKER = new Encoding("freemarker", "FreeMarker templated representation"); /** The GNU Zip encoding. */ public static final Encoding GZIP = new Encoding("gzip", "GZip compression"); /** The default (identity) encoding. */ public static final Encoding IDENTITY = new Encoding("identity", "The default encoding with no transformation"); /** The Velocity encoding. */ public static final Encoding VELOCITY = new Encoding("velocity", "Velocity templated representation"); /** The Info-Zip encoding. */ public static final Encoding ZIP = new Encoding("zip", "Zip compression"); /** * Returns the encoding associated to a name. If an existing constant exists * then it is returned, otherwise a new instance is created. * * @param name * The name. * @return The associated encoding. */ public static Encoding valueOf(final String name) { Encoding result = null; if ((name != null) && !name.equals("")) { if (name.equalsIgnoreCase(ALL.getName())) { result = ALL; } else if (name.equalsIgnoreCase(GZIP.getName())) { result = GZIP; } else if (name.equalsIgnoreCase(ZIP.getName())) { result = ZIP; } else if (name.equalsIgnoreCase(COMPRESS.getName())) { result = COMPRESS; } else if (name.equalsIgnoreCase(DEFLATE.getName())) { result = DEFLATE; } else if (name.equalsIgnoreCase(IDENTITY.getName())) { result = IDENTITY; } else if (name.equalsIgnoreCase(FREEMARKER.getName())) { result = FREEMARKER; } else if (name.equalsIgnoreCase(VELOCITY.getName())) { result = VELOCITY; } else { result = new Encoding(name); } } return result; } /** * Constructor. * * @param name * The name. */ public Encoding(final String name) { this(name, "Encoding applied to a representation"); } /** * Constructor. * * @param name * The name. * @param description * The description. */ public Encoding(final String name, final String description) { super(name, description); } /** {@inheritDoc} */ @Override public boolean equals(final Object object) { return (object instanceof Encoding) && getName().equalsIgnoreCase(((Encoding) object).getName()); } @Override public Metadata getParent() { return equals(ALL) ? null : ALL; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().toLowerCase().hashCode(); } /** * Indicates if a given encoding is included in the current one. The test is * true if both encodings are equal or if the given encoding is within the * range of the current one. For example, ALL includes all encodings. A null * encoding is considered as included into the current one. *

    * Examples: *

      *
    • ALL.includes(COMPRESS) -> true
    • *
    • COMPRESS.includes(ALL) -> false
    • *
    * * @param included * The encoding to test for inclusion. * @return True if the given encoding is included in the current one. * @see #isCompatible(Metadata) */ public boolean includes(Metadata included) { return equals(ALL) || (included == null) || equals(included); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Expectation.java0000664000175000017500000000727311757206346025327 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.engine.http.header.HeaderConstants; /** * Particular server behavior that is required by a client. Note that when used * with HTTP connectors, this class maps to the "Expect" header. * * @author Jerome Louvel */ public final class Expectation extends Parameter { /** * Creates a "100-continue" expectation. If a client will wait for a 100 * (Continue) provisional response before sending the request body, it MUST * send this expectation. A client MUST NOT send this expectation if it does * not intend to send a request entity. * * @return A new "100-continue" expectation. * @see HTTP * 1.1 - Expect header */ public static Expectation continueResponse() { return new Expectation(HeaderConstants.EXPECT_CONTINUE); } /** The list of parameters. */ private volatile List parameters; /** * Constructor for directives with no value. * * @param name * The directive name. */ public Expectation(String name) { this(name, null); } /** * Constructor for directives with a value. * * @param name * The directive name. * @param value * The directive value. */ public Expectation(String name, String value) { super(name, value); } @Override public boolean equals(Object other) { return super.equals(other); } /** * Returns the list of parameters. * * @return The list of parameters. */ public List getParameters() { // Lazy initialization with double-check. List r = this.parameters; if (r == null) { synchronized (this) { r = this.parameters; if (r == null) { this.parameters = r = new CopyOnWriteArrayList(); } } } return r; } /** * Sets the list of parameters. * * @param parameters * The list of parameters. */ public void setParameters(List parameters) { synchronized (this) { List r = getParameters(); r.clear(); r.addAll(parameters); } } } restlet-2.0.14/org.restlet/src/org/restlet/data/Conditions.java0000664000175000017500000004023311757206346025146 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.restlet.engine.util.DateUtils; import org.restlet.representation.RepresentationInfo; /** * Set of conditions applying to a request. This is equivalent to the HTTP * conditional headers. * * @see If-Match * @see If-Modified-Since * @see If-None-Match * @see If-Range * @see If-Unmodified-Since * * @author Jerome Louvel */ public final class Conditions { /** The "if-match" condition. */ private volatile List match; /** The "if-modified-since" condition. */ private volatile Date modifiedSince; /** The "if-none-match" condition. */ private volatile List noneMatch; /** The "if-range" condition as a Date. */ private volatile Date rangeDate; /** The "if-range" condition as an entity tag. */ private volatile Tag rangeTag; /** The "if-unmodified-since" condition */ private volatile Date unmodifiedSince; /** * Constructor. */ public Conditions() { } /** * Returns the modifiable list of tags that must be matched. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Match" header. * * @return The "if-match" condition. */ public List getMatch() { // Lazy initialization with double-check. List m = this.match; if (m == null) { synchronized (this) { m = this.match; if (m == null) { this.match = m = new ArrayList(); } } } return m; } /** * Returns the condition based on the modification date of the requested * variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Modified-Since" header. * * @return The condition date. */ public Date getModifiedSince() { return this.modifiedSince; } /** * Returns the modifiable list of tags that mustn't match. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-None-Match" header. * * @return The list of tags that mustn't match. */ public List getNoneMatch() { // Lazy initialization with double-check. List n = this.noneMatch; if (n == null) { synchronized (this) { n = this.noneMatch; if (n == null) { this.noneMatch = n = new ArrayList(); } } } return n; } /** * Returns the range condition based on the modification date of the * requested variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Range" header. * * @return The range condition date. */ public Date getRangeDate() { return rangeDate; } /** * Returns the range conditional status of an entity. * * @param representationInfo * The representation information that will be tested. * @return the status of the response. */ public Status getRangeStatus(RepresentationInfo representationInfo) { return getRangeStatus( (representationInfo == null) ? null : representationInfo.getTag(), (representationInfo == null) ? null : representationInfo .getModificationDate()); } /** * Returns the range conditional status of an entity. * * @param tag * The tag of the entity. * @param modificationDate * The modification date of the entity. * @return The status of the response. */ public Status getRangeStatus(Tag tag, Date modificationDate) { Status result = Status.CLIENT_ERROR_PRECONDITION_FAILED; if (getRangeTag() != null) { boolean all = getRangeTag().equals(Tag.ALL); // If a tag exists if (tag != null) { if (all || getRangeTag().equals(tag)) { result = Status.SUCCESS_OK; } } } else if (getRangeDate() != null) { // If a modification date exists if (getRangeDate().equals(modificationDate)) { result = Status.SUCCESS_OK; } } return result; } /** * Returns the range condition based on the entity tag of the requested * variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Range" header. * * @return The range entity tag. */ public Tag getRangeTag() { return rangeTag; } /** * Returns the conditional status of a variant using a given method. * * @param method * The request method. * @param entityExists * Indicates if the entity exists. * @param tag * The tag. * @param modificationDate * The modification date. * @return Null if the requested method can be performed, the status of the * response otherwise. */ public Status getStatus(Method method, boolean entityExists, Tag tag, Date modificationDate) { Status result = null; // Is the "if-Match" rule followed or not? if ((this.match != null) && !this.match.isEmpty()) { boolean matched = false; boolean failed = false; boolean all = (getMatch().size() > 0) && getMatch().get(0).equals(Tag.ALL); String statusMessage = null; if (entityExists) { // If a tag exists if (!all && (tag != null)) { // Check if it matches one of the representations already // cached by the client Tag matchTag; for (Iterator iter = getMatch().iterator(); !matched && iter.hasNext();) { matchTag = iter.next(); matched = matchTag.equals(tag, false); } } else { matched = all; } } else { // See // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 // If none of the entity tags match, or if "*" is given and no // current entity exists, the server MUST NOT perform the // requested method failed = all; statusMessage = "A non existing resource can't match any tag."; } failed = failed || !matched; if (failed) { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; if (statusMessage != null) { result = new Status(result, statusMessage); } } } // Is the "if-None-Match" rule followed or not? if ((result == null) && (this.noneMatch != null) && !this.noneMatch.isEmpty()) { boolean matched = false; if (entityExists) { // If a tag exists if (tag != null) { // Check if it matches one of the representations // already cached by the client Tag noneMatchTag; for (Iterator iter = getNoneMatch().iterator(); !matched && iter.hasNext();) { noneMatchTag = iter.next(); matched = noneMatchTag.equals(tag, (Method.GET .equals(method) || Method.HEAD.equals(method))); } // The current representation matches one of those already // cached by the client if (matched) { // Check if the current representation has been updated // since the "if-modified-since" date. In this case, the // rule is followed. Date modifiedSince = getModifiedSince(); boolean isModifiedSince = (modifiedSince != null) && (DateUtils.after(new Date(), modifiedSince) || (modificationDate == null) || DateUtils .after(modifiedSince, modificationDate)); matched = !isModifiedSince; } } else { matched = (getNoneMatch().size() > 0) && getNoneMatch().get(0).equals(Tag.ALL); } } if (matched) { if (Method.GET.equals(method) || Method.HEAD.equals(method)) { result = Status.REDIRECTION_NOT_MODIFIED; } else { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } } // Is the "if-Modified-Since" rule followed or not? if ((result == null) && (getModifiedSince() != null)) { Date modifiedSince = getModifiedSince(); boolean isModifiedSince = (DateUtils.after(new Date(), modifiedSince) || (modificationDate == null) || DateUtils .after(modifiedSince, modificationDate)); if (!isModifiedSince) { if (Method.GET.equals(method) || Method.HEAD.equals(method)) { result = Status.REDIRECTION_NOT_MODIFIED; } else { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } } // Is the "if-Unmodified-Since" rule followed or not? if ((result == null) && (getUnmodifiedSince() != null)) { Date unModifiedSince = getUnmodifiedSince(); boolean isUnModifiedSince = ((unModifiedSince == null) || (modificationDate == null) || !DateUtils.before( modificationDate, unModifiedSince)); if (!isUnModifiedSince) { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } return result; } /** * Returns the conditional status of a variant using a given method. * * @param method * The request method. * @param representationInfo * The representation information that will be tested. * @return Null if the requested method can be performed, the status of the * response otherwise. */ public Status getStatus(Method method, RepresentationInfo representationInfo) { return getStatus( method, representationInfo != null, (representationInfo == null) ? null : representationInfo .getTag(), (representationInfo == null) ? null : representationInfo.getModificationDate()); } /** * Returns the condition based on the modification date of the requested * variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Unmodified-Since" header. * * @return The condition date. */ public Date getUnmodifiedSince() { return this.unmodifiedSince; } /** * Indicates if there are some conditions set. * * @return True if there are some conditions set. */ public boolean hasSome() { return (((this.match != null) && !this.match.isEmpty()) || ((this.noneMatch != null) && !this.noneMatch.isEmpty()) || (getModifiedSince() != null) || (getUnmodifiedSince() != null)); } /** * Indicates if there are some range conditions set. * * @return True if there are some range conditions set. */ public boolean hasSomeRange() { return getRangeTag() != null || getRangeDate() != null; } /** * Sets the modifiable list of tags that must be matched.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Match" header. * * @param tags * The "if-match" condition. */ public void setMatch(List tags) { this.match = tags; } /** * Sets the condition based on the modification date of the requested * variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Modified-Since" header. * * @param date * The modification date. */ public void setModifiedSince(Date date) { this.modifiedSince = DateUtils.unmodifiable(date); } /** * Sets the modifiable list of tags that mustn't match. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-None-Match" header. * * @param tags * The list of tags that mustn't match. */ public void setNoneMatch(List tags) { this.noneMatch = tags; } /** * Sets the range condition based on the modification date of the requested * variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Range" header. * * @param rangeDate * The date of the range condition. */ public void setRangeDate(Date rangeDate) { this.rangeDate = rangeDate; } /** * Sets the range condition based on the entity tag of the requested * variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Range" header. * * @param rangeTag * The entity tag of the range condition. */ public void setRangeTag(Tag rangeTag) { this.rangeTag = rangeTag; } /** * Sets the condition based on the modification date of the requested * variant.
    *
    * Note that when used with HTTP connectors, this property maps to the * "If-Unmodified-Since" header. * * @param date * The condition date. */ public void setUnmodifiedSince(Date date) { this.unmodifiedSince = DateUtils.unmodifiable(date); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Preference.java0000664000175000017500000001070711757206350025111 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.util.Series; /** * Metadata preference definition. * * @author Jerome Louvel */ public final class Preference { /** The metadata associated with this preference. */ private volatile T metadata; /** The modifiable list of parameters. */ private volatile Series parameters; /** The quality/preference level. */ private volatile float quality; /** * Constructor. */ public Preference() { this(null, 1F, null); } /** * Constructor. * * @param metadata * The associated metadata. */ public Preference(T metadata) { this(metadata, 1F, null); } /** * Constructor. * * @param metadata * The associated metadata. * @param quality * The quality/preference level. */ public Preference(T metadata, float quality) { this(metadata, quality, null); } /** * Constructor. * * @param metadata * The associated metadata. * @param quality * The quality/preference level. * @param parameters * The list of parameters. */ public Preference(T metadata, float quality, Series parameters) { this.metadata = metadata; this.quality = quality; this.parameters = parameters; } /** * Returns the metadata associated with this preference. * * @return The metadata associated with this preference. */ public T getMetadata() { return this.metadata; } /** * Returns the modifiable list of parameters. Creates a new instance if no * one has been set. * * @return The modifiable list of parameters. */ public Series getParameters() { // Lazy initialization with double-check. Series p = this.parameters; if (p == null) { synchronized (this) { p = this.parameters; if (p == null) { this.parameters = p = new Form(); } } } return p; } /** * Returns the quality/preference level. * * @return The quality/preference level. */ public float getQuality() { return this.quality; } /** * Sets the metadata associated with this preference. * * @param metadata * The metadata associated with this preference. */ public void setMetadata(T metadata) { this.metadata = metadata; } /** * Sets the modifiable list of parameters. * * @param parameters * The modifiable list of parameters. */ public void setParameters(Series parameters) { this.parameters = parameters; } /** * Sets the quality/preference level. * * @param quality * The quality/preference level. */ public void setQuality(float quality) { this.quality = quality; } @Override public String toString() { return (getMetadata() == null) ? "" : (getMetadata().getName() + ":" + getQuality()); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Method.java0000664000175000017500000004125311757206350024253 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.restlet.engine.Engine; /** * Method to execute when handling a call. * * @author Jerome Louvel */ public final class Method implements Comparable { /** Map of registered methods. */ private static final Map _methods = new ConcurrentHashMap(); /** * Pseudo-method use to match all methods. */ public static final Method ALL = new Method("*", "Pseudo-method use to match all methods."); private static final String BASE_HTTP = "http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html"; private static final String BASE_WEBDAV = "http://www.webdav.org/specs/rfc2518.html"; /** * Used with a proxy that can dynamically switch to being a tunnel. * * @see HTTP * RFC - 9.9 CONNECT */ public static final Method CONNECT = new Method("CONNECT", "Used with a proxy that can dynamically switch to being a tunnel", BASE_HTTP + "#sec9.9", false, false); /** * Creates a duplicate of the source resource, identified by the * Request-URI, in the destination resource, identified by the URI in the * Destination header. * * @see WEBDAV * RFC - 8.8 COPY Method */ public static final Method COPY = new Method( "COPY", "Creates a duplicate of the source resource, identified by the Request-URI, in the destination resource, identified by the URI in the Destination header", BASE_WEBDAV + "#METHOD_COPY", false, true); /** * Requests that the origin server deletes the resource identified by the * request URI. * * @see HTTP * RFC - 9.7 DELETE */ public static final Method DELETE = new Method( "DELETE", "Requests that the origin server deletes the resource identified by the request URI", BASE_HTTP + "#sec9.7", false, true); /** * Retrieves whatever information (in the form of an entity) that is * identified by the request URI. * * @see HTTP * RFC - 9.3 GET */ public static final Method GET = new Method( "GET", "Retrieves whatever information (in the form of an entity) that is identified by the request URI", BASE_HTTP + "#sec9.3", true, true); /** * Identical to GET except that the server must not return a message body in * the response but only the message header. * * @see HTTP * RFC - 9.4 HEAD */ public static final Method HEAD = new Method( "HEAD", "Identical to GET except that the server must not return a message body in the response", BASE_HTTP + "#sec9.4", true, true); /** * Used to take out a lock of any access type on the resource identified by * the request URI. * * @see WEBDAV * RFC - 8.10 LOCK Method */ public static final Method LOCK = new Method("LOCK", "Used to take out a lock of any access type (WebDAV)", BASE_WEBDAV + "#METHOD_LOCK", true, false); /** * MKCOL creates a new collection resource at the location specified by the * Request URI. * * @see WEBDAV * RFC - 8.3 MKCOL Method */ public static final Method MKCOL = new Method("MKCOL", "Used to create a new collection (WebDAV)", BASE_WEBDAV + "#METHOD_MKCOL", false, true); /** * Logical equivalent of a copy, followed by consistency maintenance * processing, followed by a delete of the source where all three actions * are performed atomically. * * @see WEBDAV * RFC - 8.3 MKCOL Method */ public static final Method MOVE = new Method( "MOVE", "Logical equivalent of a copy, followed by consistency maintenance processing, followed by a delete of the source (WebDAV)", BASE_WEBDAV + "#METHOD_MOVE", false, false); /** * Requests for information about the communication options available on the * request/response chain identified by the URI. * * @see HTTP * RFC - 9.2 OPTIONS */ public static final Method OPTIONS = new Method( "OPTIONS", "Requests for information about the communication options available on the request/response chain identified by the URI", BASE_HTTP + "#sec9.2", true, true); /** * Requests that the origin server accepts the entity enclosed in the * request as a new subordinate of the resource identified by the request * URI. * * @see HTTP * RFC - 9.5 POST */ public static final Method POST = new Method( "POST", "Requests that the origin server accepts the entity enclosed in the request as a new subordinate of the resource identified by the request URI", BASE_HTTP + "#sec9.5", false, false); /** * Retrieves properties defined on the resource identified by the request * URI. * * @see WEBDAV * RFC - 8.1 PROPFIND */ public static final Method PROPFIND = new Method( "PROPFIND", "Retrieves properties defined on the resource identified by the request URI", BASE_WEBDAV + "#METHOD_PROPFIND", true, true); /** * Processes instructions specified in the request body to set and/or remove * properties defined on the resource identified by the request URI. * * @see WEBDAV * RFC - 8.2 PROPPATCH */ public static final Method PROPPATCH = new Method( "PROPPATCH", "Processes instructions specified in the request body to set and/or remove properties defined on the resource identified by the request URI", BASE_WEBDAV + "#METHOD_PROPPATCH", false, true); /** * Requests that the enclosed entity be stored under the supplied request * URI. * * @see */ public static final Method PUT = new Method( "PUT", "Requests that the enclosed entity be stored under the supplied request URI", BASE_HTTP + "#sec9.6", false, true); /** * Used to invoke a remote, application-layer loop-back of the request * message. * * @see HTTP * RFC - 9.8 TRACE */ public static final Method TRACE = new Method( "TRACE", "Used to invoke a remote, application-layer loop-back of the request message", BASE_HTTP + "#sec9.8", true, true); /** * Removes the lock identified by the lock token from the request URI, and * all other resources included in the lock. * * @see WEBDAV * RFC - 8.11 UNLOCK Method */ public static final Method UNLOCK = new Method( "UNLOCK", "Removes the lock identified by the lock token from the request URI, and all other resources included in the lock", BASE_WEBDAV + "#METHOD_UNLOCK", true, false); /** * Adds a new Method to the list of registered methods. * * @param method * The method to register. */ public static void register(Method method) { String name = (method == null) ? null : method.getName().toLowerCase(); if ((name != null) && !name.equals("")) { _methods.put(name, method); } } /** * Sorts the given list of methods by name. * * @param methods * The methods to sort. */ public static void sort(List methods) { Collections.sort(methods, new Comparator() { public int compare(Method m1, Method m2) { return m1.getName().compareTo(m2.getName()); } }); } /** * Returns the method associated to a given method name. If an existing * constant exists then it is returned, otherwise a new instance is created. * * @param name * The method name. * @return The associated method. */ public static Method valueOf(final String name) { Method result = null; if ((name != null) && !name.equals("")) { result = Method._methods.get(name.toLowerCase()); if (result == null) { result = new Method(name); } } return result; } /** The description. */ private final String description; /** * Indicates if the side-effects of several requests is the same as a single * request. */ private volatile boolean idempotent; /** The name. */ private volatile String name; /** Indicates if the method replies with a response. */ private final boolean replying; /** * Indicates if it should have the significance of taking an action other * than retrieval. */ private final boolean safe; /** The URI of the specification describing the method. */ private volatile String uri; { // Let the engine register all methods (the default ones and the ones to // be discovered) as soon as the Method class is loaded or at least // used. Engine.getInstance(); } /** * Constructor for unsafe and non idempotent methods. * * @param name * The technical name of the method. * @see org.restlet.data.Method#valueOf(String) */ public Method(final String name) { this(name, null); } /** * Constructor for unsafe and non idempotent methods. * * @param name * The technical name of the method. * @param description * The description. * @see org.restlet.data.Method#valueOf(String) */ public Method(String name, String description) { this(name, description, null, false, false); } /** * Constructor for unsafe and non idempotent methods. * * @param name * The technical name. * @param description * The description. * @param uri * The URI of the specification describing the method. * @see org.restlet.data.Method#valueOf(String) */ public Method(String name, String description, String uri) { this(name, description, uri, false, false); } /** * Constructor for methods that reply to requests with responses. * * @param name * The technical name. * @param description * The description. * @param uri * The URI of the specification describing the method. * @param safe * Indicates if the method is safe. * @param idempotent * Indicates if the method is idempotent. * @see org.restlet.data.Method#valueOf(String) */ public Method(String name, String description, String uri, boolean safe, boolean idempotent) { this(name, description, uri, safe, idempotent, true); } /** * Constructor. * * @param name * The technical name. * @param description * The description. * @param uri * The URI of the specification describing the method. * @param safe * Indicates if the method is safe. * @param idempotent * Indicates if the method is idempotent. * @param replying * Indicates if the method replies with a response. * @see org.restlet.data.Method#valueOf(String) */ public Method(String name, String description, String uri, boolean safe, boolean idempotent, boolean replying) { this.name = name; this.description = description; this.uri = uri; this.safe = safe; this.idempotent = idempotent; this.replying = replying; } /** * Compares this method to another. Based on the method name. * * @param o * The other method. */ public int compareTo(Method o) { if (o != null) { return this.getName().compareTo(o.getName()); } return 1; } /** {@inheritDoc} */ @Override public boolean equals(final Object object) { return (object instanceof Method) && ((Method) object).getName().equals(getName()); } /** * Returns the description. * * @return The description. */ public String getDescription() { return this.description; } /** * Returns the name. * * @return The name. */ public String getName() { return name; } /** * Returns the URI of the specification describing the method. * * @return The URI of the specification describing the method. */ public String getUri() { return this.uri; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().hashCode(); } /** * Indicates if the side-effects of several requests is the same as a single * request. * * @return True if the method is idempotent. */ public boolean isIdempotent() { return idempotent; } /** * Indicates if the method replies with a response. * * @return True if the method replies with a response. */ public boolean isReplying() { return replying; } /** * Indicates if it should have the significance of taking an action other * than retrieval. * * @return True if the method is safe. */ public boolean isSafe() { return safe; } /** * Sets the URI of the specification describing the method. * * @param uri * The URI of the specification describing the method. * * @deprecated Method instances are shared by all Restlet applications and * shouldn't be modifiable. */ @Deprecated public void setUri(String uri) { this.uri = uri; } /** * Returns the name. * * @return The name. */ @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Product.java0000664000175000017500000000641711757206346024463 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Product tokens are used to allow communicating applications to identify * themselves by software name and version. * * @author Thierry Boileau * @see User-Agent * @see Product Tokens */ public class Product { /** Comment. */ private volatile String comment; /** Product name. */ private volatile String name; /** Version number. */ private volatile String version; /** * Constructor. * * @param name * The product name. * @param version * The product version. * @param comment * The product comment. */ public Product(String name, String version, String comment) { super(); this.name = name; this.version = version; this.comment = comment; } /** * Returns the facultative comment. * * @return The facultative comment. */ public String getComment() { return this.comment; } /** * Returns the product name. * * @return The product name. */ public String getName() { return this.name; } /** * Returns the version of the product. * * @return The version of the product. */ public String getVersion() { return this.version; } /** * Sets the facultative comment. * * @param comment * The facultative comment. */ public void setComment(String comment) { this.comment = comment; } /** * Sets the product name. * * @param name * The product name. */ public void setName(String name) { this.name = name; } /** * Sets the version of the product. * * @param version * The version of the product. */ public void setVersion(String version) { this.version = version; } } restlet-2.0.14/org.restlet/src/org/restlet/data/Metadata.java0000664000175000017500000001152411757206346024556 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Representations metadata for content negotiation. Metadata is in the form of * name-value pairs, where the name corresponds to a standard that defines the * value's structure and semantics. Response messages may include both * representation metadata and resource metadata: information about the resource * that is not specific to the supplied representation." Roy T. Fielding * * @see Preference * @see Source dissertation * @author Jerome Louvel */ public abstract class Metadata { /** The metadata name like "text/html" or "compress" or "iso-8851-1". */ private final String name; /** The description of this metadata. */ private final String description; /** * Returns the parent metadata if available or null. * * @return The parent metadata. */ public abstract Metadata getParent(); /** * Indicates if a given metadata is included in the current one. The test is * true if both metadata are equal or if the given metadata is within the * range of the current one. For example, {@link MediaType#ALL} includes all * media types. *

    * Examples: *

      *
    • TEXT_ALL.includes(TEXT_PLAIN) -> true
    • *
    • TEXT_PLAIN.includes(TEXT_ALL) -> false
    • *
    * * @param included * The metadata to test for inclusion. * @return True if the given metadata is included in the current one. * @see #isCompatible(Metadata) */ public abstract boolean includes(Metadata included); /** * Checks if this metadata is compatible with the given metadata. *

    * Examples: *

      *
    • TEXT_ALL.isCompatible(TEXT_PLAIN) -> true
    • *
    • TEXT_PLAIN.isCompatible(TEXT_ALL) -> true
    • *
    • TEXT_PLAIN.isCompatible(APPLICATION_ALL) -> false
    • *
    * * @param otherMetadata * The other metadata to compare. * @return True if the metadata are compatible. * @see #includes(Metadata) */ public boolean isCompatible(Metadata otherMetadata) { return (otherMetadata != null) && (includes(otherMetadata) || otherMetadata.includes(this)); } /** * Constructor. * * @param name * The unique name. */ public Metadata(String name) { this(name, null); } /** * Constructor. * * @param name * The unique name. * @param description * The description. */ public Metadata(String name, String description) { this.name = name; this.description = description; } /** {@inheritDoc} */ @Override public boolean equals(Object object) { return (object instanceof Metadata) && ((Metadata) object).getName().equals(getName()); } /** * Returns the description. * * @return The description. */ public String getDescription() { return this.description; } /** * Returns the name (ex: "text/html" or "compress" or "iso-8851-1"). * * @return The name (ex: "text/html" or "compress" or "iso-8851-1"). */ public String getName() { return this.name; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().hashCode(); } /** * Returns the metadata name. * * @return The metadata name. */ @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/data/MediaType.java0000664000175000017500000011061311757206350024711 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.HashMap; import java.util.Map; import org.restlet.engine.http.header.HeaderWriter; import org.restlet.engine.util.SystemUtils; import org.restlet.util.Series; /** * Media type used in representations and preferences. The {@link #getName()} * method returns a full String representation of the media type including the * parameters. * * @see MIME types on Wikipedia * @author Jerome Louvel */ public final class MediaType extends Metadata { /** * Illegal ASCII characters as defined in RFC 1521.
    * Keep the underscore for the ordering * * @see http://www.ietf.org/rfc/rfc1521.txt * */ private static final String _TSPECIALS = "()<>@,;:/[]?=\\\""; /** * The known media types registered with {@link #register(String, String)}, * retrievable using {@link #valueOf(String)}.
    * Keep the underscore for the ordering. */ private static volatile Map _types = null; public static final MediaType ALL = register("*/*", "All media"); public static final MediaType APPLICATION_ALL = register("application/*", "All application documents"); public static final MediaType APPLICATION_ALL_XML = register( "application/*+xml", "All application/*+xml documents"); public static final MediaType APPLICATION_ATOM = register( "application/atom+xml", "Atom document"); /** * @deprecated Use {@link #APPLICATION_ATOMPUB_SERVICE} instead. */ @Deprecated public static final MediaType APPLICATION_ATOM_SERVICE_XML = register( "application/atomsvc+xml", "Atom service document"); /** * @deprecated Use {@link #APPLICATION_ATOMPUB_SERVICE} instead. */ @Deprecated public static final MediaType APPLICATION_ATOM_XML = register( "application/atom+xml", "Atom document"); public static final MediaType APPLICATION_ATOMPUB_CATEGORY = register( "application/atomcat+xml", "Atom category document"); public static final MediaType APPLICATION_ATOMPUB_SERVICE = register( "application/atomsvc+xml", "Atom service document"); public static final MediaType APPLICATION_CAB = register( "application/vnd.ms-cab-compressed", "Microsoft Cabinet archive"); public static final MediaType APPLICATION_COMPRESS = register( "application/x-compress", "Compressed file"); public static final MediaType APPLICATION_EXCEL = register( "application/vnd.ms-excel", "Microsoft Excel document"); public static final MediaType APPLICATION_FLASH = register( "application/x-shockwave-flash", "Shockwave Flash object"); public static final MediaType APPLICATION_GNU_TAR = register( "application/x-gtar", "GNU Tar archive"); public static final MediaType APPLICATION_GNU_ZIP = register( "application/x-gzip", "GNU Zip archive"); public static final MediaType APPLICATION_HTTP_COOKIES = register( "application/x-http-cookies", "HTTP cookies"); public static final MediaType APPLICATION_JAVA = register( "application/java", "Java class"); public static final MediaType APPLICATION_JAVA_ARCHIVE = register( "application/java-archive", "Java archive"); public static final MediaType APPLICATION_JAVA_OBJECT = register( "application/x-java-serialized-object", "Java serialized object"); public static final MediaType APPLICATION_JAVA_OBJECT_GWT = register( "application/x-java-serialized-object+gwt", "Java serialized object (using GWT-RPC encoder)"); public static final MediaType APPLICATION_JAVA_OBJECT_XML = register( "application/x-java-serialized-object+xml", "Java serialized object (using JavaBeans XML encoder)"); public static final MediaType APPLICATION_JAVASCRIPT = register( "application/x-javascript", "Javascript document"); public static final MediaType APPLICATION_JNLP = register( "application/x-java-jnlp-file", "JNLP"); public static final MediaType APPLICATION_JSON = register( "application/json", "JavaScript Object Notation document"); public static final MediaType APPLICATION_KML = register( "application/vnd.google-earth.kml+xml", "Google Earth/Maps KML document"); public static final MediaType APPLICATION_KMZ = register( "application/vnd.google-earth.kmz", "Google Earth/Maps KMZ document"); public static final MediaType APPLICATION_LATEX = register( "application/x-latex", "LaTeX"); public static final MediaType APPLICATION_MAC_BINHEX40 = register( "application/mac-binhex40", "Mac binhex40"); public static final MediaType APPLICATION_MATHML = register( "application/mathml+xml", "MathML XML document"); /** * @deprecated Use {@link #APPLICATION_MATHML} instead. */ @Deprecated public static final MediaType APPLICATION_MATHML_XML = register( "application/mathml+xml", "MathML XML document"); public static final MediaType APPLICATION_MSOFFICE_DOCM = register( "application/vnd.ms-word.document.macroEnabled.12", "Office Word 2007 macro-enabled document"); public static final MediaType APPLICATION_MSOFFICE_DOCX = register( "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Microsoft Office Word 2007 document"); public static final MediaType APPLICATION_MSOFFICE_DOTM = register( "application/vnd.ms-word.template.macroEnabled.12", "Office Word 2007 macro-enabled document template"); public static final MediaType APPLICATION_MSOFFICE_DOTX = register( "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "Office Word 2007 template"); public static final MediaType APPLICATION_MSOFFICE_ONETOC = register( "application/onenote", "Microsoft Office OneNote 2007 TOC"); public static final MediaType APPLICATION_MSOFFICE_ONETOC2 = register( "application/onenote", "Office OneNote 2007 TOC"); public static final MediaType APPLICATION_MSOFFICE_POTM = register( "application/vnd.ms-powerpoint.template.macroEnabled.12", "Office PowerPoint 2007 macro-enabled presentation template"); public static final MediaType APPLICATION_MSOFFICE_POTX = register( "application/vnd.openxmlformats-officedocument.presentationml.template", "Office PowerPoint 2007 template"); public static final MediaType APPLICATION_MSOFFICE_PPAM = register( "application/vnd.ms-powerpoint.addin.macroEnabled.12", "Office PowerPoint 2007 add-in"); public static final MediaType APPLICATION_MSOFFICE_PPSM = register( "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", "Office PowerPoint 2007 macro-enabled slide show"); public static final MediaType APPLICATION_MSOFFICE_PPSX = register( "application/vnd.openxmlformats-officedocument.presentationml.slideshow", "Office PowerPoint 2007 slide show"); public static final MediaType APPLICATION_MSOFFICE_PPTM = register( "application/vnd.ms-powerpoint.presentation.macroEnabled.12", "Office PowerPoint 2007 macro-enabled presentation"); public static final MediaType APPLICATION_MSOFFICE_PPTX = register( "application/vnd.openxmlformats-officedocument.presentationml.presentation", "Microsoft Office PowerPoint 2007 presentation"); public static final MediaType APPLICATION_MSOFFICE_SLDM = register( "application/vnd.ms-powerpoint.slide.macroEnabled.12", "Office PowerPoint 2007 macro-enabled slide"); public static final MediaType APPLICATION_MSOFFICE_SLDX = register( "application/vnd.openxmlformats-officedocument.presentationml.slide", "Office PowerPoint 2007 slide"); public static final MediaType APPLICATION_MSOFFICE_XLAM = register( "application/vnd.ms-excel.addin.macroEnabled.12", "Office Excel 2007 add-in"); public static final MediaType APPLICATION_MSOFFICE_XLSB = register( "application/vnd.ms-excel.sheet.binary.macroEnabled.12", "Office Excel 2007 binary workbook"); public static final MediaType APPLICATION_MSOFFICE_XLSM = register( "application/vnd.ms-excel.sheet.macroEnabled.12", "Office Excel 2007 macro-enabled workbook"); public static final MediaType APPLICATION_MSOFFICE_XLSX = register( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Microsoft Office Excel 2007 workbook"); public static final MediaType APPLICATION_MSOFFICE_XLTM = register( "application/vnd.ms-excel.template.macroEnabled.12", "Office Excel 2007 macro-enabled workbook template"); public static final MediaType APPLICATION_MSOFFICE_XLTX = register( "application/vnd.openxmlformats-officedocument.spreadsheetml.template", "Office Excel 2007 template"); public static final MediaType APPLICATION_OCTET_STREAM = register( "application/octet-stream", "Raw octet stream"); public static final MediaType APPLICATION_OPENOFFICE_ODB = register( "application/vnd.oasis.opendocument.database", "OpenDocument Database"); public static final MediaType APPLICATION_OPENOFFICE_ODC = register( "application/vnd.oasis.opendocument.chart", "OpenDocument Chart"); public static final MediaType APPLICATION_OPENOFFICE_ODF = register( "application/vnd.oasis.opendocument.formula", "OpenDocument Formula"); public static final MediaType APPLICATION_OPENOFFICE_ODG = register( "application/vnd.oasis.opendocument.graphics", "OpenDocument Drawing"); public static final MediaType APPLICATION_OPENOFFICE_ODI = register( "application/vnd.oasis.opendocument.image", "OpenDocument Image "); public static final MediaType APPLICATION_OPENOFFICE_ODM = register( "application/vnd.oasis.opendocument.text-master", "OpenDocument Master Document"); public static final MediaType APPLICATION_OPENOFFICE_ODP = register( "application/vnd.oasis.opendocument.presentation", "OpenDocument Presentation "); public static final MediaType APPLICATION_OPENOFFICE_ODS = register( "application/vnd.oasis.opendocument.spreadsheet", "OpenDocument Spreadsheet"); public static final MediaType APPLICATION_OPENOFFICE_ODT = register( "application/vnd.oasis.opendocument.text ", "OpenDocument Text"); public static final MediaType APPLICATION_OPENOFFICE_OTG = register( "application/vnd.oasis.opendocument.graphics-template", "OpenDocument Drawing Template"); public static final MediaType APPLICATION_OPENOFFICE_OTH = register( "application/vnd.oasis.opendocument.text-web", "HTML Document Template"); public static final MediaType APPLICATION_OPENOFFICE_OTP = register( "application/vnd.oasis.opendocument.presentation-template", "OpenDocument Presentation Template"); public static final MediaType APPLICATION_OPENOFFICE_OTS = register( "application/vnd.oasis.opendocument.spreadsheet-template", "OpenDocument Spreadsheet Template"); public static final MediaType APPLICATION_OPENOFFICE_OTT = register( "application/vnd.oasis.opendocument.text-template", "OpenDocument Text Template"); public static final MediaType APPLICATION_OPENOFFICE_OXT = register( "application/vnd.openofficeorg.extension", "OpenOffice.org extension"); public static final MediaType APPLICATION_PDF = register("application/pdf", "Adobe PDF document"); public static final MediaType APPLICATION_POSTSCRIPT = register( "application/postscript", "Postscript document"); public static final MediaType APPLICATION_POWERPOINT = register( "application/vnd.ms-powerpoint", "Microsoft Powerpoint document"); public static final MediaType APPLICATION_PROJECT = register( "application/vnd.ms-project", "Microsoft Project document"); public static final MediaType APPLICATION_RDF_TRIG = register( "application/x-trig", "Plain text serialized Resource Description Framework document"); public static final MediaType APPLICATION_RDF_TRIX = register( "application/trix", "Simple XML serialized Resource Description Framework document"); 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"); public static final MediaType APPLICATION_RELAXNG_COMPACT = register( "application/relax-ng-compact-syntax", "Relax NG Schema document, Compact syntax"); public static final MediaType APPLICATION_RELAXNG_XML = register( "application/x-relax-ng+xml", "Relax NG Schema document, XML syntax"); public static final MediaType APPLICATION_RSS = register( "application/rss+xml", "Really Simple Syndication document"); /** * @deprecated Use {@link #APPLICATION_RSS} instead. */ @Deprecated public static final MediaType APPLICATION_RSS_XML = register( "application/rss+xml", "Really Simple Syndication document"); public static final MediaType APPLICATION_RTF = register("application/rtf", "Rich Text Format document"); public static final MediaType APPLICATION_SPARQL_RESULTS_JSON = register( "application/sparql-results+json", "SPARQL Query Results JSON document"); public static final MediaType APPLICATION_SPARQL_RESULTS_XML = register( "application/sparql-results+xml", "SPARQL Query Results XML document"); public static final MediaType APPLICATION_SPSS_SAV = register( "application/x-spss-sav", "SPSS Data"); public static final MediaType APPLICATION_SPSS_SPS = register( "application/x-spss-sps", "SPSS Script Syntax"); public static final MediaType APPLICATION_STATA_STA = register( "application/x-stata", "Stata data file"); public static final MediaType APPLICATION_STUFFIT = register( "application/x-stuffit", "Stuffit archive"); public static final MediaType APPLICATION_TAR = register( "application/x-tar", "Tar archive"); public static final MediaType APPLICATION_TEX = register( "application/x-tex", "Tex file"); public static final MediaType APPLICATION_TROFF_MAN = register( "application/x-troff-man", "LaTeX"); public static final MediaType APPLICATION_VOICEXML = register( "application/voicexml+xml", "VoiceXML"); public static final MediaType APPLICATION_W3C_SCHEMA = register( "application/x-xsd+xml", "W3C XML Schema document"); /** * @deprecated Use {@link #APPLICATION_W3C_SCHEMA} instead. */ @Deprecated public static final MediaType APPLICATION_W3C_SCHEMA_XML = register( "application/x-xsd+xml", "W3C XML Schema document"); public static final MediaType APPLICATION_W3C_XSLT = register( "application/xslt+xml", "W3C XSLT Stylesheet"); public static final MediaType APPLICATION_WADL = register( "application/vnd.sun.wadl+xml", "Web Application Description Language document"); /** * @deprecated Use {@link #APPLICATION_WADL} instead. */ @Deprecated public static final MediaType APPLICATION_WADL_XML = register( "application/vnd.sun.wadl+xml", "Web Application Description Language document"); public static final MediaType APPLICATION_WORD = register( "application/msword", "Microsoft Word document"); public static final MediaType APPLICATION_WWW_FORM = register( "application/x-www-form-urlencoded", "Web form (URL encoded)"); public static final MediaType APPLICATION_XHTML = register( "application/xhtml+xml", "XHTML document"); /** * @deprecated Use {@link #APPLICATION_XHTML} instead. */ @Deprecated public static final MediaType APPLICATION_XHTML_XML = register( "application/xhtml+xml", "XHTML document"); public static final MediaType APPLICATION_XMI_XML = register( "application/xmi+xml", "XMI document"); public static final MediaType APPLICATION_XML = register("application/xml", "XML document"); public static final MediaType APPLICATION_XML_DTD = register( "application/xml-dtd", "XML DTD"); public static final MediaType APPLICATION_XUL = register( "application/vnd.mozilla.xul+xml", "XUL document"); public static final MediaType APPLICATION_ZIP = register("application/zip", "Zip archive"); public static final MediaType AUDIO_ALL = register("audio/*", "All audios"); public static final MediaType AUDIO_BASIC = register("audio/basic", "AU audio"); public static final MediaType AUDIO_MIDI = register("audio/midi", "MIDI audio"); public static final MediaType AUDIO_MPEG = register("audio/mpeg", "MPEG audio (MP3)"); public static final MediaType AUDIO_REAL = register("audio/x-pn-realaudio", "Real audio"); public static final MediaType AUDIO_WAV = register("audio/x-wav", "Waveform audio"); public static final MediaType IMAGE_ALL = register("image/*", "All images"); public static final MediaType IMAGE_BMP = register("image/bmp", "Windows bitmap"); public static final MediaType IMAGE_GIF = register("image/gif", "GIF image"); public static final MediaType IMAGE_ICON = register("image/x-icon", "Windows icon (Favicon)"); public static final MediaType IMAGE_JPEG = register("image/jpeg", "JPEG image"); public static final MediaType IMAGE_PNG = register("image/png", "PNG image"); public static final MediaType IMAGE_SVG = register("image/svg+xml", "Scalable Vector Graphics"); public static final MediaType IMAGE_TIFF = register("image/tiff", "TIFF image"); public static final MediaType MESSAGE_ALL = register("message/*", "All messages"); public static final MediaType MODEL_ALL = register("model/*", "All models"); public static final MediaType MODEL_VRML = register("model/vrml", "VRML"); public static final MediaType MULTIPART_ALL = register("multipart/*", "All multipart data"); public static final MediaType MULTIPART_FORM_DATA = register( "multipart/form-data", "Multipart form data"); public static final MediaType TEXT_ALL = register("text/*", "All texts"); public static final MediaType TEXT_CALENDAR = register("text/calendar", "iCalendar event"); public static final MediaType TEXT_CSS = register("text/css", "CSS stylesheet"); public static final MediaType TEXT_CSV = register("text/csv", "Comma-separated Values"); public static final MediaType TEXT_DAT = register("text/x-fixed-field", "Fixed-width Values"); public static final MediaType TEXT_HTML = register("text/html", "HTML document"); public static final MediaType TEXT_J2ME_APP_DESCRIPTOR = register( "text/vnd.sun.j2me.app-descriptor", "J2ME Application Descriptor"); public static final MediaType TEXT_JAVASCRIPT = register("text/javascript", "Javascript document"); public static final MediaType TEXT_PLAIN = register("text/plain", "Plain text"); public static final MediaType TEXT_RDF_N3 = register("text/n3", "N3 serialized Resource Description Framework document"); public static final MediaType TEXT_RDF_NTRIPLES = register( "text/n-triples", "N-Triples serialized Resource Description Framework document"); public static final MediaType TEXT_TSV = register( "text/tab-separated-values", "Tab-separated Values"); public static final MediaType TEXT_URI_LIST = register("text/uri-list", "List of URIs"); public static final MediaType TEXT_VCARD = register("text/x-vcard", "vCard"); public static final MediaType TEXT_XML = register("text/xml", "XML text"); public static final MediaType VIDEO_ALL = register("video/*", "All videos"); public static final MediaType VIDEO_AVI = register("video/x-msvideo", "AVI video"); public static final MediaType VIDEO_MP4 = register("video/mp4", "MPEG-4 video"); public static final MediaType VIDEO_MPEG = register("video/mpeg", "MPEG video"); public static final MediaType VIDEO_QUICKTIME = register("video/quicktime", "Quicktime video"); public static final MediaType VIDEO_WMV = register("video/x-ms-wmv", "Windows movie"); /** * Returns the first of the most specific media type of the given array of * {@link MediaType}s. *

    * Examples: *

      *
    • "text/plain" is more specific than "text/*" or "image/*"
    • *
    • "text/html" is same specific as "application/pdf" or "image/jpg"
    • *
    • "text/*" is same specific than "application/*" or "image/*"
    • *
    • "*/*" is the most unspecific MediaType
    • *
    * * @param mediaTypes * An array of media types. * @return The most concrete MediaType. * @throws IllegalArgumentException * If the array is null or empty. */ public static MediaType getMostSpecific(MediaType... mediaTypes) throws IllegalArgumentException { if ((mediaTypes == null) || (mediaTypes.length == 0)) { throw new IllegalArgumentException( "You must give at least one MediaType"); } if (mediaTypes.length == 1) { return mediaTypes[0]; } MediaType mostSpecific = mediaTypes[0]; for (int i = 1; i < mediaTypes.length; i++) { MediaType mediaType = mediaTypes[i]; if (mediaType != null) { if (mediaType.getMainType().equals("*")) { continue; } if (mostSpecific.getMainType().equals("*")) { mostSpecific = mediaType; continue; } if (mostSpecific.getSubType().contains("*")) { mostSpecific = mediaType; continue; } } } return mostSpecific; } /** * Returns the known media types map. * * @return the known media types map. */ private static Map getTypes() { if (_types == null) { _types = new HashMap(); } return _types; } /** * Normalizes the specified token. * * @param token * Token to normalize. * @return The normalized token. * @throws IllegalArgumentException * if token is not legal. */ private static String normalizeToken(String token) { int length; char c; // Makes sure we're not dealing with a "*" token. token = token.trim(); if ("".equals(token) || "*".equals(token)) return "*"; // Makes sure the token is RFC compliant. length = token.length(); for (int i = 0; i < length; i++) { c = token.charAt(i); if (c <= 32 || c >= 127 || _TSPECIALS.indexOf(c) != -1) throw new IllegalArgumentException("Illegal token: " + token); } return token; } /** * Normalizes the specified media type. * * @param name * The name of the type to normalize. * @param parameters * The parameters of the type to normalize. * @return The normalized type. */ private static String normalizeType(String name, Series parameters) { int slashIndex; int colonIndex; String mainType; String subType; StringBuilder params = null; // Ignore null names (backward compatibility). if (name == null) return null; // Check presence of parameters if ((colonIndex = name.indexOf(';')) != -1) { params = new StringBuilder(name.substring(colonIndex)); name = name.substring(0, colonIndex); } // No main / sub separator, assumes name/*. if ((slashIndex = name.indexOf('/')) == -1) { mainType = normalizeToken(name); subType = "*"; } else { // Normalizes the main and sub types. mainType = normalizeToken(name.substring(0, slashIndex)); subType = normalizeToken(name.substring(slashIndex + 1)); } // Merge parameters taken from the name and the method argument. if (parameters != null && !parameters.isEmpty()) { if (params == null) { params = new StringBuilder(); } HeaderWriter hw = new HeaderWriter() { @Override public HeaderWriter append(Parameter value) { return appendExtension(value); } }; for (int i = 0; i < parameters.size(); i++) { Parameter p = parameters.get(i); hw.appendParameterSeparator(); hw.appendSpace(); hw.append(p); } params.append(hw.toString()); } return (params == null) ? mainType + '/' + subType : mainType + '/' + subType + params.toString(); } /** * Register a media type as a known type that can later be retrieved using * {@link #valueOf(String)}. If the type already exists, the existing type * is returned, otherwise a new instance is created. * * @param name * The name. * @param description * The description. * @return The registered media type */ public static synchronized MediaType register(String name, String description) { if (!getTypes().containsKey(name)) { final MediaType type = new MediaType(name, description); getTypes().put(name, type); } return getTypes().get(name); } /** * Returns the media type associated to a name. If an existing constant * exists then it is returned, otherwise a new instance is created. * * @param name * The name. * @return The associated media type. */ public static MediaType valueOf(String name) { MediaType result = null; if ((name != null) && !name.equals("")) { result = getTypes().get(name); if (result == null) { result = new MediaType(name); } } return result; } /** The list of parameters. */ private volatile Series parameters; /** * Constructor. * * @param name * The name. */ public MediaType(String name) { this(name, null, "Media type or range of media types"); } /** * Constructor. * * @param name * The name. * @param parameters * The list of parameters. */ public MediaType(String name, Series parameters) { this(name, parameters, "Media type or range of media types"); } /** * Constructor. * * @param name * The name. * @param parameters * The list of parameters. * @param description * The description. */ @SuppressWarnings("unchecked") public MediaType(String name, Series parameters, String description) { super(normalizeType(name, parameters), description); if (parameters != null) { this.parameters = (Series) Series .unmodifiableSeries(parameters); } } /** * Constructor. * * @param name * The name. * @param description * The description. */ public MediaType(String name, String description) { this(name, null, description); } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { return equals(obj, false); } /** * Test the equality of two media types, with the possibility to ignore the * parameters. * * @param obj * The object to compare to. * @param ignoreParameters * Indicates if parameters should be ignored during comparison. * @return True if both media types are equal. */ public boolean equals(Object obj, boolean ignoreParameters) { boolean result = (obj == this); // if obj == this no need to go further if (!result) { // if obj isn't a mediatype or is null don't evaluate further if (obj instanceof MediaType) { final MediaType that = (MediaType) obj; if (getMainType().equals(that.getMainType()) && getSubType().equals(that.getSubType())) { result = ignoreParameters || getParameters().equals(that.getParameters()); } } } return result; } /** * Returns the main type. * * @return The main type. */ public String getMainType() { String result = null; if (getName() != null) { int index = getName().indexOf('/'); // Some clients appear to use name types without subtypes if (index == -1) { index = getName().indexOf(';'); } if (index == -1) { result = getName(); } else { result = getName().substring(0, index); } } return result; } /** * Returns the unmodifiable list of parameters. Creates a new instance if no * one has been set. * * @return The list of parameters. */ @SuppressWarnings("unchecked") public Series getParameters() { // Lazy initialization with double-check. Series p = this.parameters; if (p == null) { synchronized (this) { p = this.parameters; if (p == null) { Form params = null; if (getName() != null) { int index = getName().indexOf(';'); if (index != -1) { params = new Form(getName().substring(index + 1) .trim(), ';'); } } if (params == null) { params = new Form(); } this.parameters = p = (Series) Series .unmodifiableSeries(params); } } } return p; } /** * {@inheritDoc}
    * In case the media type has parameters, this method returns the * concatenation of the main type and the subtype. If the subtype is not * equal to "*", it returns the concatenation of the main type and "*". * Otherwise, it returns either the {@link #ALL} media type if it is already * the {@link #ALL} media type, or null. */ @Override public MediaType getParent() { MediaType result = null; if (getParameters().size() > 0) { result = MediaType.valueOf(getMainType() + "/" + getSubType()); } else { if (getSubType().equals("*")) { result = equals(ALL) ? null : ALL; } else { result = MediaType.valueOf(getMainType() + "/*"); } } return result; } /** * Returns the sub-type. * * @return The sub-type. */ public String getSubType() { String result = null; if (getName() != null) { final int slash = getName().indexOf('/'); if (slash == -1) { // No subtype found, assume that all subtypes are accepted result = "*"; } else { final int separator = getName().indexOf(';'); if (separator == -1) { result = getName().substring(slash + 1); } else { result = getName().substring(slash + 1, separator); } } } return result; } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(super.hashCode(), getParameters()); } /** * Indicates if a given media type is included in the current one. The test * is true if both types are equal or if the given media type is within the * range of the current one. For example, ALL includes all media types. * Parameters are ignored for this comparison. A null media type is * considered as included into the current one. *

    * Examples: *

      *
    • TEXT_ALL.includes(TEXT_PLAIN) -> true
    • *
    • TEXT_PLAIN.includes(TEXT_ALL) -> false
    • *
    * * @param included * The media type to test for inclusion. * @return True if the given media type is included in the current one. * @see #isCompatible(Metadata) */ public boolean includes(Metadata included) { boolean result = equals(ALL) || equals(included); if (!result && (included instanceof MediaType)) { MediaType includedMediaType = (MediaType) included; if (getMainType().equals(includedMediaType.getMainType())) { // Both media types are different if (getSubType().equals(includedMediaType.getSubType())) { result = true; } else if (getSubType().equals("*")) { result = true; } else if (getSubType().startsWith("*+") && includedMediaType.getSubType().endsWith( getSubType().substring(2))) { result = true; } } } return result; } /** * Checks if the current media type is concrete. A media type is concrete if * neither the main type nor the sub-type are equal to "*". * * @return True if this media type is concrete. */ public boolean isConcrete() { return !getName().contains("*"); } @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/data/package.html0000664000175000017500000000116111757206350024443 0ustar jamespagejamespage Information exchanged by components. "A datum is an element of information that is transferred from a component, or received by a component, via a connector." Roy T. Fielding.

    @since Restlet 1.0 @see Source dissertation @see User Guide - Mapping HTTP headers @see User Guide - Data package restlet-2.0.14/org.restlet/src/org/restlet/data/Warning.java0000664000175000017500000000673511757206350024446 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.Date; /** * Additional information about the status or transformation of a request or * response. This is typically used to warn about a possible issues with caching * operations or transformations applied to the entity body.
    *
    * Note that when used with HTTP connectors, this class maps to the "Warning" * header. * * @author Jerome Louvel */ public class Warning { /** The agent. Typically a caching agent. */ private volatile String agent; /** The warning date. */ private volatile Date date; /** The special status. */ private volatile Status status; /** The warning text. */ private volatile String text; /** * Constructor. */ public Warning() { this.agent = null; this.date = null; this.status = null; this.text = null; } /** * Returns the agent. Typically a caching agent. * * @return The agent. Typically a caching agent. */ public String getAgent() { return agent; } /** * Returns the warning date. * * @return The warning date. */ public Date getDate() { return date; } /** * Returns the special status. * * @return The special status. */ public Status getStatus() { return status; } /** * Returns the warning text. * * @return The warning text. */ public String getText() { return text; } /** * Sets the agent. Typically a caching agent. * * @param agent * The agent. Typically a caching agent. */ public void setAgent(String agent) { this.agent = agent; } /** * Sets the warning date. * * @param date * The warning date. */ public void setDate(Date date) { this.date = date; } /** * Sets the special status. * * @param status * The special status. */ public void setStatus(Status status) { this.status = status; } /** * Sets the warning text. * * @param text * The warning text. */ public void setText(String text) { this.text = text; } } restlet-2.0.14/org.restlet/src/org/restlet/data/ChallengeResponse.java0000664000175000017500000003706611757206346026450 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.Request; import org.restlet.Response; import org.restlet.engine.util.SystemUtils; import org.restlet.util.Series; /** * Authentication response sent by client to an origin server. This is typically * following a {@link ChallengeRequest} sent by the origin server to the client.
    *
    * Sometimes, it might be faster to preemptively issue a challenge response if * the client knows for sure that the target resource will require * authentication.
    *
    * Note that when used with HTTP connectors, this class maps to the * "Authorization" header. * * @author Jerome Louvel */ public final class ChallengeResponse extends ChallengeMessage { /** * Indicates if the identifier or principal has been authenticated. The * application is responsible for updating this property, relying on a * {@link org.restlet.security.Guard} or manually. */ private volatile boolean authenticated; /** The client nonce value. */ private volatile String clientNonce; /** * The {@link Request#getResourceRef()} value duplicated here in case a * proxy changed it. */ private volatile Reference digestRef; /** The user identifier, such as a login name or an access key. */ private volatile String identifier; /** The chosen quality of protection. */ private volatile String quality; /** The user secret, such as a password or a secret key. */ private volatile char[] secret; /** The server nonce count. */ private volatile int serverNounceCount; /** * Constructor. It leverages the latest server response and challenge * request in order to compute the credentials. * * @param challengeRequest * The challenge request sent by the origin server. * @param response * The latest server response. * @param identifier * The user identifier, such as a login name or an access key. * @param baseSecret * The user secret, such as a password or a secret key. */ public ChallengeResponse(final ChallengeRequest challengeRequest, final Response response, final String identifier, char[] baseSecret) { this(challengeRequest, response, identifier, baseSecret, Digest.ALGORITHM_NONE); } /** * Constructor. It leverages the latest server response and challenge * request in order to compute the credentials. * * @param challengeRequest * The challenge request sent by the origin server. * @param response * The latest server response. * @param identifier * The user identifier, such as a login name or an access key. * @param baseSecret * The user secret, such as a password or a secret key. */ public ChallengeResponse(final ChallengeRequest challengeRequest, final Response response, final String identifier, String baseSecret) { this(challengeRequest, response, identifier, baseSecret.toCharArray(), Digest.ALGORITHM_NONE); } /** * Constructor. It leverages the latest server response and challenge * request in order to compute the credentials. * * @param challengeRequest * The challenge request sent by the origin server. * @param response * The latest server response. * @param identifier * The user identifier, such as a login name or an access key. * @param baseSecret * The base secret used to compute the secret. * @param baseSecretAlgorithm * The digest algorithm of the base secret (see {@link Digest} * class). */ public ChallengeResponse(final ChallengeRequest challengeRequest, final Response response, final String identifier, char[] baseSecret, String baseSecretAlgorithm) { super(challengeRequest.getScheme()); this.identifier = identifier; this.secret = baseSecret; org.restlet.engine.security.AuthenticatorUtils.update(this, response.getRequest(), response); } /** * Constructor with no credentials. * * @param scheme * The challenge scheme. */ public ChallengeResponse(ChallengeScheme scheme) { super(scheme); this.identifier = null; this.secret = null; this.authenticated = false; this.clientNonce = null; this.digestRef = null; this.quality = null; this.serverNounceCount = 1; } /** * Constructor. * * @param scheme * The challenge scheme. * @param credentials * The raw credentials for custom challenge schemes. * @deprecated Use {@link #setRawValue(String)} instead. */ @Deprecated public ChallengeResponse(ChallengeScheme scheme, String credentials) { this(scheme); setRawValue(credentials); } /** * Constructor. * * @param scheme * The challenge scheme. * @param identifier * The user identifier, such as a login name or an access key. * @param secret * The user secret, such as a password or a secret key. */ public ChallengeResponse(final ChallengeScheme scheme, final String identifier, char[] secret) { super(scheme); this.identifier = identifier; this.secret = secret; } /** * Constructor. * * @param scheme * The challenge scheme. * @param identifier * The user identifier, such as a login name or an access key. * @param parameters * The additional scheme parameters. */ public ChallengeResponse(final ChallengeScheme scheme, final String identifier, Series parameters) { super(scheme, parameters); this.identifier = identifier; this.secret = null; } /** * Constructor. * * @param scheme * The challenge scheme. * @param identifier * The user identifier, such as a login name or an access key. * @param secret * The user secret, such as a password or a secret key. */ public ChallengeResponse(final ChallengeScheme scheme, final String identifier, String secret) { super(scheme); this.identifier = identifier; this.secret = (secret != null) ? secret.toCharArray() : null; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { boolean result = (obj == this); // if obj == this no need to go further if (!result) { // if obj isn't a challenge request or is null don't evaluate // further if (obj instanceof ChallengeResponse) { final ChallengeResponse that = (ChallengeResponse) obj; if (getCredentials() != null) { result = getCredentials().equals(that.getCredentials()); } else { result = (that.getCredentials() == null); } if (result) { if (getIdentifier() != null) { result = getIdentifier().equals(that.getIdentifier()); } else { result = (that.getIdentifier() == null); } if (result) { if (getScheme() != null) { result = getScheme().equals(that.getScheme()); } else { result = (that.getScheme() == null); } if (result) { if ((getSecret() == null) || (that.getSecret() == null)) { // check if both are null result = (getSecret() == that.getSecret()); } else { if (getSecret().length == that.getSecret().length) { boolean equals = true; for (int i = 0; (i < getSecret().length) && equals; i++) { equals = (getSecret()[i] == that .getSecret()[i]); } result = equals; } } } } } } } return result; } /** * Returns the client nonce. * * @return The client nonce. */ public String getClientNonce() { return this.clientNonce; } /** * Returns the raw credentials. * * @return The raw credentials. * @deprecated Use {@link #getRawValue()} instead. */ @Deprecated public String getCredentials() { return getRawValue(); } /** * Returns the {@link Request#getResourceRef()} value duplicated here in * case a proxy changed it. * * @return The digest URI reference. */ public Reference getDigestRef() { return digestRef; } /** * Returns the user identifier, such as a login name or an access key. * * @return The user identifier, such as a login name or an access key. */ public String getIdentifier() { return this.identifier; } /** * Gets the principal associated to the identifier property. * * @return The principal associated to the identifier property. */ public java.security.Principal getPrincipal() { return new java.security.Principal() { public String getName() { return getIdentifier(); }; }; } /** * Returns the chosen quality of protection. * * @return The chosen quality of protection. */ public String getQuality() { return quality; } /** * Returns the user secret, such as a password or a secret key. * * It is not recommended to use {@link String#String(char[])} for security * reasons. * * @return The user secret, such as a password or a secret key. */ public char[] getSecret() { return this.secret; } /** * Returns the server nonce count. * * @return The server nonce count. */ public int getServerNounceCount() { return serverNounceCount; } /** * Returns the server nonce count as an hexadecimal string of eight * characters. * * @return The server nonce count as an hexadecimal string. */ public String getServerNounceCountAsHex() { return org.restlet.engine.security.AuthenticatorUtils .formatNonceCount(getServerNounceCount()); } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(getScheme(), getIdentifier(), // Secret is simply discarded from hash code calculation because we // don't want it to be materialized as a string // (getSecret() == null) ? null : new String(getSecret()), getCredentials()); } /** * Indicates if the identifier or principal has been authenticated. The * application is responsible for updating this property, relying on a * {@link org.restlet.security.Guard} or manually. * * @return True if the identifier or principal has been authenticated. * @deprecated Use {@link ClientInfo#isAuthenticated()} instead. */ @Deprecated public boolean isAuthenticated() { return this.authenticated; } /** * Indicates if the identifier or principal has been authenticated. The * application is responsible for updating this property, relying on a * {@link org.restlet.security.Guard} or manually. * * @param authenticated * True if the identifier or principal has been authenticated. * @deprecated Use {@link ClientInfo#setAuthenticated(boolean)} instead. */ @Deprecated public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } /** * Sets the client nonce. * * @param clientNonce * The client nonce. */ public void setClientNonce(String clientNonce) { this.clientNonce = clientNonce; } /** * Sets the raw credentials. * * @param credentials * The credentials. * @deprecated Use {@link #getRawValue()} instead. */ @Deprecated public void setCredentials(String credentials) { setRawValue(credentials); } /** * Sets the digest URI reference. * * @param digestRef * The digest URI reference. */ public void setDigestRef(Reference digestRef) { this.digestRef = digestRef; } /** * Sets the user identifier, such as a login name or an access key. * * @param identifier * The user identifier, such as a login name or an access key. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Sets the chosen quality of protection. * * @param quality * The chosen quality of protection. */ public void setQuality(String quality) { this.quality = quality; } /** * Sets the user secret, such as a password or a secret key. * * @param secret * The user secret, such as a password or a secret key. */ public void setSecret(char[] secret) { this.secret = secret; } /** * Sets the user secret, such as a password or a secret key. * * @param secret * The user secret, such as a password or a secret key. */ public void setSecret(String secret) { this.secret = (secret == null) ? null : secret.toCharArray(); } /** * Sets the server nonce count. * * @param serverNounceCount * The server nonce count. */ public void setServerNounceCount(int serverNounceCount) { this.serverNounceCount = serverNounceCount; } } restlet-2.0.14/org.restlet/src/org/restlet/data/Status.java0000664000175000017500000016747211757206346024337 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.engine.Edition; import org.restlet.engine.Engine; /** * Status to return after handling a call. * * @author Jerome Louvel */ public final class Status { private static final String BASE_HTTP = "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; private static final String BASE_RESTLET = "http://www.restlet.org/documentation/" + Engine.MAJOR_NUMBER + '.' + Engine.MINOR_NUMBER + "/" + Edition.CURRENT.getShortName().toLowerCase() + "/api/"; private static final String BASE_WEBDAV = "http://www.webdav.org/specs/rfc2518.html"; /** * The request could not be understood by the server due to malformed * syntax. * * @see HTTP * RFC - 10.4.1 400 Bad Request */ public static final Status CLIENT_ERROR_BAD_REQUEST = new Status(400); /** * The request could not be completed due to a conflict with the current * state of the resource (as experienced in a version control system). * * @see HTTP * RFC - 10.4.10 409 Conflict */ public static final Status CLIENT_ERROR_CONFLICT = new Status(409); /** * The user agent expects some behavior of the server (given in an Expect * request-header field), but this expectation could not be met by this * server. * * @see HTTP * RFC - 10.4.18 417 Expectation Failed */ public static final Status CLIENT_ERROR_EXPECTATION_FAILED = new Status(417); /** * This status code means that the method could not be performed on the * resource because the requested action depended on another action and that * action failed. * * @see WEBDAV * RFC - 10.5 424 Failed Dependency */ public static final Status CLIENT_ERROR_FAILED_DEPENDENCY = new Status(424); /** * The server understood the request, but is refusing to fulfill it as it * could be explained in the entity. * * @see HTTP * RFC - 10.4.4 403 Forbidden */ public static final Status CLIENT_ERROR_FORBIDDEN = new Status(403); /** * The requested resource is no longer available at the server and no * forwarding address is known. * * @see HTTP * RFC - 10.4.11 410 Gone */ public static final Status CLIENT_ERROR_GONE = new Status(410); /** * The server refuses to accept the request without a defined * Content-Length. * * @see HTTP * RFC - 10.4.12 411 Length Required */ public static final Status CLIENT_ERROR_LENGTH_REQUIRED = new Status(411); /** * The source or destination resource of a method is locked (or temporarily * involved in another process). * * @see WEBDAV * RFC - 10.4 423 Locked */ public static final Status CLIENT_ERROR_LOCKED = new Status(423); /** * The method specified in the Request-Line is not allowed for the resource * identified by the Request-URI. * * @see HTTP * RFC - 10.4.6 405 Method Not Allowed */ public static final Status CLIENT_ERROR_METHOD_NOT_ALLOWED = new Status(405); /** * The resource identified by the request is only capable of generating * response entities whose content characteristics do not match the user's * requirements (in Accept* headers). * * @see HTTP * RFC - 10.4.7 406 Not Acceptable */ public static final Status CLIENT_ERROR_NOT_ACCEPTABLE = new Status(406); /** * The server has not found anything matching the Request-URI or the server * does not wish to reveal exactly why the request has been refused, or no * other response is applicable. * * @see HTTP * RFC - 10.4.5 404 Not Found */ public static final Status CLIENT_ERROR_NOT_FOUND = new Status(404); /** * This code is reserved for future use. * * @see HTTP * RFC - 10.4.3 402 Payment Required */ public static final Status CLIENT_ERROR_PAYMENT_REQUIRED = new Status(402); /** * Sent by the server when the user agent asks the server to carry out a * request under certain conditions that are not met. * * @see HTTP * RFC - 10.4.13 412 Precondition Failed */ public static final Status CLIENT_ERROR_PRECONDITION_FAILED = new Status( 412); /** * This code is similar to 401 (Unauthorized), but indicates that the client * must first authenticate itself with the proxy. * * @see HTTP * RFC - 10.4.8 407 Proxy Authentication Required */ public static final Status CLIENT_ERROR_PROXY_AUTHENTIFICATION_REQUIRED = new Status( 407); /** * The server is refusing to process a request because the request entity is * larger than the server is willing or able to process. * * @see HTTP * RFC - 10.4.14 413 Request Entity Too Large */ public static final Status CLIENT_ERROR_REQUEST_ENTITY_TOO_LARGE = new Status( 413); /** * Sent by the server when an HTTP client opens a connection, but has never * sent a request (or never sent the blank line that signals the end of the * request). * * @see HTTP * RFC - 10.4.9 408 Request Timeout */ public static final Status CLIENT_ERROR_REQUEST_TIMEOUT = new Status(408); /** * The server is refusing to service the request because the Request-URI is * longer than the server is willing to interpret. * * @see HTTP * RFC - 10.4.15 414 Request-URI Too Long */ public static final Status CLIENT_ERROR_REQUEST_URI_TOO_LONG = new Status( 414); /** * The request includes a Range request-header field and the selected * resource is too small for any of the byte-ranges to apply. * * @see HTTP * RFC - 10.4.17 416 Requested Range Not Satisfiable */ public static final Status CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE = new Status( 416); /** * The request requires user authentication. * * @see HTTP * RFC - 10.4.2 401 Unauthorized */ public static final Status CLIENT_ERROR_UNAUTHORIZED = new Status(401); /** * This status code means the server understands the content type of the * request entity (syntactically correct) but was unable to process the * contained instructions. * * @see WEBDAV * RFC - 10.3 422 Unprocessable Entity */ public static final Status CLIENT_ERROR_UNPROCESSABLE_ENTITY = new Status( 422); /** * The server is refusing to service the request because the entity of the * request is in a format not supported by the requested resource for the * requested method. * * @see HTTP * RFC - 10.4.16 415 Unsupported Media Type */ public static final Status CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE = new Status( 415); /** * The client connector faced an error during the communication with the * remote server (interruption, timeout, etc.). The status code is 1001. */ public static final Status CONNECTOR_ERROR_COMMUNICATION = new Status(1001); /** * The client connector could not connect to the remote server. The status * code is 1000. */ public static final Status CONNECTOR_ERROR_CONNECTION = new Status(1000); /** * The client connector faced an internal error during the process of a * request to its server or the process of a response to its client. The * status code is 1002. */ public static final Status CONNECTOR_ERROR_INTERNAL = new Status(1002); /** * This interim response (the client has to wait for the final response) is * used to inform the client that the initial part of the request has been * received and has not yet been rejected or completed by the server. * * @see HTTP * RFC - 10.1.1 100 Continue */ public static final Status INFO_CONTINUE = new Status(100); /** * This interim response is used to inform the client that the server has * accepted the complete request, but has not yet completed it since the * server has a reasonable expectation that the request will take * significant time to complete. * * @see WEBDAV * RFC - 10.1 102 Processing */ public static final Status INFO_PROCESSING = new Status(102); /** * The server understands and is willing to comply with the client's * request, via the Upgrade message header field, for a change in the * application protocol being used on this connection. * * @see HTTP * RFC - 10.1.1 101 Switching Protocols */ public static final Status INFO_SWITCHING_PROTOCOL = new Status(101); /** * Warning status code, typically returned by a cache, indicating that the * response is stale. * * @see HTTP * RFC - 14.46 Warning */ public static final Status INFO_STALE_RESPONSE = new Status(110); /** * Warning status code, typically returned by a cache, indicating that the * response is stale because an attempt to revalidate the response failed, * due to an inability to reach the server. * * @see HTTP * RFC - 14.46 Warning */ public static final Status INFO_REVALIDATION_FAILED = new Status(111); /** * Warning status code, typically returned by a cache, indicating that it is * intentionally disconnected from the rest of the network for a period of * time. * * @see HTTP * RFC - 14.46 Warning */ public static final Status INFO_DISCONNECTED_OPERATION = new Status(112); /** * Warning status code, typically returned by a cache, indicating that it * heuristically chose a freshness lifetime greater than 24 hours and the * response's age is greater than 24 hours. * * @see HTTP * RFC - 14.46 Warning */ public static final Status INFO_HEURISTIC_EXPIRATION = new Status(113); /** * Warning status code, optionally including arbitrary information to be * presented to a human user, typically returned by a cache. * * @see HTTP * RFC - 14.46 Warning */ public static final Status INFO_MISC_WARNING = new Status(199); /** * The requested resource resides temporarily under a different URI which * should not be used for future requests by the client (use status codes * 303 or 307 instead since this status has been manifestly misused). * * @see HTTP * RFC - 10.3.3 302 Found */ public static final Status REDIRECTION_FOUND = new Status(302); /** * The server lets the user agent choosing one of the multiple * representations of the requested resource, each representation having its * own specific location provided in the response entity. * * @see HTTP * RFC - 10.3.1 300 Multiple Choices */ public static final Status REDIRECTION_MULTIPLE_CHOICES = new Status(300); /** * Status code sent by the server in response to a conditional GET request * in case the document has not been modified. * * @see HTTP * RFC - 10.3.5 304 Not Modified */ public static final Status REDIRECTION_NOT_MODIFIED = new Status(304); /** * The requested resource has been assigned a new permanent URI and any * future references to this resource SHOULD use one of the returned URIs. * * @see HTTP * RFC - 10.3.2 301 Moved Permanently */ public static final Status REDIRECTION_PERMANENT = new Status(301); /** * The response to the request can be found under a different URI and SHOULD * be retrieved using a GET method on that resource. * * @see HTTP * RFC - 10.3.4 303 See Other */ public static final Status REDIRECTION_SEE_OTHER = new Status(303); /** * The requested resource resides temporarily under a different URI which * should not be used for future requests by the client. * * @see HTTP * RFC - 10.3.8 307 Temporary Redirect */ public static final Status REDIRECTION_TEMPORARY = new Status(307); /** * The requested resource MUST be accessed through the proxy given by the * Location field. * * @see HTTP * RFC - 10.3.6 305 Use Proxy */ public static final Status REDIRECTION_USE_PROXY = new Status(305); /** * The server, while acting as a gateway or proxy, received an invalid * response from the upstream server it accessed in attempting to fulfill * the request. * * @see HTTP * RFC - 10.5.3 502 Bad Gateway */ public static final Status SERVER_ERROR_BAD_GATEWAY = new Status(502); /** * The server, while acting as a gateway or proxy, could not connect to the * upstream server. * * @see HTTP * RFC - 10.5.5 504 Gateway Timeout */ public static final Status SERVER_ERROR_GATEWAY_TIMEOUT = new Status(504); /** * This status code means the method could not be performed on the resource * because the server is unable to store the representation needed to * successfully complete the request. * * @see WEBDAV * RFC - 10.6 507 Insufficient Storage */ public static final Status SERVER_ERROR_INSUFFICIENT_STORAGE = new Status( 507); /** * The server encountered an unexpected condition which prevented it from * fulfilling the request. * * @see HTTP * RFC - 10.5.1 500 Internal Server Error */ public static final Status SERVER_ERROR_INTERNAL = new Status(500); /** * The server does not support the functionality required to fulfill the * request. * * @see HTTP * RFC - 10.5.2 501 Not Implemented */ public static final Status SERVER_ERROR_NOT_IMPLEMENTED = new Status(501); /** * The server is currently unable to handle the request due to a temporary * overloading or maintenance of the server. * * @see HTTP * RFC - 10.5.4 503 Service Unavailable */ public static final Status SERVER_ERROR_SERVICE_UNAVAILABLE = new Status( 503); /** * The server does not support, or refuses to support, the HTTP protocol * version that was used in the request message. * * @see HTTP * RFC - 10.5.6 505 HTTP Version Not Supported */ public static final Status SERVER_ERROR_VERSION_NOT_SUPPORTED = new Status( 505); /** * The request has been accepted for processing, but the processing has not * been completed. * * @see HTTP * RFC - 10.2.3 202 Accepted */ public static final Status SUCCESS_ACCEPTED = new Status(202); /** * The request has been fulfilled and resulted in a new resource being * created. * * @see HTTP * RFC - 10.2.2 201 Created */ public static final Status SUCCESS_CREATED = new Status(201); /** * This response is used to inform the client that the HTTP response entity * contains a set of status codes generated during the method invocation. * * @see WEBDAV * RFC - 10.2 207 Multi-Status */ public static final Status SUCCESS_MULTI_STATUS = new Status(207); /** * The server has fulfilled the request but does not need to return an * entity-body (for example after a DELETE), and might want to return * updated meta-information. * * @see HTTP * RFC - 10.2.5 204 No Content */ public static final Status SUCCESS_NO_CONTENT = new Status(204); /** * The request has succeeded but the returned meta-information in the * entity-header does not come from the origin server, but is gathered from * a local or a third-party copy. * * @see HTTP * RFC - 10.2.4 203 Non-Authoritative Information */ public static final Status SUCCESS_NON_AUTHORITATIVE = new Status(203); /** * The request has succeeded. * * @see HTTP * RFC - 10.2.1 200 OK */ public static final Status SUCCESS_OK = new Status(200); /** * Warning status code, typically returned by a cache or a proxy, indicating * that the response has been transformed. * * @see HTTP * RFC - 14.46 Warning */ public static final Status SUCCESS_TRANSFORMATION_APPLIED = new Status(214); /** * Warning status code, optionally including arbitrary information to be * presented to a human user, typically returned by a cache. * * @see HTTP * RFC - 14.46 Warning */ public static final Status SUCCESS_MISC_PERSISTENT_WARNING = new Status(299); /** * The server has fulfilled the partial GET request for the resource * assuming the request has included a Range header field indicating the * desired range. * * @see HTTP * RFC - 10.2.7 206 Partial Content */ public static final Status SUCCESS_PARTIAL_CONTENT = new Status(206); /** * The server has fulfilled the request and the user agent SHOULD reset the * document view which caused the request to be sent. * * @see HTTP * RFC - 10.2.6 205 Reset Content */ public static final Status SUCCESS_RESET_CONTENT = new Status(205); /** * Check if the provided name of the status contains forbidden characters * such as CR and LF. an IllegalArgumentException is thrown in this case. * * @see Status * Code and Reason Phrase * @param name * The name to check * @return The name if it is correct. */ private static String checkName(String name) { if (name != null) { if (name.contains("\n") || name.contains("\r")) { throw new IllegalArgumentException( "Name of the status must not contain CR or LF characters."); } } return name; } /** * Indicates if the status is a client error status, meaning "The request * contains bad syntax or cannot be fulfilled". * * @param code * The code of the status. * @return True if the status is a client error status. */ public static boolean isClientError(int code) { return (code >= 400) && (code <= 499); } /** * Indicates if the status is a connector error status, meaning "The * connector failed to send or receive an apparently valid message". * * @param code * The code of the status. * @return True if the status is a server error status. */ public static boolean isConnectorError(int code) { return (code >= 1000) && (code <= 1099); } /** * Indicates if the status is an error (client or server) status. * * @param code * The code of the status. * @return True if the status is an error (client or server) status. */ public static boolean isError(int code) { return isClientError(code) || isServerError(code) || isConnectorError(code); } /** * Indicates if the status is a client error status, meaning "The request * contains bad syntax or cannot be fulfilled". * * @param code * The code of the status. * @return True if the status is a client error status. */ public static boolean isGlobalError(int code) { return (code >= 600) && (code <= 699); } /** * Indicates if the status is an information status, meaning "request * received, continuing process". * * @param code * The code of the status. * @return True if the status is an information status. */ public static boolean isInformational(int code) { return (code >= 100) && (code <= 199); } /** * Indicates if the status is a redirection status, meaning "Further action * must be taken in order to complete the request". * * @param code * The code of the status. * @return True if the status is a redirection status. */ public static boolean isRedirection(int code) { return (code >= 300) && (code <= 399); } /** * Indicates if the status is a server error status, meaning "The server * failed to fulfill an apparently valid request". * * @param code * The code of the status. * @return True if the status is a server error status. */ public static boolean isServerError(int code) { return (code >= 500) && (code <= 599); } /** * Indicates if the status is a success status, meaning "The action was * successfully received, understood, and accepted". * * @param code * The code of the status. * @return True if the status is a success status. */ public static boolean isSuccess(int code) { return (code >= 200) && (code <= 299); } /** * Returns the status associated to a code. If an existing constant exists * then it is returned, otherwise a new instance is created. * * @param code * The code. * @return The associated status. */ public static Status valueOf(int code) { Status result = null; switch (code) { case 100: result = INFO_CONTINUE; break; case 101: result = INFO_SWITCHING_PROTOCOL; break; case 102: result = INFO_PROCESSING; break; case 110: result = INFO_STALE_RESPONSE; break; case 111: result = INFO_REVALIDATION_FAILED; break; case 112: result = INFO_DISCONNECTED_OPERATION; break; case 113: result = INFO_HEURISTIC_EXPIRATION; break; case 199: result = INFO_MISC_WARNING; break; case 200: result = SUCCESS_OK; break; case 201: result = SUCCESS_CREATED; break; case 202: result = SUCCESS_ACCEPTED; break; case 203: result = SUCCESS_NON_AUTHORITATIVE; break; case 204: result = SUCCESS_NO_CONTENT; break; case 205: result = SUCCESS_RESET_CONTENT; break; case 206: result = SUCCESS_PARTIAL_CONTENT; break; case 207: result = SUCCESS_MULTI_STATUS; break; case 214: result = SUCCESS_TRANSFORMATION_APPLIED; break; case 299: result = SUCCESS_MISC_PERSISTENT_WARNING; break; case 300: result = REDIRECTION_MULTIPLE_CHOICES; break; case 301: result = REDIRECTION_PERMANENT; break; case 302: result = REDIRECTION_FOUND; break; case 303: result = REDIRECTION_SEE_OTHER; break; case 304: result = REDIRECTION_NOT_MODIFIED; break; case 305: result = REDIRECTION_USE_PROXY; break; case 307: result = REDIRECTION_TEMPORARY; break; case 400: result = CLIENT_ERROR_BAD_REQUEST; break; case 401: result = CLIENT_ERROR_UNAUTHORIZED; break; case 402: result = CLIENT_ERROR_PAYMENT_REQUIRED; break; case 403: result = CLIENT_ERROR_FORBIDDEN; break; case 404: result = CLIENT_ERROR_NOT_FOUND; break; case 405: result = CLIENT_ERROR_METHOD_NOT_ALLOWED; break; case 406: result = CLIENT_ERROR_NOT_ACCEPTABLE; break; case 407: result = CLIENT_ERROR_PROXY_AUTHENTIFICATION_REQUIRED; break; case 408: result = CLIENT_ERROR_REQUEST_TIMEOUT; break; case 409: result = CLIENT_ERROR_CONFLICT; break; case 410: result = CLIENT_ERROR_GONE; break; case 411: result = CLIENT_ERROR_LENGTH_REQUIRED; break; case 412: result = CLIENT_ERROR_PRECONDITION_FAILED; break; case 413: result = CLIENT_ERROR_REQUEST_ENTITY_TOO_LARGE; break; case 414: result = CLIENT_ERROR_REQUEST_URI_TOO_LONG; break; case 415: result = CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE; break; case 416: result = CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE; break; case 417: result = CLIENT_ERROR_EXPECTATION_FAILED; break; case 422: result = CLIENT_ERROR_UNPROCESSABLE_ENTITY; break; case 423: result = CLIENT_ERROR_LOCKED; break; case 424: result = CLIENT_ERROR_FAILED_DEPENDENCY; break; case 500: result = SERVER_ERROR_INTERNAL; break; case 501: result = SERVER_ERROR_NOT_IMPLEMENTED; break; case 502: result = SERVER_ERROR_BAD_GATEWAY; break; case 503: result = SERVER_ERROR_SERVICE_UNAVAILABLE; break; case 504: result = SERVER_ERROR_GATEWAY_TIMEOUT; break; case 505: result = SERVER_ERROR_VERSION_NOT_SUPPORTED; break; case 507: result = SERVER_ERROR_INSUFFICIENT_STORAGE; break; case 1000: result = CONNECTOR_ERROR_CONNECTION; break; case 1001: result = CONNECTOR_ERROR_COMMUNICATION; break; case 1002: result = CONNECTOR_ERROR_INTERNAL; break; default: result = new Status(code); } return result; } /** The specification code. */ private final int code; /** The description. */ private final String description; /** The name. */ private volatile String name; /** The related error or exception. */ private final Throwable throwable; /** The URI of the specification describing the method. */ private final String uri; /** * Constructor. * * @param code * The specification code. */ public Status(int code) { this(code, null, null, null, null); } /** * Constructor. * * @param code * The specification code. * @param name * The name. * @param description * The description. * @param uri * The URI of the specification describing the method. */ public Status(int code, final String name, final String description, final String uri) { this(code, null, name, description, uri); } /** * Constructor. * * @param code * The specification code. * @param throwable * The related error or exception. */ public Status(int code, Throwable throwable) { this(code, throwable, null, null, null); } /** * Constructor. * * @param code * The specification code. * @param throwable * The related error or exception. * @param name * The name. * @param description * The description. * @param uri * The URI of the specification describing the method. */ public Status(int code, Throwable throwable, final String name, final String description, final String uri) { this.code = code; this.throwable = throwable; this.name = checkName(name); this.description = description; this.uri = uri; } /** * Constructor. * * @param status * The status to copy. * @param description * The description to associate. */ public Status(final Status status, final String description) { this(status, null, description); } /** * Constructor. * * @param status * The status to copy. * @param throwable * The related error or exception. */ public Status(final Status status, final Throwable throwable) { this(status, throwable, null); } /** * Constructor. * * @param status * The status to copy. * @param throwable * The related error or exception. * @param description * The description to associate. */ public Status(Status status, Throwable throwable, String description) { this(status.getCode(), (throwable == null) ? status.getThrowable() : throwable, status.getName(), (description == null) ? status.getDescription() : description, status.getUri()); } /** * Indicates if the status is equal to a given one. * * @param object * The object to compare to. * @return True if the status is equal to a given one. */ @Override public boolean equals(final Object object) { return (object instanceof Status) && (this.code == ((Status) object).getCode()); } /** * Returns the corresponding code (HTTP or WebDAV or custom code). * * @return The corresponding code. */ public int getCode() { return this.code; } /** * Returns the description. * * @return The description. */ public String getDescription() { String result = this.description; if (result == null) { switch (this.code) { case 100: result = "The client should continue with its request"; break; case 101: result = "The server is willing to change the application protocol being used on this connection"; break; case 102: result = "Interim response used to inform the client that the server has accepted the complete request, but has not yet completed it"; break; case 110: result = "MUST be included whenever the returned response is stale"; break; case 111: result = "MUST be included if a cache returns a stale response because an attempt to revalidate the response failed, due to an inability to reach the server"; break; case 112: result = "SHOULD be included if the cache is intentionally disconnected from the rest of the network for a period of time"; break; case 113: result = "MUST be included if the cache heuristically chose a freshness lifetime greater than 24 hours and the response's age is greater than 24 hours"; break; case 199: result = "The warning text MAY include arbitrary information to be presented to a human user, or logged. A system receiving this warning MUST NOT take any automated action, besides presenting the warning to the user"; break; case 200: result = "The request has succeeded"; break; case 201: result = "The request has been fulfilled and resulted in a new resource being created"; break; case 202: result = "The request has been accepted for processing, but the processing has not been completed"; break; case 203: result = "The returned meta-information is not the definitive set as available from the origin server"; break; case 204: result = "The server has fulfilled the request but does not need to return an entity-body, and might want to return updated meta-information"; break; case 205: result = "The server has fulfilled the request and the user agent should reset the document view which caused the request to be sent"; break; case 206: result = "The server has fulfilled the partial get request for the resource"; break; case 207: result = "Provides status for multiple independent operations"; break; case 214: result = "MUST be added by an intermediate cache or proxy if it applies any transformation changing the content-coding (as specified in the Content-Encoding header) or media-type (as specified in the Content-Type header) of the response, or the entity-body of the response, unless this Warning code already appears in the response"; break; case 299: result = "The warning text MAY include arbitrary information to be presented to a human user, or logged. A system receiving this warning MUST NOT take any automated action"; break; case 300: result = "The requested resource corresponds to any one of a set of representations"; break; case 301: result = "The requested resource has been assigned a new permanent URI"; break; case 302: result = "The requested resource can be found under a different URI"; break; case 303: result = "The response to the request can be found under a different URI"; break; case 304: result = "The client has performed a conditional GET request and the document has not been modified"; break; case 305: result = "The requested resource must be accessed through the proxy given by the location field"; break; case 307: result = "The requested resource resides temporarily under a different URI"; break; case 400: result = "The request could not be understood by the server due to malformed syntax"; break; case 401: result = "The request requires user authentication"; break; case 402: result = "This code is reserved for future use"; break; case 403: result = "The server understood the request, but is refusing to fulfill it"; break; case 404: result = "The server has not found anything matching the request URI"; break; case 405: result = "The method specified in the request is not allowed for the resource identified by the request URI"; break; case 406: result = "The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request"; break; case 407: result = "This code is similar to Unauthorized, but indicates that the client must first authenticate itself with the proxy"; break; case 408: result = "The client did not produce a request within the time that the server was prepared to wait"; break; case 409: result = "The request could not be completed due to a conflict with the current state of the resource"; break; case 410: result = "The requested resource is no longer available at the server and no forwarding address is known"; break; case 411: result = "The server refuses to accept the request without a defined content length"; break; case 412: result = "The precondition given in one or more of the request header fields evaluated to false when it was tested on the server"; break; case 413: result = "The server is refusing to process a request because the request entity is larger than the server is willing or able to process"; break; case 414: result = "The server is refusing to service the request because the request URI is longer than the server is willing to interpret"; break; case 415: result = "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method"; break; case 416: result = "For byte ranges, this means that the first byte position were greater than the current length of the selected resource"; break; case 417: result = "The expectation given in the request header could not be met by this server"; break; case 422: result = "The server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the contained instructions"; break; case 423: result = "The source or destination resource of a method is locked"; break; case 424: result = "The method could not be performed on the resource because the requested action depended on another action and that action failed"; break; case 500: result = "The server encountered an unexpected condition which prevented it from fulfilling the request"; break; case 501: result = "The server does not support the functionality required to fulfill the request"; break; case 502: result = "The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request"; break; case 503: result = "The server is currently unable to handle the request due to a temporary overloading or maintenance of the server"; break; case 504: result = "The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request"; break; case 505: result = "The server does not support, or refuses to support, the protocol version that was used in the request message"; break; case 507: result = "The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request"; break; case 1000: result = "The connector failed to connect to the server"; break; case 1001: result = "The connector failed to complete the communication with the server"; break; case 1002: result = "The connector encountered an unexpected condition which prevented it from fulfilling the request"; break; } } return result; } /** * Returns the name of this status. * * @return The name of this status. */ public String getName() { String result = this.name; if (result == null) { switch (this.code) { case 100: result = "Continue"; break; case 101: result = "Switching Protocols"; break; case 102: result = "Processing"; break; case 110: result = "Response is stale"; break; case 111: result = "Revalidation failed"; break; case 112: result = "Disconnected operation"; break; case 113: result = "Heuristic expiration"; break; case 199: result = "Miscellaneous warning"; break; case 200: result = "OK"; break; case 201: result = "Created"; break; case 202: result = "Accepted"; break; case 203: result = "Non-Authoritative Information"; break; case 204: result = "No Content"; break; case 205: result = "Reset Content"; break; case 206: result = "Partial Content"; break; case 207: result = "Multi-Status"; break; case 214: result = "Transformation applied"; break; case 299: result = "Miscellaneous persistent warning"; break; case 300: result = "Multiple Choices"; break; case 301: result = "Moved Permanently"; break; case 302: result = "Found"; break; case 303: result = "See Other"; break; case 304: result = "Not Modified"; break; case 305: result = "Use Proxy"; break; case 307: result = "Temporary Redirect"; break; case 400: result = "Bad Request"; break; case 401: result = "Unauthorized"; break; case 402: result = "Payment Required"; break; case 403: result = "Forbidden"; break; case 404: result = "Not Found"; break; case 405: result = "Method Not Allowed"; break; case 406: result = "Not Acceptable"; break; case 407: result = "Proxy Authentication Required"; break; case 408: result = "Request Timeout"; break; case 409: result = "Conflict"; break; case 410: result = "Gone"; break; case 411: result = "Length Required"; break; case 412: result = "Precondition Failed"; break; case 413: result = "Request Entity Too Large"; break; case 414: result = "Request URI Too Long"; break; case 415: result = "Unsupported Media Type"; break; case 416: result = "Requested Range Not Satisfiable"; break; case 417: result = "Expectation Failed"; break; case 422: result = "Unprocessable Entity"; break; case 423: result = "Locked"; break; case 424: result = "Failed Dependency"; break; case 500: result = "Internal Server Error"; break; case 501: result = "Not Implemented"; break; case 502: result = "Bad Gateway"; break; case 503: result = "Service Unavailable"; break; case 504: result = "Gateway Timeout"; break; case 505: result = "Version Not Supported"; break; case 507: result = "Insufficient Storage"; break; case 1000: result = "Connection Error"; break; case 1001: result = "Communication Error"; break; case 1002: result = "Internal Connector Error"; break; } } return result; } /** * Returns the related error or exception. * * @return The related error or exception. */ public Throwable getThrowable() { return this.throwable; } /** * Returns the URI of the specification describing the status. * * @return The URI of the specification describing the status. */ public String getUri() { String result = this.uri; if (result == null) { switch (this.code) { case 100: result = BASE_HTTP + "#sec10.1.1"; break; case 101: result = BASE_HTTP + "#sec10.1.2"; break; case 102: result = BASE_WEBDAV + "#STATUS_102"; break; case 110: case 111: case 112: case 113: case 199: case 214: case 299: result = "http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46"; break; case 200: result = BASE_HTTP + "#sec10.2.1"; break; case 201: result = BASE_HTTP + "#sec10.2.2"; break; case 202: result = BASE_HTTP + "#sec10.2.3"; break; case 203: result = BASE_HTTP + "#sec10.2.4"; break; case 204: result = BASE_HTTP + "#sec10.2.5"; break; case 205: result = BASE_HTTP + "#sec10.2.6"; break; case 206: result = BASE_HTTP + "#sec10.2.7"; break; case 207: result = BASE_WEBDAV + "#STATUS_207"; break; case 300: result = BASE_HTTP + "#sec10.3.1"; break; case 301: result = BASE_HTTP + "#sec10.3.2"; break; case 302: result = BASE_HTTP + "#sec10.3.3"; break; case 303: result = BASE_HTTP + "#sec10.3.4"; break; case 304: result = BASE_HTTP + "#sec10.3.5"; break; case 305: result = BASE_HTTP + "#sec10.3.6"; break; case 307: result = BASE_HTTP + "#sec10.3.8"; break; case 400: result = BASE_HTTP + "#sec10.4.1"; break; case 401: result = BASE_HTTP + "#sec10.4.2"; break; case 402: result = BASE_HTTP + "#sec10.4.3"; break; case 403: result = BASE_HTTP + "#sec10.4.4"; break; case 404: result = BASE_HTTP + "#sec10.4.5"; break; case 405: result = BASE_HTTP + "#sec10.4.6"; break; case 406: result = BASE_HTTP + "#sec10.4.7"; break; case 407: result = BASE_HTTP + "#sec10.4.8"; break; case 408: result = BASE_HTTP + "#sec10.4.9"; break; case 409: result = BASE_HTTP + "#sec10.4.10"; break; case 410: result = BASE_HTTP + "#sec10.4.11"; break; case 411: result = BASE_HTTP + "#sec10.4.12"; break; case 412: result = BASE_HTTP + "#sec10.4.13"; break; case 413: result = BASE_HTTP + "#sec10.4.14"; break; case 414: result = BASE_HTTP + "#sec10.4.15"; break; case 415: result = BASE_HTTP + "#sec10.4.16"; break; case 416: result = BASE_HTTP + "#sec10.4.17"; break; case 417: result = BASE_HTTP + "#sec10.4.18"; break; case 422: result = BASE_WEBDAV + "#STATUS_422"; break; case 423: result = BASE_WEBDAV + "#STATUS_423"; break; case 424: result = BASE_WEBDAV + "#STATUS_424"; break; case 500: result = BASE_HTTP + "#sec10.5.1"; break; case 501: result = BASE_HTTP + "#sec10.5.2"; break; case 502: result = BASE_HTTP + "#sec10.5.3"; break; case 503: result = BASE_HTTP + "#sec10.5.4"; break; case 504: result = BASE_HTTP + "#sec10.5.5"; break; case 505: result = BASE_HTTP + "#sec10.5.6"; break; case 507: result = BASE_WEBDAV + "#STATUS_507"; break; case 1000: result = BASE_RESTLET + "org/restlet/data/Status.html#CONNECTOR_ERROR_CONNECTION"; break; case 1001: result = BASE_RESTLET + "org/restlet/data/Status.html#CONNECTOR_ERROR_COMMUNICATION"; break; case 1002: result = BASE_RESTLET + "org/restlet/data/Status.html#CONNECTOR_ERROR_INTERNAL"; break; } } return result; } /** {@inheritDoc} */ @Override public int hashCode() { return getCode(); } /** * Indicates if the status is a client error status, meaning "The request * contains bad syntax or cannot be fulfilled". * * @return True if the status is a client error status. */ public boolean isClientError() { return isClientError(getCode()); } /** * Indicates if the status is a connector error status, meaning "The * connector failed to send or receive an apparently valid message". * * @return True if the status is a connector error status. */ public boolean isConnectorError() { return isConnectorError(getCode()); } /** * Indicates if the status is an error (client or server) status. * * @return True if the status is an error (client or server) status. */ public boolean isError() { return isError(getCode()); } /** * Indicates if the status is a global error status, meaning "The server has * definitive information about a particular user". * * @return True if the status is a global error status. */ public boolean isGlobalError() { return isGlobalError(getCode()); } /** * Indicates if the status is an information status, meaning "request * received, continuing process". * * @return True if the status is an information status. */ public boolean isInformational() { return isInformational(getCode()); } /** * Indicates if an error is recoverable, meaning that simply retrying after * a delay could result in a success. Tests {@link #isConnectorError()} and * if the status is {@link #CLIENT_ERROR_REQUEST_TIMEOUT} or * {@link #SERVER_ERROR_GATEWAY_TIMEOUT} or * {@link #SERVER_ERROR_SERVICE_UNAVAILABLE}. * * @return True if the error is recoverable. */ public boolean isRecoverableError() { return isConnectorError() || equals(Status.CLIENT_ERROR_REQUEST_TIMEOUT) || equals(Status.SERVER_ERROR_GATEWAY_TIMEOUT) || equals(Status.SERVER_ERROR_SERVICE_UNAVAILABLE); } /** * Indicates if the status is a redirection status, meaning "Further action * must be taken in order to complete the request". * * @return True if the status is a redirection status. */ public boolean isRedirection() { return isRedirection(getCode()); } /** * Indicates if the status is a server error status, meaning "The server * failed to fulfill an apparently valid request". * * @return True if the status is a server error status. */ public boolean isServerError() { return isServerError(getCode()); } /** * Indicates if the status is a success status, meaning "The action was * successfully received, understood, and accepted". * * @return True if the status is a success status. */ public boolean isSuccess() { return isSuccess(getCode()); } /** * Returns the name of the status followed by its HTTP code. * * @return The name of the status followed by its HTTP code. */ @Override public String toString() { return getName() + " (" + this.code + ")" + ((getDescription() == null) ? "" : " - " + getDescription()); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Language.java0000664000175000017500000001704211757206346024562 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Language used in representations and preferences. A language tag is composed * of one or more parts: A primary language tag and a possibly empty series of * sub-tags. When formatted as a string, parts are separated by hyphens. * * @author Jerome Louvel */ public final class Language extends Metadata { /** All languages acceptable. */ public static final Language ALL = new Language("*", "All languages"); /** * The default language of the JVM. * * @see java.util.Locale#getDefault() */ public static final Language DEFAULT = new Language(java.util.Locale .getDefault().getLanguage()); /** English language. */ public static final Language ENGLISH = new Language("en", "English language"); /** English language spoken in USA. */ public static final Language ENGLISH_US = new Language("en-us", "English language in USA"); /** French language. */ public static final Language FRENCH = new Language("fr", "French language"); /** French language spoken in France. */ public static final Language FRENCH_FRANCE = new Language("fr-fr", "French language in France"); /** Spanish language. */ public static final Language SPANISH = new Language("es", "Spanish language"); /** * Returns the language associated to a name. If an existing constant exists * then it is returned, otherwise a new instance is created. * * @param name * The name. * @return The associated language. */ public static Language valueOf(final String name) { Language result = null; if ((name != null) && !name.equals("")) { if (name.equalsIgnoreCase(ALL.getName())) { result = ALL; } else if (name.equalsIgnoreCase(ENGLISH.getName())) { result = ENGLISH; } else if (name.equalsIgnoreCase(ENGLISH_US.getName())) { result = ENGLISH_US; } else if (name.equalsIgnoreCase(FRENCH.getName())) { result = FRENCH; } else if (name.equalsIgnoreCase(FRENCH_FRANCE.getName())) { result = FRENCH_FRANCE; } else if (name.equalsIgnoreCase(SPANISH.getName())) { result = SPANISH; } else { result = new Language(name); } } return result; } /** The metadata main list of subtags taken from the metadata name. */ private volatile List subTags; /** * Constructor. * * @param name * The name. */ public Language(final String name) { this(name, "Language or range of languages"); } /** * Constructor. * * @param name * The name. * @param description * The description. */ public Language(final String name, final String description) { super(name, description); this.subTags = null; } /** {@inheritDoc} */ @Override public boolean equals(final Object object) { return (object instanceof Language) && getName().equalsIgnoreCase(((Language) object).getName()); } @Override public Language getParent() { Language result = null; if ((getSubTags() != null) && !getSubTags().isEmpty()) { result = Language.valueOf(getPrimaryTag()); } else { result = equals(ALL) ? null : ALL; } return result; } /** * Returns the primary tag. * * @return The primary tag. */ public String getPrimaryTag() { final int separator = getName().indexOf('-'); if (separator == -1) { return getName(); } return getName().substring(0, separator); } /** * Returns the unmodifiable list of subtags. This list can be empty. * * @return The list of subtags for this language Tag. */ public List getSubTags() { // Lazy initialization with double-check. List v = this.subTags; if (v == null) { synchronized (this) { v = this.subTags; if (v == null) { List tokens = new CopyOnWriteArrayList(); if (getName() != null) { final String[] tags = getName().split("-"); if (tags.length > 0) { for (int i = 1; i < tags.length; i++) { tokens.add(tags[i]); } } } this.subTags = v = Collections.unmodifiableList(tokens); } } } return v; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().toLowerCase().hashCode(); } /** * Indicates if a given language is included in the current one. The test is * true if both languages are equal or if the given language is within the * range of the current one. For example, ALL includes all languages. A null * language is considered as included into the current one. *

    * Examples: *

      *
    • ENGLISH.includes(ENGLISH_US) -> true
    • *
    • ENGLISH_US.includes(ENGLISH) -> false
    • *
    * * @param included * The language to test for inclusion. * @return True if the language type is included in the current one. * @see #isCompatible(Metadata) */ public boolean includes(Metadata included) { boolean result = equals(ALL) || (included == null) || equals(included); if (!result && (included instanceof Language)) { Language includedLanguage = (Language) included; if (getPrimaryTag().equals(includedLanguage.getPrimaryTag())) { // Both languages are different if (getSubTags().equals(includedLanguage.getSubTags())) { result = true; } else if (getSubTags().isEmpty()) { result = true; } } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/data/Digest.java0000664000175000017500000001046311757206346024256 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.Arrays; import org.restlet.representation.Representation; /** * Describes a digest value and the digest algorithm used. Digests can have * several use cases such as ensuring the integrity of representations exchanges * between resources, or for authentication purpose. * * @see Representation#getDigest() * @author Jerome Louvel */ public class Digest { /** Digest algorithm defined in RFC 1319. */ public static final String ALGORITHM_MD2 = "MD2"; /** Digest algorithm defined in RFC 1321. */ public static final String ALGORITHM_MD5 = "MD5"; /** No digest algorithm defined. */ public static final String ALGORITHM_NONE = "NONE"; /** Digest algorithm defined in Secure Hash Standard, NIST FIPS 180-1. */ public static final String ALGORITHM_SHA_1 = "SHA-1"; /** NIST approved digest algorithm from SHA-2 family. */ public static final String ALGORITHM_SHA_256 = "SHA-256"; /** NIST approved digest algorithm from SHA-2 family. */ public static final String ALGORITHM_SHA_384 = "SHA-384"; /** NIST approved digest algorithm from SHA-2 family. */ public static final String ALGORITHM_SHA_512 = "SHA-512"; /** * Digest algorithm for the HTTP DIGEST scheme. This is exactly the A1 value * specified in RFC2617 which is a MD5 hash of the user name, realm and * password, separated by a colon character. */ public static final String ALGORITHM_HTTP_DIGEST = "HTTP-DIGEST-A1"; /** The digest algorithm. */ private final String algorithm; /** The digest value. */ private final byte[] value; /** * Constructor using the MD5 algorithm by default. * * @param value * The digest value. */ public Digest(byte[] value) { this(ALGORITHM_MD5, value); } /** * Constructor. * * @param algorithm * The digest algorithm. * @param value * The digest value. */ public Digest(String algorithm, byte[] value) { this.algorithm = algorithm; // In Java 6, use Arrays.copyOf. this.value = new byte[value.length]; for (int i = 0; i < value.length; i++) { this.value[i] = value[i]; } } @Override public boolean equals(Object obj) { boolean result = (obj instanceof Digest); if (result) { Digest d = (Digest) obj; result = getAlgorithm().equals(d.getAlgorithm()); result = result && Arrays.equals(getValue(), d.getValue()); } return result; } /** * Returns the digest algorithm. * * @return The digest algorithm. */ public String getAlgorithm() { return algorithm; } /** * Returns the digest value. * * @return The digest value. */ public byte[] getValue() { // In Java 6, use Arrays.copyOf. byte[] result = new byte[this.value.length]; for (int i = 0; i < this.value.length; i++) { result[i] = this.value[i]; } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/data/agent.properties0000664000175000017500000000530711757206350025404 0ustar jamespagejamespage#Firefox for Windows Mozilla/{mozillaVersion} ({osData}Windows; U; {agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} Mozilla/{mozillaVersion} ({osData}Windows; U; {agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} ({agentComment}) #Firefox for Macintosh Mozilla/{mozillaVersion} ({osData}Macintosh; U; {agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} Mozilla/{mozillaVersion} ({osData}Macintosh; U; {agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} ({agentComment}) #Firefox for Linux Mozilla/{mozillaVersion} (X11; U; {agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} Mozilla/{mozillaVersion} (X11; U; {agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} ({agentComment}) #Firefox (default) Mozilla/{mozillaVersion} ({agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} ({agentComment}) Mozilla/{mozillaVersion} ({agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion} #Internet Explorer (default) Mozilla/{mozillaVersion} (compatible; {agentName} {agentVersion}; {agentOs}{facultativeData}) #Chrome Mozilla/{mozillaVersion} ({agentOsShortName}; {osData}) AppleWebKit/{appleWebKitVersion} ({appleWebKitComment}) {agentName}/{agentVersion} Safari/{safariVersion} Mozilla/{mozillaVersion} ({agentOsShortName}; U; {osData}) AppleWebKit/{appleWebKitVersion} ({appleWebKitComment}) {agentName}/{agentVersion} {safariData} #Safari Mozilla/{mozillaVersion} ({agentOsShortName}; U; {agentOs};{osData}) AppleWebKit/{appleWebKitVersion} ({appleWebKitComment}) Version/{agentVersion} {agentName}/{buildNumber} Mozilla/{mozillaVersion} ({agentOsShortName}; U; {agentOs};{osData}) AppleWebKit/{appleWebKitVersion} ({appleWebKitComment}) {agentName}/{agentVersion} Mozilla/{mozillaVersion} ({agentOsShortName}; {agentOs}) AppleWebKit/{appleWebKitVersion} ({appleWebKitComment}) Version/{agentVersion} {agentName}/{buildNumber} #Opera for Macintosh {agentName}/{agentVersion} (Macintosh; {agentOs}; U; {osData}) #Opera for Linux {agentName}/{agentVersion} (X11; {agentOs}; U; {osData}) #Opera for Windows {agentName}/{agentVersion} ({agentOs}; U; {osData}) #Konqueror Mozilla/{mozillaVersion} (compatible; {agentName}/{commentAttribute}; {agentOs}{facultativeData}) KHTML/{agentVersion} ({agentComment}) Mozilla/{mozillaVersion} (compatible; {agentName}/{commentAttribute}; {agentOs}{facultativeData}) KHTML/{agentVersion} #Misc {agentName}/{agentVersion} {agentName}/{agentVersion} ({agentComment}) restlet-2.0.14/org.restlet/src/org/restlet/data/CacheDirective.java0000664000175000017500000003661411757206346025707 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.List; import org.restlet.engine.http.header.HeaderConstants; /** * Directive for caching mechanisms along the call chain. This overrides the * default behavior of those caches and proxies.
    *
    * Note that when used with HTTP connectors, this class maps to the * "Cache-Control" header. * * @author Jerome Louvel */ public final class CacheDirective extends Parameter { /** * Creates a "max-age" directive. Indicates that the client is willing to * accept a response whose age is no greater than the specified time in * seconds. Unless "max-stale" directive is also included, the client is not * willing to accept a stale response.
    *
    * Note that this directive can be used on requests or responses. * * @param maxAge * Maximum age in seconds. * @return A new "max-age" directive. * @see HTTP * 1.1 - Modifications of the Basic Expiration Mechanism * @see HTTP * 1.1 - Cache Revalidation and Reload Controls */ public static CacheDirective maxAge(int maxAge) { return new CacheDirective(HeaderConstants.CACHE_MAX_AGE, Integer .toString(maxAge), true); } /** * Creates a "max-stale" directive. Indicates that the client is willing to * accept a response that has exceeded its expiration time by any amount of * time.
    *
    * Note that this directive can be used on requests only. * * @return A new "max-stale" directive. * @see HTTP * 1.1 - Modifications of the Basic Expiration Mechanism */ public static CacheDirective maxStale() { return new CacheDirective(HeaderConstants.CACHE_MAX_STALE); } /** * Creates a "max-stale" directive. Indicates that the client is willing to * accept a response that has exceeded its expiration time by a given amount * of time.
    *
    * Note that this directive can be used on requests only. * * @param maxStale * Maximum stale age in seconds. * @return A new "max-stale" directive. * @see HTTP * 1.1 - Modifications of the Basic Expiration Mechanism */ public static CacheDirective maxStale(int maxStale) { return new CacheDirective(HeaderConstants.CACHE_MAX_STALE, Integer .toString(maxStale), true); } /** * Creates a "min-fresh" directive. Indicates that the client is willing to * accept a response whose freshness lifetime is no less than its current * age plus the specified time in seconds. That is, the client wants a * response that will still be fresh for at least the specified number of * seconds.
    *
    * Note that this directive can be used on requests only. * * @param minFresh * Minimum freshness lifetime in seconds. * @return A new "min-fresh" directive. * @see HTTP * 1.1 - Modifications of the Basic Expiration Mechanism */ public static CacheDirective minFresh(int minFresh) { return new CacheDirective(HeaderConstants.CACHE_MIN_FRESH, Integer .toString(minFresh), true); } /** * Creates a "must-revalidate" directive. Indicates that the origin server * requires revalidation of a cache entry on any subsequent use.
    *
    * Note that this directive can be used on responses only. * * @return A new "must-revalidate" directive. * @see HTTP * 1.1 - Cache Revalidation and Reload Controls */ public static CacheDirective mustRevalidate() { return new CacheDirective(HeaderConstants.CACHE_MUST_REVALIDATE); } /** * Creates a "no-cache" directive. Indicates that a cache must not use the * response to satisfy subsequent requests without successful revalidation * with the origin server.
    *
    * Note that this directive can be used on requests or responses. * * @return A new "no-cache" directive. * @see HTTP * 1.1 - What is Cacheable */ public static CacheDirective noCache() { return new CacheDirective(HeaderConstants.CACHE_NO_CACHE); } /** * Creates a "no-cache" directive. Indicates that a cache must not use the * response to satisfy subsequent requests without successful revalidation * with the origin server.
    *
    * Note that this directive can be used on requests or responses. * * @param fieldNames * Field names, typically a HTTP header name, that must not be * sent by caches. * @return A new "no-cache" directive. * @see HTTP * 1.1 - What is Cacheable */ public static CacheDirective noCache(List fieldNames) { StringBuilder sb = new StringBuilder(); if (fieldNames != null) { for (int i = 0; i < fieldNames.size(); i++) { sb.append("\"" + fieldNames.get(i) + "\""); if (i < fieldNames.size() - 1) { sb.append(','); } } } return new CacheDirective(HeaderConstants.CACHE_NO_CACHE, sb.toString()); } /** * Creates a "no-cache" directive. Indicates that a cache must not use the * response to satisfy subsequent requests without successful revalidation * with the origin server.
    *
    * Note that this directive can be used on requests or responses. * * @param fieldName * A field name, typically a HTTP header name, that must not be * sent by caches. * @return A new "no-cache" directive. * @see HTTP * 1.1 - What is Cacheable */ public static CacheDirective noCache(String fieldName) { return new CacheDirective(HeaderConstants.CACHE_NO_CACHE, "\"" + fieldName + "\""); } /** * Creates a "no-store" directive. Indicates that a cache must not release * or retain any information about the call. This applies to both private * and shared caches.
    *
    * Note that this directive can be used on requests or responses. * * @return A new "no-store" directive. * @see HTTP * 1.1 - What May be Stored by Caches */ public static CacheDirective noStore() { return new CacheDirective(HeaderConstants.CACHE_NO_STORE); } /** * Creates a "no-transform" directive. Indicates that a cache or * intermediary proxy must not transform the response entity.
    *
    * Note that this directive can be used on requests or responses. * * @return A new "no-transform" directive. * @see HTTP * 1.1 - No-Transform Directive */ public static CacheDirective noTransform() { return new CacheDirective(HeaderConstants.CACHE_NO_TRANSFORM); } /** * Creates a "onlyIfCached" directive. Indicates that only cached responses * should be returned to the client.
    *
    * Note that this directive can be used on requests only. * * @return A new "only-if-cached" directive. * @see HTTP * 1.1 - Cache Revalidation and Reload Controls */ public static CacheDirective onlyIfCached() { return new CacheDirective(HeaderConstants.CACHE_ONLY_IF_CACHED); } /** * Creates a "private" directive. Indicates that all or part of the response * message is intended for a single user and must not be cached by a shared * cache.
    *
    * Note that this directive can be used on responses only. * * @return A new "private" directive. * @see HTTP * 1.1 - What is Cacheable */ public static CacheDirective privateInfo() { return new CacheDirective(HeaderConstants.CACHE_PRIVATE); } /** * Creates a "private" directive. Indicates that all or part of the response * message is intended for a single user and must not be cached by a shared * cache.
    *
    * Note that this directive can be used on responses only. * * @param fieldNames * Field names, typically a HTTP header name, that must be * private. * @return A new "private" directive. * @see HTTP * 1.1 - What is Cacheable */ public static CacheDirective privateInfo(List fieldNames) { StringBuilder sb = new StringBuilder(); if (fieldNames != null) { for (int i = 0; i < fieldNames.size(); i++) { sb.append("\"" + fieldNames.get(i) + "\""); if (i < fieldNames.size() - 1) { sb.append(','); } } } return new CacheDirective(HeaderConstants.CACHE_PRIVATE, sb.toString()); } /** * Creates a "private" directive. Indicates that all or part of the response * message is intended for a single user and must not be cached by a shared * cache.
    *
    * Note that this directive can be used on responses only. * * @param fieldName * A field name, typically a HTTP header name, that is private. * @return A new "private" directive. * @see HTTP * 1.1 - What is Cacheable */ public static CacheDirective privateInfo(String fieldName) { return new CacheDirective(HeaderConstants.CACHE_PRIVATE, "\"" + fieldName + "\""); } /** * Creates a "proxy-revalidate" directive. Indicates that the origin server * requires revalidation of a cache entry on any subsequent use, except that * it does not apply to non-shared user agent caches
    *
    * Note that this directive can be used on responses only. * * @return A new "proxy-revalidate" directive. * @see HTTP * 1.1 - Cache Revalidation and Reload Controls */ public static CacheDirective proxyMustRevalidate() { return new CacheDirective(HeaderConstants.CACHE_PROXY_MUST_REVALIDATE); } /** * Creates a "public" directive. Indicates that the response may be cached * by any cache, even if it would normally be non-cacheable or cacheable * only within a non-shared cache.
    *
    * Note that this directive can be used on responses only. * * @return A new "public" directive. * @see HTTP * 1.1 - What is Cacheable */ public static CacheDirective publicInfo() { return new CacheDirective(HeaderConstants.CACHE_PUBLIC); } /** * Creates a "s-maxage" directive. Indicates that the client is willing to * accept a response from a shared cache (but not a private cache) whose age * is no greater than the specified time in seconds.
    *
    * Note that this directive can be used on responses only. * * @param sharedMaxAge * Maximum age in seconds. * @return A new "s-maxage" directive. * @see HTTP * 1.1 - Modifications of the Basic Expiration Mechanism */ public static CacheDirective sharedMaxAge(int sharedMaxAge) { return new CacheDirective(HeaderConstants.CACHE_SHARED_MAX_AGE, Integer .toString(sharedMaxAge), true); } /** Indicates if the directive is a digit value. */ private boolean digit; /** * Constructor for directives with no value. * * @param name * The directive name. */ public CacheDirective(String name) { this(name, null); } /** * Constructor for directives with a value. * * @param name * The directive name. * @param value * The directive value. */ public CacheDirective(String name, String value) { this(name, value, false); } /** * Constructor for directives with a value. * * @param name * The directive name. * @param value * The directive value. * @param digit * The kind of value (true for a digit value, false otherwise). */ public CacheDirective(String name, String value, boolean digit) { super(name, value); this.digit = digit; } /** * Returns true if the directive contains a digit value. * * @return True if the directive contains a digit value. */ public boolean isDigit() { return digit; } /** * Indicates if the directive is a digit value. * * @param digit * True if the directive contains a digit value. */ public void setDigit(boolean digit) { this.digit = digit; } } restlet-2.0.14/org.restlet/src/org/restlet/data/ChallengeRequest.java0000664000175000017500000001566011757206350026271 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Authentication challenge sent by an origin server to a client. Upon reception * of this request, the client should send a new request with the proper * {@link ChallengeResponse} set.
    *
    * Note that when used with HTTP connectors, this class maps to the * "WWW-Authenticate" header. * * @author Jerome Louvel */ public final class ChallengeRequest extends ChallengeMessage { /** The available options for quality of protection. */ private volatile List qualityOptions; /** The URI references that define the protection domains. */ private volatile List domainRefs; /** Indicates if the previous request from the client was stale. */ private volatile boolean stale; /** * Constructor. * * @param scheme * The challenge scheme. */ public ChallengeRequest(ChallengeScheme scheme) { this(scheme, null); } /** * Constructor. * * @param scheme * The challenge scheme. * @param realm * The authentication realm. */ public ChallengeRequest(ChallengeScheme scheme, String realm) { super(scheme, realm); this.domainRefs = null; this.qualityOptions = null; this.stale = false; } /** {@inheritDoc} */ @Override public boolean equals(final Object obj) { boolean result = (obj == this); // if obj == this no need to go further if (!result) { // if obj isn't a challenge request or is null don't evaluate // further if (obj instanceof ChallengeRequest) { final ChallengeRequest that = (ChallengeRequest) obj; result = (getParameters().equals(that.getParameters())); if (result) { if (getRealm() != null) { result = getRealm().equals(that.getRealm()); } else { result = (that.getRealm() == null); } if (result) { if (getScheme() != null) { result = getScheme().equals(that.getScheme()); } else { result = (that.getScheme() == null); } } } } } return result; } /** * Returns the base URI references that collectively define the protected * domains for the digest authentication. By default it return a list with a * single "/" URI reference. * * @return The base URI references. */ public List getDomainRefs() { // Lazy initialization with double-check. List r = this.domainRefs; if (r == null) { synchronized (this) { r = this.domainRefs; if (r == null) { this.domainRefs = r = new CopyOnWriteArrayList(); this.domainRefs.add(new Reference("/")); } } } return r; } /** * Returns the available options for quality of protection. The default * value is {@link #QUALITY_AUTHENTICATION}. * * @return The available options for quality of protection. */ public List getQualityOptions() { // Lazy initialization with double-check. List r = this.qualityOptions; if (r == null) { synchronized (this) { r = this.qualityOptions; if (r == null) { this.qualityOptions = r = new CopyOnWriteArrayList(); this.qualityOptions.add(QUALITY_AUTHENTICATION); } } } return r; } /** * Indicates if the previous request from the client was stale. * * @return True if the previous request from the client was stale. */ public boolean isStale() { return stale; } /** * Sets the URI references that define the protection domains for the digest * authentication. * * @param domainRefs * The base URI references. */ public void setDomainRefs(List domainRefs) { this.domainRefs = domainRefs; } /** * Sets the URI references that define the protection domains for the digest * authentication. Note that the parameters are copied into a new * {@link CopyOnWriteArrayList} instance. * * @param domainUris * The base URI references. * @see #setDomainRefs(List) */ public void setDomainUris(Collection domainUris) { List domainRefs = null; if (domainUris != null) { domainRefs = new CopyOnWriteArrayList(); for (String domainUri : domainUris) { domainRefs.add(new Reference(domainUri)); } } setDomainRefs(domainRefs); } /** * Sets the available options for quality of protection. The default value * is {@link #QUALITY_AUTHENTICATION}. * * @param qualityOptions * The available options for quality of protection. */ public void setQualityOptions(List qualityOptions) { this.qualityOptions = qualityOptions; } /** * Indicates if the previous request from the client was stale. * * @param stale * True if the previous request from the client was stale. */ public void setStale(boolean stale) { this.stale = stale; } } restlet-2.0.14/org.restlet/src/org/restlet/data/ChallengeScheme.java0000664000175000017500000002044411757206350026041 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Challenge scheme used to authenticate remote clients. * * @author Jerome Louvel */ public final class ChallengeScheme { /** Custom scheme based on IP address or cookies or query parameters, etc. */ public static final ChallengeScheme CUSTOM = new ChallengeScheme("CUSTOM", "Custom", "Custom authentication"); /** Amazon S3 HTTP scheme. */ public static final ChallengeScheme HTTP_AWS_S3 = new ChallengeScheme( "HTTP_AWS", "AWS", "Amazon S3 HTTP authentication"); /** Basic HTTP scheme. */ public static final ChallengeScheme HTTP_BASIC = new ChallengeScheme( "HTTP_BASIC", "Basic", "Basic HTTP authentication"); /** Cookie HTTP scheme. */ public static final ChallengeScheme HTTP_COOKIE = new ChallengeScheme( "HTTP_Cookie", "Cookie", "Cookie HTTP authentication"); /** Digest HTTP scheme. */ public static final ChallengeScheme HTTP_DIGEST = new ChallengeScheme( "HTTP_DIGEST", "Digest", "Digest HTTP authentication"); /** * Microsoft Azure Shared Key scheme. * * @see MSDN * page */ public static final ChallengeScheme HTTP_AZURE_SHAREDKEY = new ChallengeScheme( "HTTP_AZURE_SHAREDKEY", "SharedKey", "Microsoft Azure Shared Key authorization (authentication)"); /** * Microsoft Azure Shared Key lite scheme. * * @see MSDN * page */ public static final ChallengeScheme HTTP_AZURE_SHAREDKEY_LITE = new ChallengeScheme( "HTTP_AZURE_SHAREDKEY_LITE", "SharedKeyLite", "Microsoft Azure Shared Key lite authorization (authentication)"); /** Microsoft NTML HTTP scheme. */ public static final ChallengeScheme HTTP_NTLM = new ChallengeScheme( "HTTP_NTLM", "NTLM", "Microsoft NTLM HTTP authentication"); /** OAuth HTTP scheme. */ public static final ChallengeScheme HTTP_OAUTH = new ChallengeScheme( "HTTP_OAuth", "OAuth", "Open protocol for API authentication"); /** Basic POP scheme. Based on the USER/PASS commands. */ public static final ChallengeScheme POP_BASIC = new ChallengeScheme( "POP_BASIC", "Basic", "Basic POP authentication (USER/PASS commands)"); /** Digest POP scheme. Based on the APOP command. */ public static final ChallengeScheme POP_DIGEST = new ChallengeScheme( "POP_DIGEST", "Digest", "Digest POP authentication (APOP command)"); /** Plain SMTP scheme. */ public static final ChallengeScheme SMTP_PLAIN = new ChallengeScheme( "SMTP_PLAIN", "PLAIN", "Plain SMTP authentication"); /** Plain FTP scheme. */ public static final ChallengeScheme FTP_PLAIN = new ChallengeScheme( "FTP_PLAIN", "PLAIN", "Plain FTP authentication"); /** * Returns the challenge scheme associated to a scheme name. If an existing * constant exists then it is returned, otherwise a new instance is created. * * @param name * The scheme name. * @return The associated challenge scheme. */ public static ChallengeScheme valueOf(final String name) { ChallengeScheme result = null; if ((name != null) && !name.equals("")) { if (name.equalsIgnoreCase(CUSTOM.getName())) { result = CUSTOM; } else if (name.equalsIgnoreCase(HTTP_AWS_S3.getName())) { result = HTTP_AWS_S3; } else if (name.equalsIgnoreCase(HTTP_BASIC.getName())) { result = HTTP_BASIC; } else if (name.equalsIgnoreCase(HTTP_COOKIE.getName())) { result = HTTP_COOKIE; } else if (name.equalsIgnoreCase(HTTP_DIGEST.getName())) { result = HTTP_DIGEST; } else if (name.equalsIgnoreCase(HTTP_AZURE_SHAREDKEY.getName())) { result = HTTP_AZURE_SHAREDKEY; } else if (name.equalsIgnoreCase(HTTP_AZURE_SHAREDKEY_LITE .getName())) { result = HTTP_AZURE_SHAREDKEY_LITE; } else if (name.equalsIgnoreCase(HTTP_NTLM.getName())) { result = HTTP_NTLM; } else if (name.equalsIgnoreCase(HTTP_OAUTH.getName())) { result = HTTP_OAUTH; } else if (name.equalsIgnoreCase(POP_BASIC.getName())) { result = POP_BASIC; } else if (name.equalsIgnoreCase(POP_DIGEST.getName())) { result = POP_DIGEST; } else if (name.equalsIgnoreCase(SMTP_PLAIN.getName())) { result = SMTP_PLAIN; } else { result = new ChallengeScheme(name, null, null); } } return result; } /** The description. */ private final String description; /** The name. */ private volatile String name; /** The technical name. */ private volatile String technicalName; /** * Constructor. * * @param name * The unique name. * @param technicalName * The technical name. */ public ChallengeScheme(final String name, final String technicalName) { this(name, technicalName, null); } /** * Constructor. * * @param name * The unique name. * @param technicalName * The technical name. * @param description * The description. */ public ChallengeScheme(final String name, final String technicalName, final String description) { this.name = name; this.description = description; this.technicalName = technicalName; } /** {@inheritDoc} */ @Override public boolean equals(final Object object) { return (object instanceof ChallengeScheme) && ((ChallengeScheme) object).getName().equalsIgnoreCase( getName()); } /** * Returns the description. * * @return The description. */ public String getDescription() { return this.description; } /** * Returns the name. * * @return The name. */ public String getName() { return name; } /** * Returns the technical name (ex: BASIC). * * @return The technical name (ex: BASIC). */ public String getTechnicalName() { return this.technicalName; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().toLowerCase().hashCode(); } /** * Sets the technical name (ex: BASIC). * * @param technicalName * The technical name (ex: BASIC). */ @SuppressWarnings("unused") private void setTechnicalName(String technicalName) { this.technicalName = technicalName; } /** * Returns the name. * * @return The name. */ @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Protocol.java0000664000175000017500000003353211757206346024642 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Protocol used by client and server connectors. Connectors enable the * communication between components by implementing standard protocols. * * @author Jerome Louvel */ public final class Protocol { /** Indicates that the port number is undefined. */ public static final int UNKNOWN_PORT = -1; /** * AJP 1.3 protocol to communicate with Apache HTTP server or Microsoft IIS. */ public static final Protocol AJP = new Protocol("ajp", "AJP", "Apache Jakarta Protocol", 8009); /** All protocols wildcard. */ public static final Protocol ALL = new Protocol("all", "ALL", "Wildcard for all protocols", UNKNOWN_PORT); /** * CLAP (ClassLoader Access Protocol) is a custom scheme to access to * representations via classloaders. Example URI: * "clap://thread/org/restlet/Restlet.class".
    *
    * In order to work, CLAP requires a client connector provided by the core * Restlet engine. * * @see org.restlet.data.LocalReference */ public static final Protocol CLAP = new Protocol("clap", "CLAP", "Class Loader Access Protocol", UNKNOWN_PORT, true); /** * FILE is a standard scheme to access to representations stored in the file * system (locally most of the time). Example URI: * "file:///D/root/index.html".
    *
    * In order to work, FILE requires a client connector provided by the core * Restlet engine. * * @see org.restlet.data.LocalReference */ public static final Protocol FILE = new Protocol("file", "FILE", "Local File System Protocol", UNKNOWN_PORT, true); /** FTP protocol. */ public static final Protocol FTP = new Protocol("ftp", "FTP", "File Transfer Protocol", 21); /** HTTP protocol. */ public static final Protocol HTTP = new Protocol("http", "HTTP", "HyperText Transport Protocol", 80, "1.1"); /** HTTPS protocol (via SSL socket). */ public static final Protocol HTTPS = new Protocol("https", "HTTPS", "HTTP", "HyperText Transport Protocol (Secure)", 443, true, "1.1"); /** SIP protocol. */ public static final Protocol SIP = new Protocol("sip", "SIP", "Session Initiation Protocol", 5060, "2.0"); /** SIPS protocol (via SSL socket). */ public static final Protocol SIPS = new Protocol("sips", "SIPS", "SIP", "Session Initiation Protocol (Secure)", 5061, true, "2.0"); /** * JAR (Java ARchive) is a common scheme to access to representations inside * archive files. Example URI: * "jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class". * * @see org.restlet.data.LocalReference#createJarReference(Reference, * String) */ public static final Protocol JAR = new Protocol("jar", "JAR", "Java ARchive", UNKNOWN_PORT, true); /** JDBC protocol. */ public static final Protocol JDBC = new Protocol("jdbc", "JDBC", "Java DataBase Connectivity", UNKNOWN_PORT); /** POP protocol. */ public static final Protocol POP = new Protocol("pop", "POP", "Post Office Protocol", 110); /** POPS protocol (via SSL/TLS socket).. */ public static final Protocol POPS = new Protocol("pops", "POPS", "Post Office Protocol (Secure)", 995, true); /** * RIAP (Restlet Internal Access Protocol) is a custom scheme to access * representations via internal calls to virtual hosts/components. Example * URIs: "riap://component/myAppPath/myResource" and * "riap://application/myResource".
    *
    * In order to work, RIAP doesn't requires any client connector and is * automatically supported by the Restlet engine. * * @see org.restlet.data.LocalReference */ public static final Protocol RIAP = new Protocol("riap", "RIAP", "Restlet Internal Access Protocol", UNKNOWN_PORT, true); /** SMTP protocol. */ public static final Protocol SMTP = new Protocol("smtp", "SMTP", "Simple Mail Transfer Protocol", 25); /** SMTPS protocol (via SSL/TLS socket). */ public static final Protocol SMTPS = new Protocol("smtps", "SMTPS", "Simple Mail Transfer Protocol (Secure)", 465, true); /** Local Web Archive access protocol. */ public static final Protocol WAR = new Protocol("war", "WAR", "Web Archive Access Protocol", UNKNOWN_PORT, true); /** * ZIP is a special scheme to access to representations inside Zip archive * files. Example URI: "zip:file:///tmp/test.zip!/test.txt". * * @see org.restlet.data.LocalReference#createZipReference(Reference, * String) */ public static final Protocol ZIP = new Protocol("zip", "ZIP", "Zip Archive Access Protocol", UNKNOWN_PORT, true); /** * Creates the protocol associated to a URI scheme name. If an existing * constant exists then it is returned, otherwise a new instance is created. * * @param name * The scheme name. * @return The associated protocol. */ public static Protocol valueOf(String name) { Protocol result = null; if ((name != null) && !name.equals("")) { if (name.equalsIgnoreCase(AJP.getSchemeName())) { result = AJP; } else if (name.equalsIgnoreCase(CLAP.getSchemeName())) { result = CLAP; } else if (name.equalsIgnoreCase(FILE.getSchemeName())) { result = FILE; } else if (name.equalsIgnoreCase(FTP.getSchemeName())) { result = FTP; } else if (name.equalsIgnoreCase(HTTP.getSchemeName())) { result = HTTP; } else if (name.equalsIgnoreCase(HTTPS.getSchemeName())) { result = HTTPS; } else if (name.equalsIgnoreCase(JAR.getSchemeName())) { result = JAR; } else if (name.equalsIgnoreCase(JDBC.getSchemeName())) { result = JDBC; } else if (name.equalsIgnoreCase(POP.getSchemeName())) { result = POP; } else if (name.equalsIgnoreCase(POPS.getSchemeName())) { result = POPS; } else if (name.equalsIgnoreCase(RIAP.getSchemeName())) { result = RIAP; } else if (name.equalsIgnoreCase(SMTP.getSchemeName())) { result = SMTP; } else if (name.equalsIgnoreCase(SMTPS.getSchemeName())) { result = SMTPS; } else if (name.equalsIgnoreCase(SIP.getSchemeName())) { result = SIP; } else if (name.equalsIgnoreCase(SIPS.getSchemeName())) { result = SIPS; } else if (name.equalsIgnoreCase(WAR.getSchemeName())) { result = WAR; } else if (name.equalsIgnoreCase(ZIP.getSchemeName())) { result = ZIP; } else { result = new Protocol(name); } } return result; } /** The confidentiality. */ private final boolean confidential; /** The default port if known or -1. */ private final int defaultPort; /** The description. */ private final String description; /** The name. */ private final String name; /** The technical name that appears on the wire. */ private final String technicalName; /** The scheme name. */ private volatile String schemeName; /** The version. */ private volatile String version; /** * Constructor. * * @param schemeName * The scheme name. */ public Protocol(String schemeName) { this(schemeName, schemeName.toUpperCase(), schemeName.toUpperCase() + " Protocol", UNKNOWN_PORT); } /** * Constructor. * * @param schemeName * The scheme name. * @param name * The unique name. * @param description * The description. * @param defaultPort * The default port. */ public Protocol(String schemeName, String name, String description, int defaultPort) { this(schemeName, name, description, defaultPort, false); } /** * Constructor. * * @param schemeName * The scheme name. * @param name * The unique name. * @param description * The description. * @param defaultPort * The default port. * @param confidential * The confidentiality. */ public Protocol(String schemeName, String name, String description, int defaultPort, boolean confidential) { this(schemeName, name, description, defaultPort, confidential, null); } /** * Constructor. * * @param schemeName * The scheme name. * @param name * The unique name. * @param description * The description. * @param defaultPort * The default port. * @param confidential * The confidentiality. * @param version * The version. */ public Protocol(String schemeName, String name, String description, int defaultPort, boolean confidential, String version) { this(schemeName, name, name, description, defaultPort, confidential, version); } /** * Constructor. * * @param schemeName * The scheme name. * @param name * The unique name. * @param description * The description. * @param defaultPort * The default port. * @param version * The version. */ public Protocol(String schemeName, String name, String description, int defaultPort, String version) { this(schemeName, name, description, defaultPort, false, version); } /** * Constructor. * * @param schemeName * The scheme name. * @param name * The unique name. * @param technicalName * The technical name that appears on the wire. * @param description * The description. * @param defaultPort * The default port. * @param confidential * The confidentiality. * @param version * The version. */ public Protocol(String schemeName, String name, String technicalName, String description, int defaultPort, boolean confidential, String version) { this.name = name; this.description = description; this.schemeName = schemeName; this.technicalName = technicalName; this.defaultPort = defaultPort; this.confidential = confidential; this.version = version; } /** {@inheritDoc} */ @Override public boolean equals(final Object object) { return (object instanceof Protocol) && getName().equalsIgnoreCase(((Protocol) object).getName()); } /** * Returns the default port number. * * @return The default port number. */ public int getDefaultPort() { return this.defaultPort; } /** * Returns the description. * * @return The description. */ public String getDescription() { return this.description; } /** * Returns the name. * * @return The name. */ public String getName() { return name; } /** * Returns the URI scheme name. * * @return The URI scheme name. */ public String getSchemeName() { return this.schemeName; } /** * Returns the technical name that appears on the wire. * * @return The technical name that appears on the wire. */ public String getTechnicalName() { return technicalName; } /** * Returns the version. * * @return The version. */ public String getVersion() { return version; } /** {@inheritDoc} */ @Override public int hashCode() { return (getName() == null) ? 0 : getName().toLowerCase().hashCode(); } /** * Indicates if the protocol guarantees the confidentially of the messages * exchanged, for example via a SSL-secured connection. * * @return True if the protocol is confidential. */ public boolean isConfidential() { return this.confidential; } /** * Returns the name. * * @return The name. */ @Override public String toString() { return getName() + ((getVersion() == null) ? "" : "/" + getVersion()); } } restlet-2.0.14/org.restlet/src/org/restlet/data/ReferenceList.java0000664000175000017500000001447711757206346025602 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.restlet.engine.io.IoUtils; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.util.WrapperList; /** * List of URI references. * * @author Jerome Louvel */ public class ReferenceList extends WrapperList { /** The list's identifier. */ private volatile Reference identifier; /** * Constructor. */ public ReferenceList() { super(); } /** * Constructor. * * @param initialCapacity * The initial list capacity. */ public ReferenceList(int initialCapacity) { super(new ArrayList(initialCapacity)); } /** * Constructor. * * @param delegate * The delegate list. */ public ReferenceList(List delegate) { super(delegate); } /** * Constructor from a "text/uri-list" representation. * * @param uriList * The "text/uri-list" representation to parse. * @throws IOException */ public ReferenceList(Representation uriList) throws IOException { BufferedReader br = null; try { br = new BufferedReader(uriList.getReader(), IoUtils .getBufferSize()); String line = br.readLine(); // Checks if the list reference is specified as the first comment. if ((line != null) && line.startsWith("#")) { setIdentifier(new Reference(line.substring(1).trim())); line = br.readLine(); } while (line != null) { if (!line.startsWith("#")) { add(new Reference(line.trim())); } line = br.readLine(); } } finally { if (br != null) { br.close(); } } } /** * Creates then adds a reference at the end of the list. * * @param uri * The uri of the reference to add. * @return True (as per the general contract of the Collection.add method). */ public boolean add(String uri) { return add(new Reference(uri)); } /** * Returns the list identifier. * * @return The list identifier. */ public Reference getIdentifier() { return this.identifier; } /** * Returns a representation of the list in the "text/uri-list" format. * * @return A representation of the list in the "text/uri-list" format. */ public Representation getTextRepresentation() { final StringBuilder sb = new StringBuilder(); if (getIdentifier() != null) { sb.append("# ").append(getIdentifier().toString()).append("\r\n"); } for (final Reference ref : this) { sb.append(ref.toString()).append("\r\n"); } return new StringRepresentation(sb.toString(), MediaType.TEXT_URI_LIST); } /** * Returns a representation of the list in "text/html" format. * * @return A representation of the list in "text/html" format. */ public Representation getWebRepresentation() { // Create a simple HTML list final StringBuilder sb = new StringBuilder(); sb.append("\n"); if (getIdentifier() != null) { sb.append("

    Listing of \"" + getIdentifier().getPath() + "\"

    \n"); final Reference parentRef = getIdentifier().getParentRef(); if (!parentRef.equals(getIdentifier())) { sb.append("..
    \n"); } } else { sb.append("

    List of references

    \n"); } for (final Reference ref : this) { sb.append("" + ref.getRelativeRef(getIdentifier()) + "
    \n"); } sb.append("\n"); return new StringRepresentation(sb.toString(), MediaType.TEXT_HTML); } /** * Sets the list reference. * * @param identifier * The list identifier. */ public void setIdentifier(Reference identifier) { this.identifier = identifier; } /** * Sets the list reference. * * @param identifier * The list identifier as a URI. */ public void setIdentifier(String identifier) { setIdentifier(new Reference(identifier)); } /** * Returns a view of the portion of this list between the specified * fromIndex, inclusive, and toIndex, exclusive. * * @param fromIndex * The start position. * @param toIndex * The end position (exclusive). * @return The sub-list. */ @Override public ReferenceList subList(int fromIndex, int toIndex) { return new ReferenceList(getDelegate().subList(fromIndex, toIndex)); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Reference.java0000664000175000017500000030342711757206346024742 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.engine.Edition; /** * Reference to a Uniform Resource Identifier (URI). Contrary to the * java.net.URI class, this interface represents mutable references. It strictly * conforms to the RFC 3986 specifying URIs and follow its naming conventions.
    * *
     * URI reference        = absolute-reference | relative-reference
     * 
     * absolute-reference   = scheme ":" scheme-specific-part [ "#" fragment ]
     * scheme-specific-part = ( hierarchical-part [ "?" query ] ) | opaque-part
     * hierarchical-part    = ( "//" authority path-abempty ) | path-absolute | path-rootless | path-empty
     * authority            = [ user-info "@" ] host-domain [ ":" host-port ]
     * 
     * relative-reference   = relative-part [ "?" query ] [ "#" fragment ]
     * relative-part        = ( "//" authority path-abempty ) | path-absolute | path-noscheme | path-empty
     * 
     * path-abempty         = begins with "/" or is empty
     * path-absolute        = begins with "/" but not "//"
     * path-noscheme        = begins with a non-colon segment
     * path-rootless        = begins with a segment
     * path-empty           = zero characters
     * 
    * *

    * Note that this class doesn't encode or decode the reserved characters. It * assumes that the URIs or the URI parts passed in are properly encoded using * the standard URI encoding mechanism. You can use the static "encode()" and * "decode()" methods for this purpose. Note that if an invalid URI character is * detected by the constructor or one of the setters, a trace will be logged and * the character will be automatically encoded. *

    *

    * The fundamental point to underline is the difference between an URI * "reference" and an URI. Contrary to an URI (the target identifier of a REST * resource), an URI reference can be relative (with or without query and * fragment part). This relative URI reference can then be resolved against a * base reference via the getTargetRef() method which will return a new resolved * Reference instance, an absolute URI reference with no base reference and with * no dot-segments (the path segments "." and ".."). *

    *

    * You can also apply the getTargetRef() method on absolute references in order * to solve the dot-segments. Note that applying the getRelativeRef() method on * an absolute reference returns the current reference relatively to a base * reference, if any, and solves the dot-segments. *

    *

    * The Reference stores its data as a single string, the one passed to the * constructor. This string can always be obtained using the toString() method. * A couple of integer indexes are maintained to improve the extraction time of * various reference properties (URI components). *

    *

    * When you modify a specific component of the URI reference, via the setPath() * method for example, the internal string is simply regenerated by updating * only the relevant part. We try as much as possible to protect the bytes given * to the Reference class instead of transparently parsing and normalizing the * URI data. Our idea is to protect encodings and special characters in all case * and reduce the memory size taken by this class while making Reference * instances mutable. *

    *

    * Because the base reference is only a property of the Reference ("baseRef"). * When you use the "Reference(base, path)" constructor, it is equivalent to * doing:
    * ref = new Reference(path);
    * ref.setBaseRef(base); *

    *

    * The base ref is not automatically resolved or "merged" with the rest of the * reference information (the path here). For example, this let's you reuse a * single reference as the base of several relative references. If you modify * the base reference, all relative references are still accurate. *

    * Note that the name and value properties are thread safe, stored in volatile * members. * * @author Jerome Louvel * @see RFC 3986 */ public class Reference { /** Helps to map characters and their validity as URI characters. */ private static final boolean[] charValidityMap = new boolean[127]; static { // Initialize the map of valid characters. for (int character = 0; character < 127; character++) { charValidityMap[character] = isReserved(character) || isUnreserved(character) || (character == '%'); } } /** * Decodes a given string using the standard URI encoding mechanism and the * UTF-8 character set. * * @param toDecode * The string to decode. * @return The decoded string. */ public static String decode(String toDecode) { String result = null; if (toDecode != null) { try { result = java.net.URLDecoder.decode(toDecode, "UTF-8"); } catch (UnsupportedEncodingException uee) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to decode the string with the UTF-8 character set.", uee); } } return result; } /** * Decodes a given string using the standard URI encoding mechanism. If the * provided character set is null, the string is returned but not decoded. * Note: The * World Wide Web Consortium Recommendation states that UTF-8 should be * used. Not doing so may introduce incompatibilities. * * @param toDecode * The string to decode. * @param characterSet * The name of a supported character encoding. * @return The decoded string or null if the named character encoding is not * supported. */ public static String decode(String toDecode, CharacterSet characterSet) { if (Edition.CURRENT == Edition.GWT) { if (!CharacterSet.UTF_8.equals(characterSet)) { throw new IllegalArgumentException( "Only UTF-8 URL encoding is supported under GWT"); } } String result = null; try { result = (characterSet == null) ? toDecode : java.net.URLDecoder .decode(toDecode, characterSet.getName()); } catch (UnsupportedEncodingException uee) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to decode the string with the UTF-8 character set.", uee); } return result; } /** * Encodes a given string using the standard URI encoding mechanism and the * UTF-8 character set. * * @param toEncode * The string to encode. * @return The encoded string. */ public static String encode(String toEncode) { String result = null; if (toEncode != null) { try { result = java.net.URLEncoder.encode(toEncode, "UTF-8"); } catch (UnsupportedEncodingException uee) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to encode the string with the UTF-8 character set.", uee); } } return result; } /** * Encodes a given string using the standard URI encoding mechanism. If the * provided character set is null, the string is returned but not encoded. * * Note: The * World Wide Web Consortium Recommendation states that UTF-8 should be * used. Not doing so may introduce incompatibilites. * * @param toEncode * The string to encode. * @param characterSet * The supported character encoding. * @return The encoded string or null if the named character encoding is not * supported. */ public static String encode(String toEncode, CharacterSet characterSet) { if (Edition.CURRENT == Edition.GWT) { if (!CharacterSet.UTF_8.equals(characterSet)) { throw new IllegalArgumentException( "Only UTF-8 URL encoding is supported under GWT"); } } String result = null; try { result = (characterSet == null) ? toEncode : java.net.URLEncoder .encode(toEncode, characterSet.getName()); } catch (UnsupportedEncodingException uee) { Context.getCurrentLogger() .log(Level.WARNING, "Unable to encode the string with the UTF-8 character set.", uee); } return result; } /** * Indicates if the given character is alphabetical (a-z or A-Z). * * @param character * The character to test. * @return True if the given character is alphabetical (a-z or A-Z). */ private static boolean isAlpha(int character) { return isUpperCase(character) || isLowerCase(character); } /** * Indicates if the given character is a digit (0-9). * * @param character * The character to test. * @return True if the given character is a digit (0-9). */ private static boolean isDigit(int character) { return (character >= '0') && (character <= '9'); } /** * Indicates if the given character is a generic URI component delimiter * character. * * @param character * The character to test. * @return True if the given character is a generic URI component delimiter * character. */ public static boolean isGenericDelimiter(int character) { return (character == ':') || (character == '/') || (character == '?') || (character == '#') || (character == '[') || (character == ']') || (character == '@'); } /** * Indicates if the given character is lower case (a-z). * * @param character * The character to test. * @return True if the given character is lower case (a-z). */ private static boolean isLowerCase(int character) { return (character >= 'a') && (character <= 'z'); } /** * Indicates if the given character is a reserved URI character. * * @param character * The character to test. * @return True if the given character is a reserved URI character. */ public static boolean isReserved(int character) { return isGenericDelimiter(character) || isSubDelimiter(character); } /** * Indicates if the given character is an URI subcomponent delimiter * character. * * @param character * The character to test. * @return True if the given character is an URI subcomponent delimiter * character. */ public static boolean isSubDelimiter(int character) { return (character == '!') || (character == '$') || (character == '&') || (character == '\'') || (character == '(') || (character == ')') || (character == '*') || (character == '+') || (character == ',') || (character == ';') || (character == '='); } /** * Indicates if the given character is an unreserved URI character. * * @param character * The character to test. * @return True if the given character is an unreserved URI character. */ public static boolean isUnreserved(int character) { return isAlpha(character) || isDigit(character) || (character == '-') || (character == '.') || (character == '_') || (character == '~'); } /** * Indicates if the given character is upper case (A-Z). * * @param character * The character to test. * @return True if the given character is upper case (A-Z). */ private static boolean isUpperCase(int character) { return (character >= 'A') && (character <= 'Z'); } /** * Indicates if the given character is a valid URI character. * * @param character * The character to test. * @return True if the given character is a valid URI character. */ public static boolean isValid(int character) { return character >= 0 && character < 127 && charValidityMap[character]; } /** * Creates a reference string from its parts. * * @param scheme * The scheme ("http", "https" or "ftp"). * @param hostName * The host name or IP address. * @param hostPort * The host port (default ports are correctly ignored). * @param path * The path component for hierarchical identifiers. * @param query * The optional query component for hierarchical identifiers. * @param fragment * The optional fragment identifier. * @return The reference as String. */ public static String toString(String scheme, String hostName, Integer hostPort, String path, String query, String fragment) { String host = hostName; // Appends the host port number if (hostPort != null) { final int defaultPort = Protocol.valueOf(scheme).getDefaultPort(); if (hostPort != defaultPort) { host = hostName + ':' + hostPort; } } return toString(scheme, host, path, query, fragment); } /** * Creates a relative reference string from its parts. * * @param relativePart * The relative part component. * @param query * The optional query component for hierarchical identifiers. * @param fragment * The optional fragment identifier. * @return The relative reference as a String. */ public static String toString(String relativePart, String query, String fragment) { final StringBuilder sb = new StringBuilder(); // Append the path if (relativePart != null) { sb.append(relativePart); } // Append the query string if (query != null) { sb.append('?').append(query); } // Append the fragment identifier if (fragment != null) { sb.append('#').append(fragment); } // Actually construct the reference return sb.toString(); } /** * Creates a reference string from its parts. * * @param scheme * The scheme ("http", "https" or "ftp"). * @param host * The host name or IP address plus the optional port number. * @param path * The path component for hierarchical identifiers. * @param query * The optional query component for hierarchical identifiers. * @param fragment * The optional fragment identifier. * @return The reference a String. */ public static String toString(String scheme, String host, String path, String query, String fragment) { final StringBuilder sb = new StringBuilder(); if (scheme != null) { // Append the scheme and host name sb.append(scheme.toLowerCase()).append("://").append(host); } // Append the path if (path != null) { sb.append(path); } // Append the query string if (query != null) { sb.append('?').append(query); } // Append the fragment identifier if (fragment != null) { sb.append('#').append(fragment); } // Actually construct the reference return sb.toString(); } /** The base reference for relative references. */ private volatile Reference baseRef; /** The fragment separator index. */ private volatile int fragmentIndex; /** The internal reference. */ private volatile String internalRef; /** The query separator index. */ private volatile int queryIndex; /** The scheme separator index. */ private volatile int schemeIndex; /** * Empty constructor. */ public Reference() { this((Reference) null, (String) null); } /** * Constructor from an {@link java.net.URI} instance. * * @param uri * The {@link java.net.URI} instance. */ public Reference(java.net.URI uri) { this(uri.toString()); } /** * Constructor from an {@link java.net.URL} instance. * * @param url * The {@link java.net.URL} instance. */ public Reference(java.net.URL url) { this(url.toString()); } /** * Constructor for a protocol and host name. Uses the default port for the * given protocol. * * @param protocol * Protocol/scheme to use * @param hostName * The host name or IP address. */ public Reference(Protocol protocol, String hostName) { this(protocol, hostName, protocol.getDefaultPort()); } /** * Constructor for a protocol, host name and host port * * @param protocol * Protocol/scheme to use * @param hostName * The host name or IP address. * @param hostPort * The host port (default ports are correctly ignored). */ public Reference(Protocol protocol, String hostName, int hostPort) { this(protocol.getSchemeName(), hostName, hostPort, null, null, null); } /** * Clone constructor. * * @param ref * The reference to clone. */ public Reference(Reference ref) { this(ref.baseRef, ref.internalRef); } /** * Constructor from an URI reference (most likely relative). * * @param baseRef * The base reference. * @param uriReference * The URI reference, either absolute or relative. */ public Reference(Reference baseRef, Reference uriReference) { this(baseRef, uriReference.toString()); } /** * Constructor from an URI reference (most likely relative). * * @param baseRef * The base reference. * @param uriRef * The URI reference, either absolute or relative. */ public Reference(Reference baseRef, String uriRef) { uriRef = encodeInvalidCharacters(uriRef); this.baseRef = baseRef; this.internalRef = uriRef; updateIndexes(); } /** * Constructor of relative reference from its parts. * * @param baseRef * The base reference. * @param relativePart * The relative part component (most of the time it is the path * component). * @param query * The optional query component for hierarchical identifiers. * @param fragment * The optional fragment identifier. */ public Reference(Reference baseRef, String relativePart, String query, String fragment) { this(baseRef, toString(relativePart, query, fragment)); } /** * Constructor from an URI reference. * * @param uriReference * The URI reference, either absolute or relative. */ public Reference(String uriReference) { this((Reference) null, uriReference); } /** * Constructor from an identifier and a fragment. * * @param identifier * The resource identifier. * @param fragment * The fragment identifier. */ public Reference(String identifier, String fragment) { this((fragment == null) ? identifier : identifier + '#' + fragment); } /** * Constructor of absolute reference from its parts. * * @param scheme * The scheme ("http", "https" or "ftp"). * @param hostName * The host name or IP address. * @param hostPort * The host port (default ports are correctly ignored). * @param path * The path component for hierarchical identifiers. * @param query * The optional query component for hierarchical identifiers. * @param fragment * The optional fragment identifier. */ public Reference(String scheme, String hostName, int hostPort, String path, String query, String fragment) { this(toString(scheme, hostName, hostPort, path, query, fragment)); } /** * Adds a parameter to the query component. The name and value are * automatically encoded if necessary. * * @param name * The parameter name. * @param value * The optional parameter value. * @return The updated reference. */ public Reference addQueryParameter(String name, String value) { final String query = getQuery(); if (query == null) { if (value == null) { setQuery(encode(name)); } else { setQuery(encode(name) + '=' + encode(value)); } } else { if (value == null) { setQuery(query + '&' + encode(name)); } else { setQuery(query + '&' + encode(name) + '=' + encode(value)); } } return this; } /** * Adds a segment at the end of the path. If the current path doesn't end * with a slash character, one is inserted before the new segment value. The * value is automatically encoded if necessary. * * @param value * The segment value to add. * @return The updated reference. */ public Reference addSegment(String value) { final String path = getPath(); if (value != null) { if (path == null) { setPath("/" + value); } else { if (path.endsWith("/")) { setPath(path + encode(value)); } else { setPath(path + "/" + encode(value)); } } } return this; } @Override public Reference clone() { final Reference newRef = new Reference(); if (this.baseRef == null) { newRef.baseRef = null; } else if (equals(this.baseRef)) { newRef.baseRef = newRef; } else { newRef.baseRef = this.baseRef.clone(); } newRef.fragmentIndex = this.fragmentIndex; newRef.internalRef = this.internalRef; newRef.queryIndex = this.queryIndex; newRef.schemeIndex = this.schemeIndex; return newRef; } /** * Checks if all characters are valid and encodes invalid characters if * necessary. * * @param uriRef * The URI reference to check. * @return The original reference, eventually with invalid URI characters * encoded. */ private String encodeInvalidCharacters(String uriRef) throws IllegalArgumentException { String result = uriRef; if (uriRef != null) { boolean valid = true; // Ensure that all characters are valid, otherwise encode them for (int i = 0; valid && (i < uriRef.length()); i++) { if (!isValid(uriRef.charAt(i))) { valid = false; Context.getCurrentLogger().fine( "Invalid character detected in URI reference at index '" + i + "': \"" + uriRef.charAt(i) + "\". It will be automatically encoded."); } else if ((uriRef.charAt(i) == '%') && (i > uriRef.length() - 2)) { // A percent encoding character has been detected but // without the necessary two hexadecimal digits following valid = false; Context.getCurrentLogger().fine( "Invalid percent encoding detected in URI reference at index '" + i + "': \"" + uriRef.charAt(i) + "\". It will be automatically encoded."); } } if (!valid) { StringBuilder sb = new StringBuilder(); for (int i = 0; (i < uriRef.length()); i++) { if (isValid(uriRef.charAt(i))) { if ((uriRef.charAt(i) == '%') && (i > uriRef.length() - 2)) { sb.append("%25"); } else { sb.append(uriRef.charAt(i)); } } else { sb.append(encode(String.valueOf(uriRef.charAt(i)))); } } result = sb.toString(); } } return result; } /** * Indicates whether some other object is "equal to" this one. * * @param object * The object to compare to. * @return True if this object is the same as the obj argument. */ @Override public boolean equals(Object object) { if (object instanceof Reference) { final Reference ref = (Reference) object; if (this.internalRef == null) { return ref.internalRef == null; } return this.internalRef.equals(ref.internalRef); } return false; } /** * Returns the authority component for hierarchical identifiers. Includes * the user info, host name and the host port number.
    * Note that no URI decoding is done by this method. * * @return The authority component for hierarchical identifiers. */ public String getAuthority() { final String part = isRelative() ? getRelativePart() : getSchemeSpecificPart(); if ((part != null) && part.startsWith("//")) { int index = part.indexOf('/', 2); if (index != -1) { return part.substring(2, index); } index = part.indexOf('?'); if (index != -1) { return part.substring(2, index); } return part.substring(2); } return null; } /** * Returns the optionnally decoded authority component. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded authority component. * @see #getAuthority() */ public String getAuthority(boolean decode) { return decode ? decode(getAuthority()) : getAuthority(); } /** * Returns the base reference for relative references. * * @return The base reference for relative references. */ public Reference getBaseRef() { return this.baseRef; } /** * Returns the optional extensions for hierarchical identifiers. An * extensions part starts after the first '.' character of the last path * segment and ends with either the end of the segment of with the first ';' * character (matrix start). It is a token similar to file extensions * separated by '.' characters. The value can be ommited.
    * Note that no URI decoding is done by this method. * * @return The extensions or null. * @see #getExtensionsAsArray() * @see #setExtensions(String) */ public String getExtensions() { String result = null; final String lastSegment = getLastSegment(); if (lastSegment != null) { final int extensionIndex = lastSegment.indexOf('.'); final int matrixIndex = lastSegment.indexOf(';'); if (extensionIndex != -1) { // Extensions found if (matrixIndex != -1) { result = lastSegment.substring(extensionIndex + 1, matrixIndex); } else { // No matrix found result = lastSegment.substring(extensionIndex + 1); } } } return result; } /** * Returns the extensions as an array or null if no extension is found. * * @return The extensions as an array or null if no extension is found. * @see #getExtensions() */ public String[] getExtensionsAsArray() { String[] result = null; final String extensions = getExtensions(); if (extensions != null) { result = extensions.split("\\."); } return result; } /** * Returns the fragment identifier.
    * Note that no URI decoding is done by this method. * * @return The fragment identifier. */ public String getFragment() { if (hasFragment()) { return this.internalRef.substring(this.fragmentIndex + 1); } return null; } /** * Returns the optionnally decoded fragment identifier. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded fragment identifier. * @see #getFragment() */ public String getFragment(boolean decode) { return decode ? decode(getFragment()) : getFragment(); } /** * Returns the hierarchical part which is equivalent to the scheme specific * part less the query component.
    * Note that no URI decoding is done by this method. * * @return The hierarchical part . */ public String getHierarchicalPart() { if (hasScheme()) { // Scheme found if (hasQuery()) { // Query found return this.internalRef.substring(this.schemeIndex + 1, this.queryIndex); } // No query found if (hasFragment()) { // Fragment found return this.internalRef.substring(this.schemeIndex + 1, this.fragmentIndex); } // No fragment found return this.internalRef.substring(this.schemeIndex + 1); } // No scheme found if (hasQuery()) { // Query found return this.internalRef.substring(0, this.queryIndex); } if (hasFragment()) { // Fragment found return this.internalRef.substring(0, this.fragmentIndex); } // No fragment found return this.internalRef; } /** * Returns the optionnally decoded hierarchical part. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded hierarchical part. * @see #getHierarchicalPart() */ public String getHierarchicalPart(boolean decode) { return decode ? decode(getHierarchicalPart()) : getHierarchicalPart(); } /** * Returns the host domain name component for server based hierarchical * identifiers. It can also be replaced by an IP address when no domain name * was registered.
    * Note that no URI decoding is done by this method. * * @return The host domain name component for server based hierarchical * identifiers. */ public String getHostDomain() { String result = null; final String authority = getAuthority(); if (authority != null) { final int index1 = authority.indexOf('@'); // We must prevent the case where the userinfo part contains ':' final int index2 = authority.indexOf(':', (index1 == -1 ? 0 : index1)); if (index1 != -1) { // User info found if (index2 != -1) { // Port found result = authority.substring(index1 + 1, index2); } else { // No port found result = authority.substring(index1 + 1); } } else { // No user info found if (index2 != -1) { // Port found result = authority.substring(0, index2); } else { // No port found result = authority; } } } return result; } /** * Returns the optionnally decoded host domain name component. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded host domain name component. * @see #getHostDomain() */ public String getHostDomain(boolean decode) { return decode ? decode(getHostDomain()) : getHostDomain(); } /** * Returns the host identifier. Includes the scheme, the host name and the * host port number.
    * Note that no URI decoding is done by this method. * * @return The host identifier. */ public String getHostIdentifier() { final StringBuilder result = new StringBuilder(); result.append(getScheme()).append("://").append(getAuthority()); return result.toString(); } /** * Returns the optionnally decoded host identifier. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded host identifier. * @see #getHostIdentifier() */ public String getHostIdentifier(boolean decode) { return decode ? decode(getHostIdentifier()) : getHostIdentifier(); } /** * Returns the optional port number for server based hierarchical * identifiers. * * @return The optional port number for server based hierarchical * identifiers or -1 if the port number does not exist. */ public int getHostPort() { int result = -1; final String authority = getAuthority(); if (authority != null) { final int index1 = authority.indexOf('@'); // We must prevent the case where the userinfo part contains ':' final int index = authority.indexOf(':', (index1 == -1 ? 0 : index1)); if (index != -1) { try { result = Integer.parseInt(authority.substring(index + 1)); } catch (NumberFormatException nfe) { Context.getCurrentLogger().log( Level.WARNING, "Can't parse hostPort : [hostRef,requestUri]=[" + getBaseRef() + "," + this.internalRef + "]"); } } } return result; } /** * Returns the absolute resource identifier, without the fragment.
    * Note that no URI decoding is done by this method. * * @return The absolute resource identifier, without the fragment. */ public String getIdentifier() { if (hasFragment()) { // Fragment found return this.internalRef.substring(0, this.fragmentIndex); } // No fragment found return this.internalRef; } /** * Returns the optionnally decoded absolute resource identifier. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded absolute resource identifier. * @see #getIdentifier() */ public String getIdentifier(boolean decode) { return decode ? decode(getIdentifier()) : getIdentifier(); } /** * Returns the last segment of a hierarchical path.
    * For example the "/a/b/c" and "/a/b/c/" paths have the same segments: "a", * "b", "c.
    * Note that no URI decoding is done by this method. * * @return The last segment of a hierarchical path. */ public String getLastSegment() { String result = null; String path = getPath(); if (path != null) { if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } final int lastSlash = path.lastIndexOf('/'); if (lastSlash != -1) { result = path.substring(lastSlash + 1); } } return result; } /** * Returns the optionnally decoded last segment. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded last segment. * @see #getLastSegment() */ public String getLastSegment(boolean decode) { return getLastSegment(decode, false); } /** * Returns the optionnally decoded last segment. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @param excludeMatrix * @return The optionnally decoded last segment. * @see #getLastSegment() */ public String getLastSegment(boolean decode, boolean excludeMatrix) { String result = getLastSegment(); if (excludeMatrix && (result != null)) { final int matrixIndex = result.indexOf(';'); if (matrixIndex != -1) { result = result.substring(0, matrixIndex); } } return decode ? decode(result) : result; } /** * Returns the optional matrix for hierarchical identifiers. A matrix part * starts after the first ';' character of the last path segment. It is a * sequence of 'name=value' parameters separated by ';' characters. The * value can be ommited.
    * Note that no URI decoding is done by this method. * * @return The matrix or null. */ public String getMatrix() { final String lastSegment = getLastSegment(); if (lastSegment != null) { final int matrixIndex = lastSegment.indexOf(';'); if (matrixIndex != -1) { return lastSegment.substring(matrixIndex + 1); } } // No matrix found return null; } /** * Returns the optionnally decoded matrix. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded matrix. * @see #getMatrix() */ public String getMatrix(boolean decode) { return decode ? decode(getMatrix()) : getMatrix(); } /** * Returns the optional matrix as a form. * * @return The optional matrix component as a form. */ public Form getMatrixAsForm() { return new Form(getMatrix(), ';'); } /** * Returns the optional matrix as a form submission. * * @param characterSet * The supported character encoding. * @return The optional matrix as a form. */ public Form getMatrixAsForm(CharacterSet characterSet) { return new Form(getMatrix(), characterSet, ';'); } /** * Returns the parent reference of a hierarchical reference. The last slash * of the path will be considered as the end of the parent path. * * @return The parent reference of a hierarchical reference. */ public Reference getParentRef() { Reference result = null; if (isHierarchical()) { String parentRef = null; String path = getPath(); if (!path.equals("/") && !path.equals("")) { if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } parentRef = getHostIdentifier() + path.substring(0, path.lastIndexOf('/') + 1); } else { parentRef = this.internalRef; } result = new Reference(parentRef); } return result; } /** * Returns the path component for hierarchical identifiers. If not path is * available it returns null.
    * Note that no URI decoding is done by this method. * * @return The path component for hierarchical identifiers. */ public String getPath() { String result = null; final String part = isRelative() ? getRelativePart() : getSchemeSpecificPart(); if (part != null) { if (part.startsWith("//")) { // Authority found final int index1 = part.indexOf('/', 2); if (index1 != -1) { // Path found final int index2 = part.indexOf('?'); if (index2 != -1) { // Query found result = part.substring(index1, index2); } else { // No query found result = part.substring(index1); } } else { // Path must be empty in this case } } else { // No authority found final int index = part.indexOf('?'); if (index != -1) { // Query found result = part.substring(0, index); } else { // No query found result = part; } } } return result; } /** * Returns the optionnally decoded path component. If not path is available * it returns null. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded path component. * @see #getPath() */ public String getPath(boolean decode) { return decode ? decode(getPath()) : getPath(); } /** * Returns the optional query component for hierarchical identifiers.
    * Note that no URI decoding is done by this method. * * @return The query component or null. */ public String getQuery() { if (hasQuery()) { // Query found if (hasFragment()) { if (this.queryIndex < this.fragmentIndex) { // Fragment found and query sign not inside fragment return this.internalRef.substring(this.queryIndex + 1, this.fragmentIndex); } return null; } // No fragment found return this.internalRef.substring(this.queryIndex + 1); } // No query found return null; } /** * Returns the optionnally decoded query component. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded query component. * @see #getQuery() */ public String getQuery(boolean decode) { return decode ? decode(getQuery()) : getQuery(); } /** * Returns the optional query component as a form. * * @return The optional query component as a form. */ public Form getQueryAsForm() { return new Form(getQuery()); } /** * Returns the optional query component as a form submission. * * @param characterSet * The supported character encoding. * @return The optional query component as a form submission. */ public Form getQueryAsForm(CharacterSet characterSet) { return new Form(getQuery(), characterSet); } /** * Returns the relative part of relative references, without the query and * fragment. If the reference is absolute, then null is returned.
    * Note that no URI decoding is done by this method. * * @return The relative part. */ public String getRelativePart() { return isRelative() ? toString(false, false) : null; } /** * Returns the optionnally decoded relative part. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded relative part. * @see #getRelativePart() */ public String getRelativePart(boolean decode) { return decode ? decode(getRelativePart()) : getRelativePart(); } /** * Returns the current reference as a relative reference to the current base * reference. This method should only be invoked for absolute references, * otherwise an IllegalArgumentException will be raised. * * @return The current reference as a relative reference to the current base * reference. * @see #getRelativeRef(Reference) */ public Reference getRelativeRef() { return getRelativeRef(getBaseRef()); } /** * Returns the current reference relatively to a base reference. This method * should only be invoked for absolute references, otherwise an * IllegalArgumentException will be raised. * * @param base * The base reference to use. * @throws IllegalArgumentException * If the relative reference is computed although the reference * or the base reference are not absolute or not hierarchical. * @return The current reference relatively to a base reference. */ public Reference getRelativeRef(Reference base) { Reference result = null; if (base == null) { result = this; } else if (!isAbsolute() || !isHierarchical()) { throw new IllegalArgumentException( "The reference must have an absolute hierarchical path component"); } else if (!base.isAbsolute() || !base.isHierarchical()) { throw new IllegalArgumentException( "The base reference must have an absolute hierarchical path component"); } else if (!getHostIdentifier().equals(base.getHostIdentifier())) { result = this; } else { final String localPath = getPath(); final String basePath = base.getPath(); String relativePath = null; if ((basePath == null) || (localPath == null)) { relativePath = localPath; } else { // Find the junction point boolean diffFound = false; int lastSlashIndex = -1; int i = 0; char current; while (!diffFound && (i < localPath.length()) && (i < basePath.length())) { current = localPath.charAt(i); if (current != basePath.charAt(i)) { diffFound = true; } else { if (current == '/') { lastSlashIndex = i; } i++; } } if (!diffFound) { if (localPath.length() == basePath.length()) { // Both paths are strictly equivalent relativePath = "."; } else if (i == localPath.length()) { // End of local path reached if (basePath.charAt(i) == '/') { if ((i + 1) == basePath.length()) { // Both paths are strictly equivalent relativePath = "."; } else { // The local path is a direct parent of the base // path // We need to add enough ".." in the relative // path final StringBuilder sb = new StringBuilder(); // Count segments int segments = 0; for (int j = basePath.indexOf('/', i); j != -1; j = basePath .indexOf('/', j + 1)) segments++; // Build relative path for (int j = 0; j < segments; j++) sb.append("../"); int lastLocalSlash = localPath.lastIndexOf('/'); sb.append(localPath .substring(lastLocalSlash + 1)); relativePath = sb.toString(); } } else { // The base path has a segment that starts like // the last local path segment // But that is longer. Situation similar to a // junction final StringBuilder sb = new StringBuilder(); // Count segments int segments = 0; for (int j = basePath.indexOf('/', i); j != -1; j = basePath .indexOf('/', j + 1)) segments++; // Build relative path for (int j = 0; j < segments; j++) if (j > 0) sb.append("/.."); else sb.append(".."); relativePath = sb.toString(); if (relativePath.equals("")) { relativePath = "."; } } } else if (i == basePath.length()) { if (localPath.charAt(i) == '/') { if ((i + 1) == localPath.length()) { // Both paths are strictly equivalent relativePath = "."; } else { // The local path is a direct child of the base // path relativePath = localPath.substring(i + 1); } } else { if (lastSlashIndex == (i - 1)) { // The local path is a direct subpath of the // base path relativePath = localPath.substring(i); } else { relativePath = ".." + localPath.substring(lastSlashIndex); } } } } else { // We found a junction point, we need to add enough ".." in // the relative path and append the rest of the local path // the local path is a direct subpath of the base path final StringBuilder sb = new StringBuilder(); // Count segments int segments = 0; for (int j = basePath.indexOf('/', i); j != -1; j = basePath .indexOf('/', j + 1)) segments++; // Build relative path for (int j = 0; j < segments; j++) sb.append("../"); sb.append(localPath.substring(lastSlashIndex + 1)); relativePath = sb.toString(); } } // Build the result reference result = new Reference(); final String query = getQuery(); final String fragment = getFragment(); boolean modified = false; if ((query != null) && (!query.equals(base.getQuery()))) { result.setQuery(query); modified = true; } if ((fragment != null) && (!fragment.equals(base.getFragment()))) { result.setFragment(fragment); modified = true; } if (!modified || !relativePath.equals(".")) { result.setPath(relativePath); } } return result; } /** * Returns the part of the resource identifier remaining after the base * reference. Note that the optional fragment is not returned by this * method. Must be used with the following prerequisites: *
      *
    • the reference is absolute
    • *
    • the reference identifier starts with the resource baseRef
    • *
    *
    * Note that no URI decoding is done by this method. * * @return The remaining resource part or null if the prerequisites are not * satisfied. * @see #getRemainingPart(boolean) */ public String getRemainingPart() { return getRemainingPart(false, true); } /** * Returns the optionally decoded remaining part. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionally decoded remaining part. * @see #getRemainingPart() */ public String getRemainingPart(boolean decode) { return getRemainingPart(true, true); } /** * Returns the optionally decoded remaining part with or without the query * part of the reference. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @param query * True if the query part should be returned, false otherwise. * @return The optionally decoded remaining part. * @see #getRemainingPart() */ public String getRemainingPart(boolean decode, boolean query) { String result = null; final String all = toString(query, false); if (getBaseRef() != null) { final String base = getBaseRef().toString(query, false); if ((base != null) && all.startsWith(base)) { result = all.substring(base.length()); } } else { result = all; } return decode ? decode(result) : result; } /** * Returns the scheme component.
    * Note that no URI decoding is done by this method. * * @return The scheme component. */ public String getScheme() { if (hasScheme()) { // Scheme found return this.internalRef.substring(0, this.schemeIndex); } // No scheme found return null; } /** * Returns the optionnally decoded scheme component. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded scheme component. * @see #getScheme() */ public String getScheme(boolean decode) { return decode ? decode(getScheme()) : getScheme(); } /** * Returns the protocol associated with the scheme component. * * @return The protocol associated with the scheme component. */ public Protocol getSchemeProtocol() { return Protocol.valueOf(getScheme()); } /** * Returns the scheme specific part.
    * Note that no URI decoding is done by this method. * * @return The scheme specific part. */ public String getSchemeSpecificPart() { String result = null; if (hasScheme()) { // Scheme found if (hasFragment()) { // Fragment found result = this.internalRef.substring(this.schemeIndex + 1, this.fragmentIndex); } else { // No fragment found result = this.internalRef.substring(this.schemeIndex + 1); } } return result; } /** * Returns the optionnally decoded scheme specific part. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded scheme specific part. * @see #getSchemeSpecificPart() */ public String getSchemeSpecificPart(boolean decode) { return decode ? decode(getSchemeSpecificPart()) : getSchemeSpecificPart(); } /** * Returns the list of segments in a hierarchical path.
    * A new list is created for each call.
    * Note that no URI decoding is done by this method. * * @return The segments of a hierarchical path. */ public List getSegments() { final List result = new ArrayList(); final String path = getPath(); int start = -2; // The index of the slash starting the segment char current; if (path != null) { for (int i = 0; i < path.length(); i++) { current = path.charAt(i); if (current == '/') { if (start == -2) { // Beginning of an absolute path or sequence of two // separators start = i; } else { // End of a segment result.add(path.substring(start + 1, i)); start = i; } } else { if (start == -2) { // Starting a new segment for a relative path start = -1; } else { // Looking for the next character } } } if (start != -2) { // Add the last segment result.add(path.substring(start + 1)); } } return result; } /** * Returns the optionnally decoded list of segments. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded list of segments. * @see #getSegments() */ public List getSegments(boolean decode) { final List result = getSegments(); if (decode) { for (int i = 0; i < result.size(); i++) { result.set(i, decode(result.get(i))); } } return result; } /** * Returns the target reference. This method resolves relative references * against the base reference then normalize them. * * @throws IllegalArgumentException * If the base reference (after resolution) is not absolute. * @throws IllegalArgumentException * If the reference is relative and not base reference has been * provided. * * @return The target reference. */ public Reference getTargetRef() { Reference result = null; // Step 1 - Resolve relative reference against their base reference if (isRelative() && (this.baseRef != null)) { Reference baseReference = null; if (this.baseRef.isAbsolute()) { baseReference = this.baseRef; } else { baseReference = this.baseRef.getTargetRef(); } if (baseReference.isRelative()) { throw new IllegalArgumentException( "The base reference must have an absolute hierarchical path component"); } // Relative URI detected final String authority = getAuthority(); final String path = getPath(); final String query = getQuery(); final String fragment = getFragment(); // Create an empty reference result = new Reference(); result.setScheme(baseReference.getScheme()); if (authority != null) { result.setAuthority(authority); result.setPath(path); result.setQuery(query); } else { result.setAuthority(baseReference.getAuthority()); if ((path == null) || (path.equals(""))) { result.setPath(baseReference.getPath()); if (query != null) { result.setQuery(query); } else { result.setQuery(baseReference.getQuery()); } } else { if (path.startsWith("/")) { result.setPath(path); } else { final String basePath = baseReference.getPath(); String mergedPath = null; if ((baseReference.getAuthority() != null) && ((basePath == null) || (basePath.equals("")))) { mergedPath = "/" + path; } else { // Remove the last segment which may be empty if // the path is ending with a slash final int lastSlash = basePath.lastIndexOf('/'); if (lastSlash == -1) { mergedPath = path; } else { mergedPath = basePath.substring(0, lastSlash + 1) + path; } } result.setPath(mergedPath); } result.setQuery(query); } } result.setFragment(fragment); } else if (isRelative()) { // Relative reference with no baseRef detected throw new IllegalArgumentException( "Relative references are only usable when a base reference is set."); } else { // Absolute URI detected result = new Reference(this.internalRef); } // Step 2 - Normalize the target reference result.normalize(); return result; } /** * Returns the user info component for server based hierarchical * identifiers.
    * Note that no URI decoding is done by this method. * * @return The user info component for server based hierarchical * identifiers. */ public String getUserInfo() { String result = null; final String authority = getAuthority(); if (authority != null) { final int index = authority.indexOf('@'); if (index != -1) { result = authority.substring(0, index); } } return result; } /** * Returns the optionnally decoded user info component. * * @param decode * Indicates if the result should be decoded using the * {@link #decode(String)} method. * @return The optionnally decoded user info component. * @see #getUserInfo() */ public String getUserInfo(boolean decode) { return decode ? decode(getUserInfo()) : getUserInfo(); } /** * Indicates if this reference has file-like extensions on its last path * segment. * * @return True if there is are extensions. * @see #getExtensions() */ public boolean hasExtensions() { boolean result = false; // If these reference ends with a "/", it cannot be a file. final String path = getPath(); if (!((path != null) && path.endsWith("/"))) { final String lastSegment = getLastSegment(); if (lastSegment != null) { final int extensionsIndex = lastSegment.indexOf('.'); final int matrixIndex = lastSegment.indexOf(';'); result = (extensionsIndex != -1) && ((matrixIndex == -1) || (extensionsIndex < matrixIndex)); } } return result; } /** * Indicates if this reference has a fragment identifier. * * @return True if there is a fragment identifier. */ public boolean hasFragment() { return (this.fragmentIndex != -1); } /** * Returns a hash code value for the object. * * @return A hash code value for the object. */ @Override public int hashCode() { return (this.internalRef == null) ? 0 : this.internalRef.hashCode(); } /** * Indicates if this reference has a matrix. * * @return True if there is a matrix. * @see #getMatrix() */ public boolean hasMatrix() { return (getLastSegment().indexOf(';') != -1); } /** * Indicates if this reference has a query component. * * @return True if there is a query. */ public boolean hasQuery() { return (this.queryIndex != -1); } /** * Indicates if this reference has a scheme component. * * @return True if there is a scheme component. */ public boolean hasScheme() { return (this.schemeIndex != -1); } /** * Indicates if the reference is absolute. * * @return True if the reference is absolute. */ public boolean isAbsolute() { return (getScheme() != null); } /** * Returns true if both reference are equivalent, meaning that they resolve * to the same target reference. * * @param ref * The reference to compare. * @return True if both reference are equivalent. */ public boolean isEquivalentTo(Reference ref) { return getTargetRef().equals(ref.getTargetRef()); } /** * Indicates if the identifier is hierarchical. * * @return True if the identifier is hierarchical, false if it is opaque. */ public boolean isHierarchical() { return isRelative() || (getSchemeSpecificPart().charAt(0) == '/'); } /** * Indicates if the identifier is opaque. * * @return True if the identifier is opaque, false if it is hierarchical. */ public boolean isOpaque() { return isAbsolute() && (getSchemeSpecificPart().charAt(0) != '/'); } /** * Indicates if the reference is a parent of the hierarchical child * reference. * * @param childRef * The hierarchical reference. * @return True if the reference is a parent of the hierarchical child * reference. */ public boolean isParent(Reference childRef) { boolean result = false; if ((childRef != null) && (childRef.isHierarchical())) { result = childRef.toString(false, false).startsWith( toString(false, false)); } return result; } /** * Indicates if the reference is relative. * * @return True if the reference is relative. */ public boolean isRelative() { return (getScheme() == null); } /** * Normalizes the reference. Useful before comparison between references or * when building a target reference from a base and a relative references. * * @return The current reference. */ public Reference normalize() { // 1. The input buffer is initialized with the now-appended path // components and the output buffer is initialized to the empty string. final StringBuilder output = new StringBuilder(); final StringBuilder input = new StringBuilder(); final String path = getPath(); if (path != null) { input.append(path); } // 2. While the input buffer is not empty, loop as follows: while (input.length() > 0) { // A. If the input buffer begins with a prefix of "../" or "./", // then remove that prefix from the input buffer; otherwise, if ((input.length() >= 3) && input.substring(0, 3).equals("../")) { input.delete(0, 3); } else if ((input.length() >= 2) && input.substring(0, 2).equals("./")) { input.delete(0, 2); } // B. if the input buffer begins with a prefix of "/./" or "/.", // where "." is a complete path segment, then replace that // prefix with "/" in the input buffer; otherwise, else if ((input.length() >= 3) && input.substring(0, 3).equals("/./")) { input.delete(0, 2); } else if ((input.length() == 2) && input.substring(0, 2).equals("/.")) { input.delete(1, 2); } // C. if the input buffer begins with a prefix of "/../" or "/..", // where ".." is a complete path segment, then replace that prefix // with "/" in the input buffer and remove the last segment and its // preceding "/" (if any) from the output buffer; otherwise, else if ((input.length() >= 4) && input.substring(0, 4).equals("/../")) { input.delete(0, 3); removeLastSegment(output); } else if ((input.length() == 3) && input.substring(0, 3).equals("/..")) { input.delete(1, 3); removeLastSegment(output); } // D. if the input buffer consists only of "." or "..", then remove // that from the input buffer; otherwise, else if ((input.length() == 1) && input.substring(0, 1).equals(".")) { input.delete(0, 1); } else if ((input.length() == 2) && input.substring(0, 2).equals("..")) { input.delete(0, 2); } // E. move the first path segment in the input buffer to the end of // the output buffer, including the initial "/" character (if any) // and any subsequent characters up to, but not including, the next // "/" character or the end of the input buffer. else { int max = -1; for (int i = 1; (max == -1) && (i < input.length()); i++) { if (input.charAt(i) == '/') { max = i; } } if (max != -1) { // We found the next "/" character. output.append(input.substring(0, max)); input.delete(0, max); } else { // End of input buffer reached output.append(input); input.delete(0, input.length()); } } } // Finally, the output buffer is returned as the result setPath(output.toString()); // Ensure that the scheme and host names are reset in lower case setScheme(getScheme()); setHostDomain(getHostDomain()); // Remove the port if it is equal to the default port of the reference's // Protocol. final int hostPort = getHostPort(); if (hostPort != -1) { final int defaultPort = Protocol.valueOf(getScheme()) .getDefaultPort(); if (hostPort == defaultPort) { setHostPort(null); } } return this; } /** * Removes the last segement from the output builder. * * @param output * The output builder to update. */ private void removeLastSegment(StringBuilder output) { int min = -1; for (int i = output.length() - 1; (min == -1) && (i >= 0); i--) { if (output.charAt(i) == '/') { min = i; } } if (min != -1) { // We found the previous "/" character. output.delete(min, output.length()); } else { // End of output buffer reached output.delete(0, output.length()); } } /** * Sets the authority component for hierarchical identifiers. * * @param authority * The authority component for hierarchical identifiers. */ public void setAuthority(String authority) { final String oldPart = isRelative() ? getRelativePart() : getSchemeSpecificPart(); String newPart; final String newAuthority = (authority == null) ? "" : "//" + authority; if (oldPart == null) { newPart = newAuthority; } else if (oldPart.startsWith("//")) { int index = oldPart.indexOf('/', 2); if (index != -1) { newPart = newAuthority + oldPart.substring(index); } else { index = oldPart.indexOf('?'); if (index != -1) { newPart = newAuthority + oldPart.substring(index); } else { newPart = newAuthority; } } } else { newPart = newAuthority + oldPart; } if (isAbsolute()) { setSchemeSpecificPart(newPart); } else { setRelativePart(newPart); } } /** * Sets the base reference for relative references. * * @param baseRef * The base reference for relative references. */ public void setBaseRef(Reference baseRef) { this.baseRef = baseRef; } /** * Sets the base reference for relative references. * * @param baseUri * The base URI for relative references. */ public void setBaseRef(String baseUri) { setBaseRef(new Reference(baseUri)); } /** * Sets the extensions for hierarchical identifiers. An extensions part * starts after the first '.' character of the last path segment and ends * with either the end of the segment of with the first ';' character * (matrix start). It is a token similar to file extensions separated by '.' * characters. The value can be ommited.
    * Note that no URI decoding is done by this method. * * @param extensions * The extensions to set or null (without leading or trailing * dots). * @see #getExtensions() * @see #getExtensionsAsArray() * @see #setExtensions(String[]) */ public void setExtensions(String extensions) { final String lastSegment = getLastSegment(); if (lastSegment != null) { final int extensionIndex = lastSegment.indexOf('.'); final int matrixIndex = lastSegment.indexOf(';'); final StringBuilder sb = new StringBuilder(); if (extensionIndex != -1) { // Extensions found sb.append(lastSegment.substring(0, extensionIndex)); if ((extensions != null) && (extensions.length() > 0)) { sb.append('.').append(extensions); } if (matrixIndex != -1) { sb.append(lastSegment.substring(matrixIndex)); } } else { // Extensions not found if ((extensions != null) && (extensions.length() > 0)) { if (matrixIndex != -1) { // Matrix found, make sure we append it // after the extensions sb.append(lastSegment.substring(0, matrixIndex)) .append('.').append(extensions) .append(lastSegment.substring(matrixIndex)); } else { // No matrix found, just append the extensions sb.append(lastSegment).append('.').append(extensions); } } else { // No change necessary sb.append(lastSegment); } } // Finally update the last segment setLastSegment(sb.toString()); } else { setLastSegment('.' + extensions); } } /** * Sets the extensions based on an array of extension tokens (without dots). * * @param extensions * The array of extensions. * @see #getExtensions() * @see #getExtensionsAsArray() * @see #setExtensions(String) */ public void setExtensions(String[] extensions) { String exts = null; if (extensions != null) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < extensions.length; i++) { if (i > 0) { sb.append('.'); } sb.append(extensions[i]); } exts = sb.toString(); } setExtensions(exts); } /** * Sets the fragment identifier. * * @param fragment * The fragment identifier. * @throws IllegalArgumentException * if the fragment parameter contains the fragment delimiter * ('#'). */ public void setFragment(String fragment) { fragment = encodeInvalidCharacters(fragment); if ((fragment != null) && (fragment.indexOf('#') != -1)) { throw new IllegalArgumentException( "Illegal '#' character detected in parameter"); } if (hasFragment()) { // Existing fragment if (fragment != null) { this.internalRef = this.internalRef.substring(0, this.fragmentIndex + 1) + fragment; } else { this.internalRef = this.internalRef.substring(0, this.fragmentIndex); } } else { // No existing fragment if (fragment != null) { if (this.internalRef != null) { this.internalRef = this.internalRef + '#' + fragment; } else { this.internalRef = '#' + fragment; } } else { // Do nothing } } updateIndexes(); } /** * Sets the host domain component for server based hierarchical identifiers. * * @param domain * The host component for server based hierarchical identifiers. */ public void setHostDomain(String domain) { final String authority = getAuthority(); if (authority == null) { setAuthority(domain); } else { if (domain == null) { domain = ""; } else { // URI specification indicates that host names should be // produced in lower case domain = domain.toLowerCase(); } final int index1 = authority.indexOf('@'); // We must prevent the case where the userinfo part contains ':' final int index2 = authority.indexOf(':', (index1 == -1 ? 0 : index1)); if (index1 != -1) { // User info found if (index2 != -1) { // Port found setAuthority(authority.substring(0, index1 + 1) + domain + authority.substring(index2)); } else { // No port found setAuthority(authority.substring(0, index1 + 1) + domain); } } else { // No user info found if (index2 != -1) { // Port found setAuthority(domain + authority.substring(index2)); } else { // No port found setAuthority(domain); } } } } /** * Sets the optional port number for server based hierarchical identifiers. * * @param port * The optional port number for server based hierarchical * identifiers. * @throws IllegalArgumentException * If the autority has not been defined. */ public void setHostPort(Integer port) { final String authority = getAuthority(); if (authority != null) { final int index1 = authority.indexOf('@'); // We must prevent the case where the userinfo part contains ':' final int index = authority.indexOf(':', (index1 == -1 ? 0 : index1)); final String newPort = (port == null) ? "" : ":" + port; if (index != -1) { setAuthority(authority.substring(0, index) + newPort); } else { setAuthority(authority + newPort); } } else { throw new IllegalArgumentException( "No authority defined, please define a host name first"); } } /** * Sets the absolute resource identifier. * * @param identifier * The absolute resource identifier. * @throws IllegalArgumentException * If the identifier parameter contains the fragment delimiter * ('#'). */ public void setIdentifier(String identifier) { identifier = encodeInvalidCharacters(identifier); if (identifier == null) { identifier = ""; } if (identifier.indexOf('#') != -1) { throw new IllegalArgumentException( "Illegal '#' character detected in parameter"); } if (hasFragment()) { // Fragment found this.internalRef = identifier + this.internalRef.substring(this.fragmentIndex); } else { // No fragment found this.internalRef = identifier; } updateIndexes(); } /** * Sets the last segment of the path. If no path is available, then it * creates one and adds a slash in front of the given last segmetn.
    * Note that no URI decoding is done by this method. * * @param lastSegment * The last segment of a hierarchical path. */ public void setLastSegment(String lastSegment) { String path = getPath(); int lastSlashIndex = -1; if (path != null) { lastSlashIndex = path.lastIndexOf('/'); } if (lastSlashIndex != -1) { setPath(path.substring(0, lastSlashIndex + 1) + lastSegment); } else { setPath('/' + lastSegment); } } /** * Sets the path component for hierarchical identifiers. * * @param path * The path component for hierarchical identifiers. */ public void setPath(String path) { final String oldPart = isRelative() ? getRelativePart() : getSchemeSpecificPart(); String newPart = null; if (oldPart != null) { if (path == null) { path = ""; } if (oldPart.startsWith("//")) { // Authority found final int index1 = oldPart.indexOf('/', 2); if (index1 != -1) { // Path found final int index2 = oldPart.indexOf('?'); if (index2 != -1) { // Query found newPart = oldPart.substring(0, index1) + path + oldPart.substring(index2); } else { // No query found newPart = oldPart.substring(0, index1) + path; } } else { // No path found final int index2 = oldPart.indexOf('?'); if (index2 != -1) { // Query found newPart = oldPart.substring(0, index2) + path + oldPart.substring(index2); } else { // No query found newPart = oldPart + path; } } } else { // No authority found final int index = oldPart.indexOf('?'); if (index != -1) { // Query found newPart = path + oldPart.substring(index); } else { // No query found newPart = path; } } } else { newPart = path; } if (isAbsolute()) { setSchemeSpecificPart(newPart); } else { setRelativePart(newPart); } } /** * Sets the scheme component based on this protocol. * * @param protocol * The protocol of the scheme component. */ public void setProtocol(Protocol protocol) { setScheme(protocol.getSchemeName()); } /** * Sets the query component for hierarchical identifiers. * * @param query * The query component for hierarchical identifiers. */ public void setQuery(String query) { query = encodeInvalidCharacters(query); final boolean emptyQueryString = ((query == null) || (query.length() <= 0)); if (hasQuery()) { // Query found if (hasFragment()) { // Fragment found if (!emptyQueryString) { this.internalRef = this.internalRef.substring(0, this.queryIndex + 1) + query + this.internalRef.substring(this.fragmentIndex); } else { this.internalRef = this.internalRef.substring(0, this.queryIndex) + this.internalRef.substring(this.fragmentIndex); } } else { // No fragment found if (!emptyQueryString) { this.internalRef = this.internalRef.substring(0, this.queryIndex + 1) + query; } else { this.internalRef = this.internalRef.substring(0, this.queryIndex); } } } else { // No query found if (hasFragment()) { // Fragment found if (!emptyQueryString) { this.internalRef = this.internalRef.substring(0, this.fragmentIndex) + '?' + query + this.internalRef.substring(this.fragmentIndex); } else { // Do nothing; } } else { // No fragment found if (!emptyQueryString) { if (this.internalRef != null) { this.internalRef = this.internalRef + '?' + query; } else { this.internalRef = '?' + query; } } else { // Do nothing; } } } updateIndexes(); } /** * Sets the relative part for relative references only. * * @param relativePart * The relative part to set. */ public void setRelativePart(String relativePart) { relativePart = encodeInvalidCharacters(relativePart); if (relativePart == null) { relativePart = ""; } if (!hasScheme()) { // This is a relative reference, no scheme found if (hasQuery()) { // Query found this.internalRef = relativePart + this.internalRef.substring(this.queryIndex); } else if (hasFragment()) { // Fragment found this.internalRef = relativePart + this.internalRef.substring(this.fragmentIndex); } else { // No fragment found this.internalRef = relativePart; } } updateIndexes(); } /** * Sets the scheme component. * * @param scheme * The scheme component. */ public void setScheme(String scheme) { scheme = encodeInvalidCharacters(scheme); if (scheme != null) { // URI specification indicates that scheme names should be // produced in lower case scheme = scheme.toLowerCase(); } if (hasScheme()) { // Scheme found if (scheme != null) { this.internalRef = scheme + this.internalRef.substring(this.schemeIndex); } else { this.internalRef = this.internalRef .substring(this.schemeIndex + 1); } } else { // No scheme found if (scheme != null) { if (this.internalRef == null) { this.internalRef = scheme + ':'; } else { this.internalRef = scheme + ':' + this.internalRef; } } } updateIndexes(); } /** * Sets the scheme specific part. * * @param schemeSpecificPart * The scheme specific part. */ public void setSchemeSpecificPart(String schemeSpecificPart) { schemeSpecificPart = encodeInvalidCharacters(schemeSpecificPart); if (schemeSpecificPart == null) { schemeSpecificPart = ""; } if (hasScheme()) { // Scheme found if (hasFragment()) { // Fragment found this.internalRef = this.internalRef.substring(0, this.schemeIndex + 1) + schemeSpecificPart + this.internalRef.substring(this.fragmentIndex); } else { // No fragment found this.internalRef = this.internalRef.substring(0, this.schemeIndex + 1) + schemeSpecificPart; } } else { // No scheme found if (hasFragment()) { // Fragment found this.internalRef = schemeSpecificPart + this.internalRef.substring(this.fragmentIndex); } else { // No fragment found this.internalRef = schemeSpecificPart; } } updateIndexes(); } /** * Sets the segments of a hierarchical path.
    * A new absolute path will replace any existing one. * * @param segments * The segments of the hierarchical path. */ public void setSegments(List segments) { final StringBuilder sb = new StringBuilder(); for (final String segment : segments) { sb.append('/').append(segment); } setPath(sb.toString()); } /** * Sets the user info component for server based hierarchical identifiers. * * @param userInfo * The user info component for server based hierarchical * identifiers. * @throws IllegalArgumentException * If the autority part has not been defined. */ public void setUserInfo(String userInfo) { final String authority = getAuthority(); if (authority != null) { final int index = authority.indexOf('@'); final String newUserInfo = (userInfo == null) ? "" : userInfo + '@'; if (index != -1) { setAuthority(newUserInfo + authority.substring(index + 1)); } else { setAuthority(newUserInfo + authority); } } else { throw new IllegalArgumentException( "No authority defined, please define a host name first"); } } /** * Returns the reference as an URI string. * * @return The reference as an URI string. */ @Override public String toString() { return this.internalRef; } /** * Returns the URI reference string. * * @param query * Indicates if the query should be included; * @param fragment * Indicates if the fragment should be included; * @return The URI reference string. */ public String toString(boolean query, boolean fragment) { if (query) { if (fragment) { return this.internalRef; } if (hasFragment()) { return this.internalRef.substring(0, this.fragmentIndex); } return this.internalRef; } if (fragment) { // Fragment should be included if (hasQuery()) { // Query found if (hasFragment()) { // Fragment found return this.internalRef.substring(0, this.queryIndex) + "#" + getFragment(); } // No fragment found return this.internalRef.substring(0, this.queryIndex); } // No query found return this.internalRef; } // Fragment should not be included if (hasQuery()) { // Query found return this.internalRef.substring(0, this.queryIndex); } if (hasFragment()) { // Fragment found return this.internalRef.substring(0, this.fragmentIndex); } return this.internalRef; } /** * Converts to a {@link java.net.URI} instance. Note that relative * references are resolved before conversion using the * {@link #getTargetRef()} method. * * @return A {@link java.net.URI} instance. */ public java.net.URI toUri() { return java.net.URI.create(getTargetRef().toString()); } /** * Converts to a {@link java.net.URL} instance. Note that relative * references are resolved before conversion using the * {@link #getTargetRef()} method. * * @return A {@link java.net.URL} instance. */ public java.net.URL toUrl() { java.net.URL result = null; try { result = new java.net.URL(getTargetRef().toString()); } catch (java.net.MalformedURLException e) { throw new IllegalArgumentException("Malformed URL exception", e); } return result; } /** * Updates internal indexes. */ private void updateIndexes() { if (this.internalRef != null) { // Compute the indexes final int firstSlashIndex = this.internalRef.indexOf('/'); this.schemeIndex = this.internalRef.indexOf(':'); if ((firstSlashIndex != -1) && (this.schemeIndex > firstSlashIndex)) { // We are in the rare case of a relative reference where one of // the path segments contains a colon character. In this case, // we ignore the colon as a valid scheme index. // Note that this colon can't be in the first segment as it is // forbidden by the URI RFC. this.schemeIndex = -1; } this.queryIndex = this.internalRef.indexOf('?'); this.fragmentIndex = this.internalRef.indexOf('#'); if (hasQuery() && hasFragment() && (this.queryIndex > this.fragmentIndex)) { // Query sign inside fragment this.queryIndex = -1; } if (hasQuery() && this.schemeIndex > this.queryIndex) { // Colon sign inside query this.schemeIndex = -1; } if (hasFragment() && this.schemeIndex > this.fragmentIndex) { // Colon sign inside fragment this.schemeIndex = -1; } } else { this.schemeIndex = -1; this.queryIndex = -1; this.fragmentIndex = -1; } } } restlet-2.0.14/org.restlet/src/org/restlet/data/RecipientInfo.java0000664000175000017500000000726011757206346025576 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; /** * Describes an intermediary via which the call went through. The intermediary * is typically a proxy or a cache.
    *
    * Note that when used with HTTP connectors, this class maps to the "Via" * header. * * @author Jerome Louvel */ public class RecipientInfo { /** The protocol used to communicate with the recipient. */ private volatile Protocol protocol; /** The optional comment, typically the software agent name. */ private volatile String comment; /** The host name and port number or a pseudonym. */ private volatile String name; /** * Default constructor. */ public RecipientInfo() { } /** * Constructor. * * @param protocol * The protocol used to communicate with the recipient. * @param name * The host name and port number or a pseudonym. * @param agent * The software agent. */ public RecipientInfo(Protocol protocol, String name, String agent) { this.protocol = protocol; this.name = name; this.comment = agent; } /** * Returns the optional comment, typically the software agent name. * * @return The optional comment. */ public String getComment() { return comment; } /** * Returns the host name and port number or a pseudonym. * * @return The host name and port number or a pseudonym. */ public String getName() { return name; } /** * Returns the protocol used to communicate with the recipient. * * @return The protocol used to communicate with the recipient. */ public Protocol getProtocol() { return protocol; } /** * Sets the optional comment, typically the software agent name. * * @param comment * The optional comment. */ public void setComment(String comment) { this.comment = comment; } /** * Sets the host name and port number or a pseudonym. * * @param name * The host name and port number or a pseudonym. */ public void setName(String name) { this.name = name; } /** * Sets the protocol used to communicate with the recipient. * * @param protocol * The protocol used to communicate with the recipient. */ public void setProtocol(Protocol protocol) { this.protocol = protocol; } } restlet-2.0.14/org.restlet/src/org/restlet/data/Parameter.java0000664000175000017500000001077711757206346024767 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.io.IOException; import org.restlet.util.Couple; /** * Multi-usage parameter. Note that the name and value properties are thread * safe, stored in volatile members. * * @author Jerome Louvel */ public class Parameter extends Couple implements Comparable { /** * Default constructor. */ public Parameter() { this(null, null); } /** * Creates a parameter. * * @param name * The parameter name buffer. * @param value * The parameter value buffer (can be null). * @return The created parameter. * @throws IOException */ public static Parameter create(CharSequence name, CharSequence value) { if (value != null) { return new Parameter(name.toString(), value.toString()); } return new Parameter(name.toString(), null); } /** * Preferred constructor. * * @param name * The name. * @param value * The value. */ public Parameter(String name, String value) { super(name, value); } /** * Compares this object with the specified object for order. * * @param o * The object to be compared. * @return A negative integer, zero, or a positive integer as this object is * less than, equal to, or greater than the specified object. */ public int compareTo(Parameter o) { return getName().compareTo(o.getName()); } /** * Encodes the parameter and appends the result to the given buffer. Uses * the standard URI encoding mechanism. * * @param buffer * The buffer to append. * @param characterSet * The supported character encoding * @throws IOException */ public void encode(Appendable buffer, CharacterSet characterSet) throws IOException { if (getName() != null) { buffer.append(Reference.encode(getName(), characterSet)); if (getValue() != null) { buffer.append('='); buffer.append(Reference.encode(getValue(), characterSet)); } } } /** * Encodes the parameter using the standard URI encoding mechanism. * * @param characterSet * The supported character encoding. * @return The encoded string. * @throws IOException */ public String encode(CharacterSet characterSet) throws IOException { final StringBuilder sb = new StringBuilder(); encode(sb, characterSet); return sb.toString(); } /** * Returns the name of this parameter. * * @return The name of this parameter. */ public String getName() { return getFirst(); } /** * Returns the value. * * @return The value. */ public String getValue() { return getSecond(); } /** * Sets the name. * * @param name * The name. */ public void setName(String name) { setFirst(name); } /** * Sets the value. * * @param value * The value. */ public void setValue(String value) { setSecond(value); } } restlet-2.0.14/org.restlet/src/org/restlet/data/Dimension.java0000664000175000017500000000325011757206346024760 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.Response; /** * Dimension on which the representations of a resource may vary. Note that when * used with HTTP connectors, this class maps to the "Vary" header. * * @see Response#getDimensions() * @author Jerome Louvel * @author Piyush Purang (ppurang@gmail.com) */ public enum Dimension { AUTHORIZATION, CHARACTER_SET, CLIENT_ADDRESS, CLIENT_AGENT, UNSPECIFIED, ENCODING, LANGUAGE, MEDIA_TYPE, TIME, } restlet-2.0.14/org.restlet/src/org/restlet/data/Cookie.java0000664000175000017500000001407611757206346024254 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.Request; import org.restlet.engine.util.SystemUtils; /** * Cookie provided by a client. To get the list of all cookies sent by a client, * you can use the {@link Request#getCookies()} method.
    *
    * Note that if you are on the server side and want to set a cookie on the * client, you should use the {@link CookieSetting} class instead.
    *
    * Note that when used with HTTP connectors, this class maps to the "Cookie" * header. * * @see Request#getCookies() * @see User * Guide - Getting parameter values * @author Jerome Louvel */ public class Cookie extends Parameter { /** The domain name. */ private volatile String domain; /** The validity path. */ private volatile String path; /** The version number. */ private volatile int version; /** * Constructor. */ public Cookie() { this(0, null, null, null, null); } /** * Constructor. * * @param version * The version number. * @param name * The name. * @param value * The value. */ public Cookie(int version, String name, String value) { this(version, name, value, null, null); } /** * Constructor. * * @param version * The version number. * @param name * The name. * @param value * The value. * @param path * The validity path. * @param domain * The domain name. */ public Cookie(int version, String name, String value, String path, String domain) { super(name, value); this.version = version; this.path = path; this.domain = domain; } /** * Constructor. * * @param name * The name. * @param value * The value. */ public Cookie(String name, String value) { this(0, name, value, null, null); } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { boolean result = (obj == this); // if obj == this no need to go further if (!result) { // test for equality at Parameter level i.e. name and value. if (super.equals(obj)) { // if obj isn't a cookie or is null don't evaluate further if (obj instanceof Cookie) { final Cookie that = (Cookie) obj; result = (this.version == that.version); if (result) // if versions are equal test domains { if (!(this.domain == null)) // compare domains // taking care of nulls { result = (this.domain.equals(that.domain)); } else { result = (that.domain == null); } if (result) // if domains are equal test the paths { if (!(this.path == null)) // compare paths taking // care of nulls { result = (this.path.equals(that.path)); } else { result = (that.path == null); } } } } } } return result; } /** * Returns the domain name. * * @return The domain name. */ public String getDomain() { return this.domain; } /** * Returns the validity path. * * @return The validity path. */ public String getPath() { return this.path; } /** * Returns the cookie specification version. * * @return The cookie specification version. */ public int getVersion() { return this.version; } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(super.hashCode(), getVersion(), getPath(), getDomain()); } /** * Sets the domain name. * * @param domain * The domain name. */ public void setDomain(String domain) { this.domain = domain; } /** * Sets the validity path. * * @param path * The validity path. */ public void setPath(String path) { this.path = path; } /** * Sets the cookie specification version. * * @param version * The cookie specification version. */ public void setVersion(int version) { this.version = version; } } restlet-2.0.14/org.restlet/src/org/restlet/data/ClientInfo.java0000664000175000017500000010640711757206346025075 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Context; import org.restlet.engine.Engine; import org.restlet.engine.io.IoUtils; import org.restlet.representation.Variant; /** * Client specific data related to a call. When extracted from a request, most * of these data are directly taken from the underlying headers. There are some * exceptions: agentAttributes and mainAgentProduct which are taken from the * agent name (for example the "user-agent" header for HTTP requests).
    *
    * As described by the HTTP specification, the "user-agent" can be seen as a * ordered list of products name (ie a name and a version) and/or comments.
    *
    * Each HTTP client (mainly browsers and web crawlers) defines its own * "user-agent" header which can be seen as the "signature" of the client. * Unfortunately, there is no rule to identify clearly a kind a client and its * version (let's say firefox 2.x, Internet Explorer IE 7.0, Opera, etc) * according to its signature. Each signature follow its own rules which may * vary according to the version of the client.
    *
    * In order to help retrieving interesting data such as product name (Firefox, * IE, etc), version, operating system, Restlet users has the ability to define * their own way to extract data from the "user-agent" header. It is based on a * list of templates declared in a file called "agent.properties" and located in * the classpath in the sub directory "org/restlet/data". Each template * describes a typical user-agent string and allows to use predefined variables * that help to retrieve the content of the agent name, version, operating * system.
    *
    * The "user-agent" string is confronted to the each template from the beginning * of the property file to the end. The loop stops at the first matched * template.
    *
    * Here is a sample of such template:
    * *
     * #Firefox for Windows
     *  Mozilla/{mozillaVersion} (Windows; U; {agentOs}; {osData}; rv:{releaseVersion}) Gecko/{geckoReleaseDate} {agentName}/{agentVersion}
     * 
    * * This template matches the "user-agent" string of the Firefox client for * windows: * *
     *  Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20060918 Firefox/2.0
     * 
    * * At this time, six predefined variables are used:
    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    NameDescription
    agentNameName of the user agent (i.e.: Firefox)
    agentVersionVersion of the user agent
    agentOsOperating system of the user agent
    agentCommentComment string, that is to say a sequence of characters enclosed "(", or * ")"
    commentAttributeA sequence of characters enclosed by ";", "(", or ")"
    facultativeDataA sequence of characters that can be empty
    *
    *
    * These variables are used to generate a {@link Product} instance with the main * data (name, version, comment). This instance is accessible via the * {@link ClientInfo#getMainAgentProduct()} method. All other variables used in * the template aims at catching a sequence of characters and are accessible via * the {@link ClientInfo#getAgentAttributes()} method. * * @author Jerome Louvel */ public final class ClientInfo { /** * List of user-agent templates defined in "agent.properties" file.
    * * @see The {@link ClientInfo#getAgentAttributes()} method. */ private static volatile List userAgentTemplates = null; /** * Returns the list of user-agent templates defined in "agent.properties" * file. * * @return The list of user-agent templates defined in "agent.properties" * file. * @see The {@link ClientInfo#getAgentAttributes()} method. */ private static List getUserAgentTemplates() { // Lazy initialization with double-check. List u = ClientInfo.userAgentTemplates; if (u == null) { synchronized (ClientInfo.class) { u = ClientInfo.userAgentTemplates; if (u == null) { // Load from the "agent.properties" file final java.net.URL userAgentPropertiesUrl = Engine .getResource("org/restlet/data/agent.properties"); if (userAgentPropertiesUrl != null) { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader( userAgentPropertiesUrl.openStream(), CharacterSet.UTF_8.getName()), IoUtils .getBufferSize()); String line = reader.readLine(); for (; line != null; line = reader.readLine()) { if ((line.trim().length() > 0) && !line.trim().startsWith("#")) { if (u == null) { u = new CopyOnWriteArrayList(); } u.add(line); } } reader.close(); } catch (IOException e) { if (Context.getCurrent() != null) { Context .getCurrent() .getLogger() .warning( "Cannot read '" + userAgentPropertiesUrl .toString() + "' due to: " + e.getMessage()); } } } ClientInfo.userAgentTemplates = u; } } } return u; } /** The character set preferences. */ private volatile List> acceptedCharacterSets; /** The encoding preferences. */ private volatile List> acceptedEncodings; /** The language preferences. */ private volatile List> acceptedLanguages; /** The media preferences. */ private volatile List> acceptedMediaTypes; /** The immediate IP addresses. */ private volatile String address; /** The email address of the human user controlling the user agent. */ private volatile String from; /** The agent name. */ private volatile String agent; /** The attributes data taken from the agent name. */ private volatile Map agentAttributes; /** The main product data taken from the agent name. */ private volatile Product agentMainProduct; /** The list of product tokens taken from the agent name. */ private volatile List agentProducts; /** * Indicates if the subject has been authenticated. The application is * responsible for updating this property, relying on * {@link org.restlet.security.Authenticator} or manually. */ private volatile boolean authenticated; /** The forwarded IP addresses. */ private volatile List forwardedAddresses; /** The port number. */ private volatile int port; /** List of additional client principals. */ private volatile List principals; /** Authenticated user. */ private volatile org.restlet.security.User user; /** List of user roles. */ private volatile List roles; /** List of expectations. */ private volatile List expectations; /** * Constructor. */ public ClientInfo() { this.address = null; this.agent = null; this.port = -1; this.acceptedCharacterSets = null; this.acceptedEncodings = null; this.acceptedLanguages = null; this.acceptedMediaTypes = null; this.forwardedAddresses = null; this.from = null; this.agentProducts = null; this.principals = null; this.user = null; this.roles = null; this.expectations = null; } /** * Constructor from a list of variants. Note that only media types are taken * into account. * * @param variants * The variants corresponding to the accepted media types. */ public ClientInfo( List variants) { if (variants != null) { for (org.restlet.representation.Variant variant : variants) { getAcceptedMediaTypes().add( new Preference(variant.getMediaType())); } } } /** * Constructor from a media type. * * @param mediaType * The preferred media type. */ public ClientInfo(MediaType mediaType) { getAcceptedMediaTypes().add(new Preference(mediaType)); } /** * Returns the modifiable list of character set preferences. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Accept-Charset" header. * * @return The character set preferences. */ public List> getAcceptedCharacterSets() { // Lazy initialization with double-check. List> a = this.acceptedCharacterSets; if (a == null) { synchronized (this) { a = this.acceptedCharacterSets; if (a == null) { this.acceptedCharacterSets = a = new CopyOnWriteArrayList>(); } } } return a; } /** * Returns the modifiable list of encoding preferences. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Accept-Encoding" header. * * @return The encoding preferences. */ public List> getAcceptedEncodings() { // Lazy initialization with double-check. List> a = this.acceptedEncodings; if (a == null) { synchronized (this) { a = this.acceptedEncodings; if (a == null) { this.acceptedEncodings = a = new CopyOnWriteArrayList>(); } } } return a; } /** * Returns the modifiable list of language preferences. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Accept-Language" header. * * @return The language preferences. */ public List> getAcceptedLanguages() { // Lazy initialization with double-check. List> a = this.acceptedLanguages; if (a == null) { synchronized (this) { a = this.acceptedLanguages; if (a == null) { this.acceptedLanguages = a = new CopyOnWriteArrayList>(); } } } return a; } /** * Returns the modifiable list of media type preferences. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Accept" header. * * @return The media type preferences. */ public List> getAcceptedMediaTypes() { // Lazy initialization with double-check. List> a = this.acceptedMediaTypes; if (a == null) { synchronized (this) { a = this.acceptedMediaTypes; if (a == null) { this.acceptedMediaTypes = a = new CopyOnWriteArrayList>(); } } } return a; } /** * Returns the immediate client's IP address. If the real client is * separated from the server by a proxy server, this will return the IP * address of the proxy. * * @return The immediate client's IP address. * @see #getUpstreamAddress() * @see #getForwardedAddresses() */ public String getAddress() { return this.address; } /** * Returns the list of client IP addresses. The first address is the one of * the immediate client component as returned by the getClientAdress() * method and the last address should correspond to the origin client * (frequently a user agent).
    *
    * This is useful when the user agent is separated from the origin server by * a chain of intermediary components. Creates a new instance if no one has * been set. * * @return The client IP addresses. * @deprecated Use the {@link #getForwardedAddresses()} method instead. */ @Deprecated public List getAddresses() { return getForwardedAddresses(); } /** * Returns the agent name (ex: "Restlet-Framework/2.0"). Note that when used * with HTTP connectors, this property maps to the "User-Agent" header. * * @return The agent name. */ public String getAgent() { return this.agent; } /** * Returns a list of attributes taken from the name of the user agent. * * @return A list of attributes taken from the name of the user agent. * @see #getAgent() */ public Map getAgentAttributes() { if (this.agentAttributes == null) { this.agentAttributes = new ConcurrentHashMap(); Map map = new ConcurrentHashMap(); // Loop on a list of user-agent templates until a template match // the current user-agent string. The list of templates is // located in a file named "agent.properties" available on // the classpath. // Some defined variables are used in order to catch the name, // version and optional comment. Respectively, these // variables are called "agentName", "agentVersion" and // "agentComment". org.restlet.routing.Template template = null; // Predefined variables. org.restlet.routing.Variable agentName = new org.restlet.routing.Variable( org.restlet.routing.Variable.TYPE_TOKEN); org.restlet.routing.Variable agentVersion = new org.restlet.routing.Variable( org.restlet.routing.Variable.TYPE_TOKEN); org.restlet.routing.Variable agentComment = new org.restlet.routing.Variable( org.restlet.routing.Variable.TYPE_COMMENT); org.restlet.routing.Variable agentCommentAttribute = new org.restlet.routing.Variable( org.restlet.routing.Variable.TYPE_COMMENT_ATTRIBUTE); org.restlet.routing.Variable facultativeData = new org.restlet.routing.Variable( org.restlet.routing.Variable.TYPE_ALL, null, false, false); for (String string : ClientInfo.getUserAgentTemplates()) { template = new org.restlet.routing.Template(string, org.restlet.routing.Template.MODE_EQUALS); // Update the predefined variables. template.getVariables().put("agentName", agentName); template.getVariables().put("agentVersion", agentVersion); template.getVariables().put("agentComment", agentComment); template.getVariables().put("agentOs", agentCommentAttribute); template.getVariables().put("commentAttribute", agentCommentAttribute); template.getVariables().put("facultativeData", facultativeData); // Parse the template if (template.parse(getAgent(), map) > -1) { for (String key : map.keySet()) { this.agentAttributes.put(key, (String) map.get(key)); } break; } } } return this.agentAttributes; } /** * Returns the name of the user agent. * * @return The name of the user agent. * @see #getAgent() */ public String getAgentName() { final Product product = getMainAgentProduct(); if (product != null) { return product.getName(); } return null; } /** * Returns the list of product tokens from the user agent name. * * @return The list of product tokens from the user agent name. * @see #getAgent() */ public List getAgentProducts() { if (this.agentProducts == null) { this.agentProducts = org.restlet.engine.http.header.ProductReader .read(getAgent()); } return this.agentProducts; } /** * Returns the version of the user agent. * * @return The version of the user agent. * @see #getAgent() */ public String getAgentVersion() { final Product product = getMainAgentProduct(); if (product != null) { return product.getVersion(); } return null; } /** * Returns the client expectations. * * @return The client expectations. */ public List getExpectations() { // Lazy initialization with double-check. List a = this.expectations; if (a == null) { synchronized (this) { a = this.expectations; if (a == null) { this.expectations = a = new CopyOnWriteArrayList(); } } } return a; } /** * Returns the list of forwarded IP addresses. This is useful when the user * agent is separated from the origin server by a chain of intermediary * components. Creates a new instance if no one has been set.
    *
    * The first address is the one of the immediate client component and the * last address should correspond to the origin client (frequently a user * agent).
    *
    * This information is only safe for intermediary components within your * local network. Other addresses could easily be changed by setting a fake * header and should not be trusted for serious security checks.
    *
    * Note that your HTTP server connectors need to have a special * "useForwardedForHeader" parameter explicitly set to "true" in order to * activate this feature, due to potential security issues. * * @return The list of forwarded IP addresses. * @see #getUpstreamAddress() * @see Wikipedia * page for the "X-Forwarded-For" HTTP header */ public List getForwardedAddresses() { // Lazy initialization with double-check. List a = this.forwardedAddresses; if (a == null) { synchronized (this) { a = this.forwardedAddresses; if (a == null) { this.forwardedAddresses = a = new CopyOnWriteArrayList(); } } } return a; } /** * Returns the email address of the human user controlling the user agent. * Default value is null. * * @return The email address of the human user controlling the user agent. */ public String getFrom() { return from; } /** * Returns a Product object based on the name of the user agent. * * @return A Product object based on name of the user agent. */ public Product getMainAgentProduct() { if (this.agentMainProduct == null) { if (getAgentAttributes() != null) { this.agentMainProduct = new Product(getAgentAttributes().get( "agentName"), getAgentAttributes().get("agentVersion"), getAgentAttributes().get("agentComment")); } } return this.agentMainProduct; } /** * Returns the port number which sent the call. If no port is specified, -1 * is returned. * * @return The port number which sent the call. */ public int getPort() { return this.port; } /** * Returns the preferred character set among a list of supported ones, based * on the client preferences. * * @param supported * The supported character sets. * @return The preferred character set. */ public CharacterSet getPreferredCharacterSet(List supported) { return org.restlet.engine.util.ConnegUtils.getPreferredMetadata( supported, getAcceptedCharacterSets()); } /** * Returns the preferred encoding among a list of supported ones, based on * the client preferences. * * @param supported * The supported encodings. * @return The preferred encoding. */ public Encoding getPreferredEncoding(List supported) { return org.restlet.engine.util.ConnegUtils.getPreferredMetadata( supported, getAcceptedEncodings()); } /** * Returns the preferred language among a list of supported ones, based on * the client preferences. * * @param supported * The supported languages. * @return The preferred language. */ public Language getPreferredLanguage(List supported) { return org.restlet.engine.util.ConnegUtils.getPreferredMetadata( supported, getAcceptedLanguages()); } /** * Returns the preferred media type among a list of supported ones, based on * the client preferences. * * @param supported * The supported media types. * @return The preferred media type. */ public MediaType getPreferredMediaType(List supported) { return org.restlet.engine.util.ConnegUtils.getPreferredMetadata( supported, getAcceptedMediaTypes()); } /** * Returns the best variant for a given resource according the the client * preferences: accepted languages, accepted character sets, accepted media * types and accepted encodings. A default language is provided in case the * variants don't match the client preferences. * * @param variants * The list of variants to compare. * @param metadataService * The metadata service. * @return The best variant. * @see Apache * content negotiation algorithm */ public Variant getPreferredVariant(List variants, org.restlet.service.MetadataService metadataService) { return org.restlet.engine.util.ConnegUtils.getPreferredVariant(this, variants, metadataService); } /** * Returns the best variant for a given resource according the the client * preferences. A default language is provided in case the resource's * variants don't match the client preferences. * * @param resource * The resource for which the best representation needs to be * set. * @param metadataService * The metadata service. * @return The best variant. * @see Apache * content negotiation algorithm * @deprecated Used * {@link #getPreferredVariant(List, org.restlet.service.MetadataService)} * instead. */ @Deprecated public Variant getPreferredVariant(org.restlet.resource.Resource resource, org.restlet.service.MetadataService metadataService) { return getPreferredVariant(resource.getVariants(), metadataService); } /** * Returns the additional client principals. Note that {@link #getUser()} * and {@link #getRoles()} methods already return user and role principals. * * @return The additional client principals. */ public List getPrincipals() { // Lazy initialization with double-check. List a = this.principals; if (a == null) { synchronized (this) { a = this.principals; if (a == null) { this.principals = a = new CopyOnWriteArrayList(); } } } return a; } /** * Returns the authenticated user roles. * * @return The authenticated user roles. */ public List getRoles() { // Lazy initialization with double-check. List a = this.roles; if (a == null) { synchronized (this) { a = this.roles; if (a == null) { this.roles = a = new CopyOnWriteArrayList(); } } } return a; } /** * Returns the IP address of the upstream client component. In general this * will correspond the the user agent IP address. This is useful if there * are intermediary components like proxies and load balancers. * * If the supporting {@link #getForwardedAddresses()} method returns a non * empty list, the IP address will be the first element. Otherwise, the * value of {@link #getAddress()} will be returned.
    *
    * Note that your HTTP server connectors need to have a special * "useForwardedForHeader" parameter explicitly set to "true" in order to * activate this feature, due to potential security issues. * * @return The most upstream IP address. * @see #getAddress() * @see #getForwardedAddresses() */ public String getUpstreamAddress() { if (this.forwardedAddresses == null || this.forwardedAddresses.isEmpty()) { return getAddress(); } return this.forwardedAddresses.get(0); } /** * Returns the authenticated user. * * @return The authenticated user. */ public org.restlet.security.User getUser() { return user; } /** * Indicates if the identifier or principal has been authenticated. The * application is responsible for updating this property, relying on a * {@link org.restlet.security.Guard} or manually. * * @return True if the identifier or principal has been authenticated. */ public boolean isAuthenticated() { return this.authenticated; } /** * Sets the character set preferences. Note that when used with HTTP * connectors, this property maps to the "Accept-Charset" header. * * @param acceptedCharacterSets * The character set preferences. */ public void setAcceptedCharacterSets( List> acceptedCharacterSets) { synchronized (this) { List> ac = getAcceptedCharacterSets(); ac.clear(); ac.addAll(acceptedCharacterSets); } } /** * Sets the encoding preferences. Note that when used with HTTP connectors, * this property maps to the "Accept-Encoding" header. * * @param acceptedEncodings * The encoding preferences. */ public void setAcceptedEncodings( List> acceptedEncodings) { synchronized (this) { List> ac = getAcceptedEncodings(); ac.clear(); ac.addAll(acceptedEncodings); } } /** * Sets the language preferences. Note that when used with HTTP connectors, * this property maps to the "Accept-Language" header. * * @param acceptedLanguages * The language preferences. */ public void setAcceptedLanguages( List> acceptedLanguages) { synchronized (this) { List> ac = getAcceptedLanguages(); ac.clear(); ac.addAll(acceptedLanguages); } } /** * Sets the media type preferences. Note that when used with HTTP * connectors, this property maps to the "Accept" header. * * @param acceptedMediaTypes * The media type preferences. */ public void setAcceptedMediaTypes( List> acceptedMediaTypes) { synchronized (this) { List> ac = getAcceptedMediaTypes(); ac.clear(); ac.addAll(acceptedMediaTypes); } } /** * Sets the client's IP address. * * @param address * The client's IP address. */ public void setAddress(String address) { this.address = address; } /** * Sets the list of client IP addresses. * * @param addresses * The list of client IP addresses. * @deprecated See the {@link #setForwardedAddresses(List)} method instead. */ @Deprecated public void setAddresses(List addresses) { setForwardedAddresses(addresses); } /** * Sets the agent name (ex: "Restlet-Framework/2.0"). Note that when used * with HTTP connectors, this property maps to the "User-Agent" header. * * @param agent * The agent name. */ public void setAgent(String agent) { this.agent = agent; } /** * Sets a list of attributes taken from the name of the user agent. * * @param agentAttributes * A list of attributes taken from the name of the user agent. */ public void setAgentAttributes(Map agentAttributes) { synchronized (this) { Map aa = getAgentAttributes(); aa.clear(); aa.putAll(agentAttributes); } } /** * Sets the list of product tokens from the user agent name. * * @param agentProducts * The list of product tokens from the user agent name. */ public void setAgentProducts(List agentProducts) { synchronized (this) { List ap = getAgentProducts(); ap.clear(); ap.addAll(agentProducts); } } /** * Indicates if the identifier or principal has been authenticated. The * application is responsible for updating this property, relying on a * {@link org.restlet.security.Guard} or manually. * * @param authenticated * True if the identifier or principal has been authenticated. */ public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } /** * Sets the client expectations. * * @param expectations * The client expectations. */ public void setExpectations(List expectations) { synchronized (this) { List e = getExpectations(); e.clear(); e.addAll(expectations); } } /** * Sets the list of forwarded IP addresses. * * @param forwardedAddresses * The list of forwarded IP addresses. * @see #getForwardedAddresses() */ public void setForwardedAddresses(List forwardedAddresses) { synchronized (this) { List fa = getForwardedAddresses(); fa.clear(); fa.addAll(forwardedAddresses); } } /** * Sets the email address of the human user controlling the user agent. * * @param from * The email address of the human user controlling the user * agent. */ public void setFrom(String from) { this.from = from; } /** * Sets the port number which sent the call. * * @param port * The port number which sent the call. */ public void setPort(int port) { this.port = port; } /** * Sets the additional client principals. * * @param principals * The additional client principals. * @see #getPrincipals() */ public void setPrincipals(List principals) { synchronized (this) { List fa = getPrincipals(); fa.clear(); fa.addAll(principals); } } /** * Sets the authenticated user roles. * * @param roles * The authenticated user roles. */ public void setRoles(List roles) { synchronized (this) { List r = getRoles(); r.clear(); r.addAll(roles); } } /** * Sets the authenticated user. * * @param user * The authenticated user. */ public void setUser(org.restlet.security.User user) { this.user = user; } } restlet-2.0.14/org.restlet/src/org/restlet/data/ChallengeMessage.java0000664000175000017500000001563611757206346026235 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import org.restlet.engine.util.SystemUtils; import org.restlet.util.Series; /** * Base authentication challenge message exchanged between an origin server and * a client. * * @author Jerome Louvel */ public abstract class ChallengeMessage { /** Authentication quality. */ public static final String QUALITY_AUTHENTICATION = "auth"; /** Authentication and integrity. */ public static final String QUALITY_AUTHENTICATION_INTEGRITY = "auth-int"; /** The raw value for custom challenge schemes. */ private volatile String rawValue; /** The additional scheme parameters. */ private volatile Series parameters; /** The challenge scheme. */ private volatile ChallengeScheme scheme; /** The server nonce. */ private volatile String serverNonce; /** The authentication realm. */ private volatile String realm; /** * An opaque string of data which should be returned by the client * unchanged. */ private volatile String opaque; /** The digest algorithm. */ private volatile String digestAlgorithm; /** * Constructor. * * @param scheme * The challenge scheme. */ public ChallengeMessage(ChallengeScheme scheme) { this(scheme, null, null); } /** * Constructor. * * @param scheme * The challenge scheme. * @param parameters * The additional scheme parameters. */ public ChallengeMessage(ChallengeScheme scheme, Series parameters) { this(scheme, null, null); } /** * Constructor. * * @param scheme * The challenge scheme. * @param realm * The authentication realm. */ public ChallengeMessage(ChallengeScheme scheme, String realm) { this(scheme, realm, null); } /** * Constructor. * * @param scheme * The challenge scheme. * @param realm * The authentication realm. * @param parameters * The additional scheme parameters. */ public ChallengeMessage(ChallengeScheme scheme, String realm, Series parameters) { this.scheme = scheme; this.rawValue = null; this.realm = realm; this.parameters = parameters; this.digestAlgorithm = Digest.ALGORITHM_MD5; this.serverNonce = null; this.opaque = null; } /** * Returns the digest algorithm. See {@link Digest} class for DIGEST_* * constants. Default value is {@link Digest#ALGORITHM_MD5}. * * @return The digest algorithm. */ public String getDigestAlgorithm() { return digestAlgorithm; } /** * Returns an opaque string of data which should be returned by the client * unchanged. * * @return An opaque string of data. */ public String getOpaque() { return opaque; } /** * Returns the modifiable series of scheme parameters. Creates a new * instance if no one has been set. * * @return The modifiable series of scheme parameters. */ public Series getParameters() { if (this.parameters == null) { this.parameters = new Form(); } return this.parameters; } /** * Returns the raw challenge value. * * @return The raw challenge value. */ public String getRawValue() { return this.rawValue; } /** * Returns the realm name. * * @return The realm name. */ public String getRealm() { return this.realm; } /** * Returns the scheme used. * * @return The scheme used. */ public ChallengeScheme getScheme() { return this.scheme; } /** * Returns the server nonce. * * @return The server nonce. */ public String getServerNonce() { return serverNonce; } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(getScheme(), getRealm(), getParameters()); } /** * Sets the digest algorithm. See {@link Digest} class for ALGORITHM_* * constants. Default value is {@link Digest#ALGORITHM_MD5}. * * @param digestAlgorithm * The digest algorithm. */ public void setDigestAlgorithm(String digestAlgorithm) { this.digestAlgorithm = digestAlgorithm; } /** * Sets an opaque string of data which should be returned by the client * unchanged. * * @param opaque * An opaque string of data. */ public void setOpaque(String opaque) { this.opaque = opaque; } /** * Sets the parameters. * * @param parameters * The parameters. */ public void setParameters(Series parameters) { this.parameters = parameters; } /** * Sets the raw value. * * @param rawValue * The raw value. */ public void setRawValue(String rawValue) { this.rawValue = rawValue; } /** * Sets the realm name. * * @param realm * The realm name. */ public void setRealm(String realm) { this.realm = realm; } /** * Sets the scheme used. * * @param scheme * The scheme used. */ public void setScheme(ChallengeScheme scheme) { this.scheme = scheme; } /** * Sets the server nonce. * * @param serverNonce * The server nonce. */ public void setServerNonce(String serverNonce) { this.serverNonce = serverNonce; } } restlet-2.0.14/org.restlet/src/org/restlet/data/LocalReference.java0000664000175000017500000003272411757206350025707 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.data; import java.io.File; /** * Reference to a local resource. It has helper methods for the three following * schemes: {@link Protocol#CLAP}, {@link Protocol#FILE}, {@link Protocol#JAR} * and {@link Protocol#RIAP}. * * @author Jerome Louvel */ public final class LocalReference extends Reference { /** * The resources will be resolved from the classloader associated with the * local class. This is the same as the {@link #CLAP_CLASS} authority. * Examples: clap:///rootPkg/subPkg/myClass.class or * clap:///rootPkg/file.html * * @see java.lang.Class#getClassLoader() */ public static final int CLAP_DEFAULT = 0; /** * The resources will be resolved from the classloader associated with the * local class. This is the default CLAP authority. Examples: * clap://class/rootPkg/subPkg/myClass.class or * clap://class/rootPkg/file.html or clap:///rootPkg/file.html * * @see java.lang.Class#getClassLoader() */ public static final int CLAP_CLASS = 1; /** * The resources will be resolved from the system's classloader. Examples: * clap://system/rootPkg/subPkg/myClass.class or * clap://system/rootPkg/file.html * * @see java.lang.ClassLoader#getSystemClassLoader() */ public static final int CLAP_SYSTEM = 2; /** * The resources will be resolved from the current thread's classloader. * Examples: clap://thread/rootPkg/subPkg/myClass.class or * clap://thread/rootPkg/file.html * * @see java.lang.Thread#getContextClassLoader() */ public static final int CLAP_THREAD = 3; /** * The resources will be resolved from the current application's root * Restlet. Example riap://application/myPath/myResource */ public static final int RIAP_APPLICATION = 4; /** * The resources will be resolved from the current component's internal * (private) router. Example riap://component/myAppPath/myResource */ public static final int RIAP_COMPONENT = 5; /** * The resources will be resolved from the current component's virtual host. * Example riap://host/myAppPath/myResource */ public static final int RIAP_HOST = 6; /** * Constructor. * * @param pkg * The package to identify. */ public static LocalReference createClapReference(Package pkg) { return createClapReference(CLAP_DEFAULT, pkg); } /** * Constructor for CLAP URIs to a given package. * * @param authorityType * The authority type for the resource path. * @param pkg * The package to identify. */ public static LocalReference createClapReference(int authorityType, Package pkg) { String pkgPath = pkg.getName().replaceAll("\\.", "/"); return new LocalReference("clap://" + getAuthorityName(authorityType) + "/" + pkgPath); } /** * Constructor. * * @param path * The resource path. */ public static LocalReference createClapReference(String path) { return createClapReference(CLAP_DEFAULT, path); } /** * Constructor. * * @param authorityType * The authority type for the resource path. * @param path * The resource path. */ public static LocalReference createClapReference(int authorityType, String path) { return new LocalReference("clap://" + getAuthorityName(authorityType) + path); } /** * Constructor. * * @param file * The file whose path must be used. * @return The new local reference. * @see #createFileReference(String) */ public static LocalReference createFileReference(File file) { return createFileReference(file.getAbsolutePath()); } /** * Constructor. * * @param filePath * The local file path. * @see #createFileReference(String, String) */ public static LocalReference createFileReference(String filePath) { return createFileReference("", filePath); } /** * Constructor. * * @param hostName * The authority (can be a host name or the special "localhost" * or an empty value). * @param filePath * The file path. */ public static LocalReference createFileReference(String hostName, String filePath) { return new LocalReference("file://" + hostName + "/" + normalizePath(filePath)); } /** * Constructor. * * @param jarFile * The JAR file reference. * @param entryPath * The entry path inside the JAR file. */ public static LocalReference createJarReference(Reference jarFile, String entryPath) { return new LocalReference("jar:" + jarFile.getTargetRef().toString() + "!/" + entryPath); } /** * Constructor. * * @param authorityType * The authority type for the resource path. * @param path * The resource path. */ public static LocalReference createRiapReference(int authorityType, String path) { return new LocalReference("riap://" + getAuthorityName(authorityType) + path); } /** * Constructor. * * @param zipFile * The Zip file reference. * @param entryPath * The entry path inside the Zip file. */ public static LocalReference createZipReference(Reference zipFile, String entryPath) { return new LocalReference("zip:" + zipFile.getTargetRef().toString() + "!/" + entryPath); } /** * Returns an authority name. * * @param authority * The authority. * @return The name. */ public static String getAuthorityName(int authority) { String result = null; switch (authority) { case CLAP_DEFAULT: result = ""; break; case CLAP_CLASS: result = "class"; break; case CLAP_SYSTEM: result = "system"; break; case CLAP_THREAD: result = "thread"; break; case RIAP_APPLICATION: result = "application"; break; case RIAP_COMPONENT: result = "component"; break; case RIAP_HOST: result = "host"; break; } return result; } /** * Localize a path by converting all the separator characters to the * system-dependent separator character. * * @param path * The path to localize. * @return The localized path. */ public static String localizePath(String path) { final StringBuilder result = new StringBuilder(); char nextChar; for (int i = 0; i < path.length(); i++) { nextChar = path.charAt(i); if (nextChar == '/') { // Convert the URI separator to // the system dependent path separator result.append(File.separatorChar); } else { result.append(nextChar); } } return result.toString(); } /** * Normalize a path by converting all the system-dependent separator * characters to the standard '/' separator character. * * @param path * The path to normalize. * @return The normalize path. */ public static String normalizePath(String path) { final StringBuilder result = new StringBuilder(); char nextChar; for (int i = 0; i < path.length(); i++) { nextChar = path.charAt(i); if ((nextChar == File.separatorChar)) { // Convert the Windows style path separator // to the standard path separator result.append('/'); } else if (!isUnreserved(nextChar)) { result.append(Reference.encode("" + nextChar)); } else { result.append(nextChar); } } return result.toString(); } /** * Constructor. * * @param localRef * The local reference. */ public LocalReference(Reference localRef) { super(localRef.getTargetRef().toString()); } /** * Constructor. * * @param localUri * The local URI. */ public LocalReference(String localUri) { super(localUri); } /** * Returns the type of authority. * * @return The type of authority. */ public int getClapAuthorityType() { int result = 0; if (Protocol.CLAP.equals(getSchemeProtocol())) { final String authority = getAuthority(); if (authority != null) { if (authority.equalsIgnoreCase(getAuthorityName(CLAP_CLASS))) { result = CLAP_CLASS; } else if (authority .equalsIgnoreCase(getAuthorityName(CLAP_SYSTEM))) { result = CLAP_SYSTEM; } else if (authority .equalsIgnoreCase(getAuthorityName(CLAP_THREAD))) { result = CLAP_THREAD; } else { result = CLAP_DEFAULT; } } } return result; } /** * Gets the local file corresponding to the reference. Only URIs referring * to the "localhost" or to an empty authority are supported. * * @return The local file corresponding to the reference. */ public File getFile() { File result = null; if (Protocol.FILE.equals(getSchemeProtocol())) { final String hostName = getAuthority(); if ((hostName == null) || hostName.equals("") || hostName.equalsIgnoreCase("localhost")) { final String filePath = Reference.decode(getPath()); result = new File(filePath); } else { throw new RuntimeException( "Can't resolve files on remote host machines"); } } return result; } /** * Returns the JAR entry path. * * @return The JAR entry path. */ public String getJarEntryPath() { String result = null; if (Protocol.JAR.equals(getSchemeProtocol())) { final String ssp = getSchemeSpecificPart(); if (ssp != null) { final int separatorIndex = ssp.indexOf("!/"); if (separatorIndex != -1) { result = ssp.substring(separatorIndex + 2); } } } return result; } /** * Returns the JAR file reference. * * @return The JAR file reference. */ public Reference getJarFileRef() { Reference result = null; if (Protocol.JAR.equals(getSchemeProtocol())) { final String ssp = getSchemeSpecificPart(); if (ssp != null) { final int separatorIndex = ssp.indexOf("!/"); if (separatorIndex != -1) { result = new Reference(ssp.substring(0, separatorIndex)); } } } return result; } /** * Returns the type of authority. * * @return The type of authority. */ public int getRiapAuthorityType() { int result = 0; if (Protocol.RIAP.equals(getSchemeProtocol())) { final String authority = getAuthority(); if (authority != null) { if (authority .equalsIgnoreCase(getAuthorityName(RIAP_APPLICATION))) { result = RIAP_APPLICATION; } else if (authority .equalsIgnoreCase(getAuthorityName(RIAP_COMPONENT))) { result = RIAP_COMPONENT; } else if (authority .equalsIgnoreCase(getAuthorityName(RIAP_HOST))) { result = RIAP_HOST; } } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/util/0000775000175000017500000000000011757206350022227 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/util/Triple.java0000664000175000017500000001024211757206346024335 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import org.restlet.engine.util.SystemUtils; /** * Relationship between three typed objects. * * @author Jerome Louvel * * @param * The first object's type. * @param * The second object's type. * @param * The third object's type. */ public class Triple { /** The first object. */ private volatile T first; /** The second object. */ private volatile U second; /** The third object. */ private volatile V third; /** * Constructor. * * @param first * The first object. * @param second * The second object. * @param third * The third object. */ public Triple(T first, U second, V third) { this.first = first; this.second = second; this.third = third; } @Override public boolean equals(Object other) { boolean result = (this == other); if (!result && (other instanceof Triple)) { Triple triple = (Triple) other; if (((triple.getFirst() == null) && (getFirst() == null)) || ((getFirst() != null) && getFirst().equals( triple.getFirst()))) { if (((triple.getSecond() == null) && (getSecond() == null)) || ((getSecond() != null) && getSecond().equals( triple.getSecond()))) { result = (((triple.getThird() == null) && (getThird() == null)) || ((getThird() != null) && getThird() .equals(triple.getThird()))); } } } return result; } /** * Returns the first object. * * @return The first object. */ public T getFirst() { return first; } /** * Returns the second object. * * @return The second object. */ public U getSecond() { return second; } /** * Returns the third object. * * @return The third object. */ public V getThird() { return third; } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(getFirst(), getSecond(), getThird()); } /** * Sets the first object. * * @param first * The first object. */ public void setFirst(T first) { this.first = first; } /** * Sets the second object. * * @param second * The second object. */ public void setSecond(U second) { this.second = second; } /** * Sets the third object. * * @param third * The third object. */ public void setThird(V third) { this.third = third; } @Override public String toString() { return "(" + getFirst() + "," + getSecond() + "," + getThird() + ")"; } } restlet-2.0.14/org.restlet/src/org/restlet/util/WrapperRestlet.java0000664000175000017500000000735011757206346026067 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.logging.Logger; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; /** * Restlet wrapper. Useful for application developer who need to wrap a Restlet * instance. * * @author Thierry Boileau * @see The decorator (aka * wrapper) pattern */ public class WrapperRestlet extends Restlet { /** The wrapped Restlet instance. */ private Restlet wrappedRestlet; /** * Constructor. * * @param wrappedRestlet * The wrapped Restlet instance. */ public WrapperRestlet(Restlet wrappedRestlet) { super(); this.wrappedRestlet = wrappedRestlet; } @Override public org.restlet.Application getApplication() { return wrappedRestlet.getApplication(); } @Override public String getAuthor() { return wrappedRestlet.getAuthor(); } @Override public Context getContext() { return wrappedRestlet.getContext(); } @Override public String getDescription() { return wrappedRestlet.getDescription(); } @Override public Logger getLogger() { return wrappedRestlet.getLogger(); } @Override public String getName() { return wrappedRestlet.getName(); } @Override public String getOwner() { return wrappedRestlet.getOwner(); } @Override public void handle(Request request, Response response) { wrappedRestlet.handle(request, response); } @Override public boolean isStarted() { return wrappedRestlet.isStarted(); } @Override public boolean isStopped() { return wrappedRestlet.isStopped(); } @Override public void setAuthor(String author) { wrappedRestlet.setAuthor(author); } @Override public void setContext(Context context) { wrappedRestlet.setContext(context); } @Override public void setDescription(String description) { wrappedRestlet.setDescription(description); } @Override public void setName(String name) { wrappedRestlet.setName(name); } @Override public void setOwner(String owner) { wrappedRestlet.setOwner(owner); } @Override public synchronized void start() throws Exception { wrappedRestlet.start(); } @Override public synchronized void stop() throws Exception { wrappedRestlet.stop(); } } restlet-2.0.14/org.restlet/src/org/restlet/util/WrapperRequest.java0000664000175000017500000003337411757206346026102 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.List; import java.util.Map; import org.restlet.Request; import org.restlet.Response; import org.restlet.Uniform; import org.restlet.data.ChallengeResponse; import org.restlet.data.ClientInfo; import org.restlet.data.Conditions; import org.restlet.data.Cookie; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Range; import org.restlet.data.Reference; import org.restlet.representation.Representation; /** * Request wrapper. Useful for application developer who need to enrich the * request with application related properties and behavior. * * @see The decorator (aka * wrapper) pattern * @author Jerome Louvel */ public class WrapperRequest extends Request { /** The wrapped request. */ private final Request wrappedRequest; /** * Constructor. * * @param wrappedRequest * The wrapped request. */ public WrapperRequest(Request wrappedRequest) { this.wrappedRequest = wrappedRequest; } @Override public boolean abort() { return wrappedRequest.abort(); } @Override public void commit(Response response) { wrappedRequest.commit(response); } /** * Returns a modifiable attributes map that can be used by developers to * save information relative to the message. This is an easier alternative * to the creation of a wrapper instance around the whole message.
    *
    * * In addition, this map is a shared space between the developer and the * connectors. In this case, it is used to exchange information that is not * uniform across all protocols and couldn't therefore be directly included * in the API. For this purpose, all attribute names starting with * "org.restlet" are reserved. Currently the following attributes are used: * * * * * * * * * * * *
    Attribute nameClass nameDescription
    org.restlet.http.headersorg.restlet.data.FormServer HTTP connectors must provide all request headers and client * HTTP connectors must provide all response headers, exactly as they were * received. In addition, developers can also use this attribute to specify * non-standard headers that should be added to the request or to the * response.
    * Adding standard HTTP headers is forbidden because it could conflict with * the connector's internal behavior, limit portability or prevent future * optimizations. * * @return The modifiable attributes map. */ @Override public Map getAttributes() { return getWrappedRequest().getAttributes(); } /** * Returns the authentication response sent by a client to an origin server. * * @return The authentication response sent by a client to an origin server. */ @Override public ChallengeResponse getChallengeResponse() { return getWrappedRequest().getChallengeResponse(); } /** * Returns the client-specific information. * * @return The client-specific information. */ @Override public ClientInfo getClientInfo() { return getWrappedRequest().getClientInfo(); } /** * Returns the conditions applying to this call. * * @return The conditions applying to this call. */ @Override public Conditions getConditions() { return getWrappedRequest().getConditions(); } /** * Returns the cookies provided by the client. * * @return The cookies provided by the client. */ @Override public Series getCookies() { return getWrappedRequest().getCookies(); } /** * Returns the entity representation. * * @return The entity representation. */ @Override public Representation getEntity() { return getWrappedRequest().getEntity(); } /** * Returns the entity as a DOM representation.
    * Note that this triggers the parsing of the entity into a reusable DOM * document stored in memory.
    * This method and the related getEntity*() methods can only be invoked * once. * * @return The entity as a DOM representation. * @deprecated Will be removed in future release 2.1. */ @Deprecated @Override public Form getEntityAsForm() { return getWrappedRequest().getEntityAsForm(); } /** * Returns the host reference. This may be different from the resourceRef's * host, for example for URNs and other URIs that don't contain host * information. * * @return The host reference. */ @Override public Reference getHostRef() { return getWrappedRequest().getHostRef(); } @Override public int getMaxForwards() { return wrappedRequest.getMaxForwards(); } /** * Returns the method. * * @return The method. */ @Override public Method getMethod() { return getWrappedRequest().getMethod(); } @Override public Uniform getOnResponse() { return wrappedRequest.getOnResponse(); } @Override public Reference getOriginalRef() { return wrappedRequest.getOriginalRef(); } /** * Returns the protocol by first returning the baseRef.schemeProtocol * property if it is set, or the resourceRef.schemeProtocol property * otherwise. * * @return The protocol or null if not available. */ @Override public Protocol getProtocol() { return getWrappedRequest().getProtocol(); } /** * Returns the authentication response sent by a client to a proxy. * * @return The authentication response sent by a client to a proxy. */ @Override public ChallengeResponse getProxyChallengeResponse() { return getWrappedRequest().getProxyChallengeResponse(); } @Override public List getRanges() { return wrappedRequest.getRanges(); } /** * Returns the referrer reference if available. * * @return The referrer reference. */ @Override public Reference getReferrerRef() { return getWrappedRequest().getReferrerRef(); } /** * Returns the reference of the target resource. * * @return The reference of the target resource. */ @Override public Reference getResourceRef() { return getWrappedRequest().getResourceRef(); } /** * Returns the application root reference. * * @return The application root reference. */ @Override public Reference getRootRef() { return getWrappedRequest().getRootRef(); } /** * Returns the wrapped request. * * @return The wrapped request. */ protected Request getWrappedRequest() { return this.wrappedRequest; } /** * Indicates if the call came over a confidential channel such as an * SSL-secured connection. * * @return True if the call came over a confidential channel. */ @Override public boolean isConfidential() { return getWrappedRequest().isConfidential(); } /** * Indicates if a content is available and can be sent. Several conditions * must be met: the method must allow the sending of content, the content * must exists and have some available data. * * @return True if a content is available and can be sent. */ @Override public boolean isEntityAvailable() { return getWrappedRequest().isEntityAvailable(); } @Override public boolean isExpectingResponse() { return wrappedRequest.isExpectingResponse(); } /** * Sets the authentication response sent by a client to an origin server. * * @param response * The authentication response sent by a client to an origin * server. */ @Override public void setChallengeResponse(ChallengeResponse response) { getWrappedRequest().setChallengeResponse(response); } @Override public void setClientInfo(ClientInfo clientInfo) { wrappedRequest.setClientInfo(clientInfo); } @Override public void setConditions(Conditions conditions) { wrappedRequest.setConditions(conditions); } @Override public void setCookies(Series cookies) { wrappedRequest.setCookies(cookies); } /** * Sets the entity representation. * * @param entity * The entity representation. */ @Override public void setEntity(Representation entity) { getWrappedRequest().setEntity(entity); } /** * Sets a textual entity. * * @param value * The represented string. * @param mediaType * The representation's media type. */ @Override public void setEntity(String value, MediaType mediaType) { getWrappedRequest().setEntity(value, mediaType); } /** * Sets the host reference. * * @param hostRef * The host reference. */ @Override public void setHostRef(Reference hostRef) { getWrappedRequest().setHostRef(hostRef); } /** * Sets the host reference using an URI string. * * @param hostUri * The host URI. */ @Override public void setHostRef(String hostUri) { getWrappedRequest().setHostRef(hostUri); } @Override public void setMaxForwards(int maxForwards) { wrappedRequest.setMaxForwards(maxForwards); } /** * Sets the method called. * * @param method * The method called. */ @Override public void setMethod(Method method) { getWrappedRequest().setMethod(method); } @Override public void setOnResponse(Uniform onResponseCallback) { wrappedRequest.setOnResponse(onResponseCallback); } @Override public void setOriginalRef(Reference originalRef) { wrappedRequest.setOriginalRef(originalRef); } @Override public void setProtocol(Protocol protocol) { wrappedRequest.setProtocol(protocol); } /** * Sets the authentication response sent by a client to a proxy. * * @param response * The authentication response sent by a client to a proxy. */ @Override public void setProxyChallengeResponse(ChallengeResponse response) { getWrappedRequest().setProxyChallengeResponse(response); } @Override public void setRanges(List ranges) { wrappedRequest.setRanges(ranges); } /** * Sets the referrer reference if available. * * @param referrerRef * The referrer reference. */ @Override public void setReferrerRef(Reference referrerRef) { getWrappedRequest().setReferrerRef(referrerRef); } /** * Sets the referrer reference if available using an URI string. * * @param referrerUri * The referrer URI. */ @Override public void setReferrerRef(String referrerUri) { getWrappedRequest().setReferrerRef(referrerUri); } /** * Sets the target resource reference. If the reference is relative, it will * be resolved as an absolute reference. Also, the context's base reference * will be reset. Finally, the reference will be normalized to ensure a * consistent handling of the call. * * @param resourceRef * The resource reference. */ @Override public void setResourceRef(Reference resourceRef) { getWrappedRequest().setResourceRef(resourceRef); } /** * Sets the target resource reference using an URI string. Note that the URI * can be either absolute or relative to the context's base reference. * * @param resourceUri * The resource URI. */ @Override public void setResourceRef(String resourceUri) { getWrappedRequest().setResourceRef(resourceUri); } /** * Sets the application root reference. * * @param rootRef * The application root reference. */ @Override public void setRootRef(Reference rootRef) { getWrappedRequest().setRootRef(rootRef); } @Override public String toString() { return wrappedRequest.toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/util/Resolver.java0000664000175000017500000001577611757206350024713 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.Map; import org.restlet.Request; import org.restlet.Response; import org.restlet.engine.util.CallResolver; import org.restlet.engine.util.MapResolver; /** * Resolves a name into a value. By default, the {@link #createResolver(Map)} * static method can adapt a Java map into a resolver. Another useful method is * {@link #createResolver(Request, Response)}, which can expose a Restlet call * into a compact data model, with the following variables: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Model propertyVariable nameContent type
    request.confidentialcboolean (true|false)
    request.clientInfo.addressciaString
    request.clientInfo.upstreamAddressciuaString
    request.clientInfo.agentcigString
    request.challengeResponse.identifiercriString
    request.challengeResponse.schemecrsString
    request.datedDate (HTTP format)
    request.entity.characterSetecsString
    response.entity.characterSetECSString
    request.entity.encodingeeString
    response.entity.encodingEEString
    request.entity.expirationDateeedDate (HTTP format)
    response.entity.expirationDateEEDDate (HTTP format)
    request.entity.languageelString
    response.entity.languageELString
    request.entity.modificationDateemdDate (HTTP format)
    response.entity.modificationDateEMDDate (HTTP format)
    request.entity.mediaTypeemtString
    response.entity.mediaTypeEMTString
    request.entity.sizeesInteger
    response.entity.sizeESInteger
    request.entity.tagetString
    response.entity.tagETString
    request.referrerReff*Reference (see table below variable name sub-parts)
    request.hostRefh*Reference (see table below variable name sub-parts)
    request.methodmString
    request.rootRefo*Reference (see table below variable name sub-parts)
    request.protocolpString
    request.resourceRefr*Reference (see table below variable name sub-parts)
    response.redirectRefR*Reference (see table below variable name sub-parts)
    response.statusSInteger
    response.serverInfo.addressSIAString
    response.serverInfo.agentSIGString
    response.serverInfo.portSIPInteger
    *
    * * Below is the list of name sub-parts, for Reference variables, that can * replace the asterix in the variable names above:
    *
    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Reference propertySub-part nameContent type
    authorityaString
    baseRefb*Reference
    relativeParteString
    fragmentfString
    hostIdentifierhString
    identifieriString
    pathpString
    queryqString
    remainingPartrString
    * * @author Jerome Louvel */ public abstract class Resolver { /** * Creates a resolver that is based on a given map. * * @param map * Map between names and values. * @return The map resolver. */ public static Resolver createResolver(Map map) { return new MapResolver(map); } /** * Creates a resolver that is based on a call (request, response couple). It * first looks up the response attributes, then the request attributes and * finally the variables listed in this class Javadocs above. * * @param request * The request. * @param response * The response. * @return The call resolver. */ public static Resolver createResolver(Request request, Response response) { return new CallResolver(request, response); } /** * Resolves a name into a value. * * @param name * The name to resolve. * @return The resolved value. */ public abstract T resolve(String name); } restlet-2.0.14/org.restlet/src/org/restlet/util/WrapperResponse.java0000664000175000017500000004033111757206350026232 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.AuthenticationInfo; import org.restlet.data.ChallengeRequest; import org.restlet.data.CookieSetting; import org.restlet.data.Dimension; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.ServerInfo; import org.restlet.data.Status; import org.restlet.representation.Representation; /** * Request wrapper. Useful for application developer who need to enrich the * request with application related properties and behavior. * * @see The decorator (aka * wrapper) pattern * @author Jerome Louvel */ public class WrapperResponse extends Response { /** The wrapped response. */ private final Response wrappedResponse; /** * Constructor. * * @param wrappedResponse * The wrapped response. */ public WrapperResponse(Response wrappedResponse) { super((Request) null); this.wrappedResponse = wrappedResponse; } @Override public void abort() { wrappedResponse.abort(); } @Override public void commit() { wrappedResponse.commit(); } @Override public int getAge() { return wrappedResponse.getAge(); } /** * Returns the set of methods allowed on the requested resource. This * property only has to be updated when a status * CLIENT_ERROR_METHOD_NOT_ALLOWED is set. * * @return The list of allowed methods. */ @Override public Set getAllowedMethods() { return getWrappedResponse().getAllowedMethods(); } /** * Returns a modifiable attributes map that can be used by developers to * save information relative to the message. This is an easier alternative * to the creation of a wrapper instance around the whole message.
    *
    * * In addition, this map is a shared space between the developer and the * connectors. In this case, it is used to exchange information that is not * uniform across all protocols and couldn't therefore be directly included * in the API. For this purpose, all attribute names starting with * "org.restlet" are reserved. Currently the following attributes are used: * * * * * * * * * * * *
    Attribute nameClass nameDescription
    org.restlet.http.headersorg.restlet.data.FormServer HTTP connectors must provide all request headers and client * HTTP connectors must provide all response headers, exactly as they were * received. In addition, developers can also use this attribute to specify * non-standard headers that should be added to the request or to the * response.
    * Adding standard HTTP headers is forbidden because it could conflict with * the connector's internal behavior, limit portability or prevent future * optimizations. * * @return The modifiable attributes map. */ @Override public Map getAttributes() { return getWrappedResponse().getAttributes(); } @Override public AuthenticationInfo getAuthenticationInfo() { return wrappedResponse.getAuthenticationInfo(); } /** * Returns the list of authentication requests sent by an origin server to a * client. * * @return The list of authentication requests sent by an origin server to a * client. */ @Override public List getChallengeRequests() { return getWrappedResponse().getChallengeRequests(); } /** * Returns the cookie settings provided by the server. * * @return The cookie settings provided by the server. */ @Override public Series getCookieSettings() { return getWrappedResponse().getCookieSettings(); } /** * Returns the set of selecting dimensions on which the response entity may * vary. If some server-side content negotiation is done, this set should be * properly updated, other it can be left empty. * * @return The set of dimensions on which the response entity may vary. */ @Override public Set getDimensions() { return getWrappedResponse().getDimensions(); } /** * Returns the entity representation. * * @return The entity representation. */ @Override public Representation getEntity() { return getWrappedResponse().getEntity(); } /** * Returns the entity as a DOM representation.
    * Note that this triggers the parsing of the entity into a reusable DOM * document stored in memory.
    * This method and the related getEntity*() methods can only be invoked * once. * * @return The entity as a DOM representation. * @deprecated Will be removed in future release 2.1. */ @Deprecated @Override public Form getEntityAsForm() { return getWrappedResponse().getEntityAsForm(); } /** * Returns the reference that the client should follow for redirections or * resource creations. * * @return The redirection reference. */ @Override public Reference getLocationRef() { return getWrappedResponse().getLocationRef(); } /** * Returns the list of authentication requests sent by a proxy to a client. * * @return The list of authentication requests sent by a proxy to a client. */ @Override public List getProxyChallengeRequests() { return getWrappedResponse().getProxyChallengeRequests(); } /** * Returns the associated request * * @return The associated request */ @Override public Request getRequest() { return getWrappedResponse().getRequest(); } @Override public Date getRetryAfter() { return wrappedResponse.getRetryAfter(); } /** * Returns the server-specific information. * * @return The server-specific information. */ @Override public ServerInfo getServerInfo() { return getWrappedResponse().getServerInfo(); } /** * Returns the status. * * @return The status. */ @Override public Status getStatus() { return getWrappedResponse().getStatus(); } /** * Returns the wrapped response. * * @return The wrapped response. */ protected Response getWrappedResponse() { return this.wrappedResponse; } @Override public boolean isAutoCommitting() { return wrappedResponse.isAutoCommitting(); } @Override public boolean isCommitted() { return wrappedResponse.isCommitted(); } /** * Indicates if the call came over a confidential channel such as an * SSL-secured connection. * * @return True if the call came over a confidential channel. */ @Override public boolean isConfidential() { return getWrappedResponse().isConfidential(); } /** * Indicates if a content is available and can be sent. Several conditions * must be met: the content must exists and have some available data. * * @return True if a content is available and can be sent. */ @Override public boolean isEntityAvailable() { return getWrappedResponse().isEntityAvailable(); } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target URI reference. */ @Override public void redirectPermanent(Reference targetRef) { getWrappedResponse().redirectPermanent(targetRef); } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetUri * The target URI. */ @Override public void redirectPermanent(String targetUri) { getWrappedResponse().redirectPermanent(targetUri); } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource. * * @param targetRef * The target reference. */ @Override public void redirectSeeOther(Reference targetRef) { getWrappedResponse().redirectSeeOther(targetRef); } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource. * * @param targetUri * The target URI. */ @Override public void redirectSeeOther(String targetUri) { getWrappedResponse().redirectSeeOther(targetUri); } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target reference. */ @Override public void redirectTemporary(Reference targetRef) { getWrappedResponse().redirectTemporary(targetRef); } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetUri * The target URI. */ @Override public void redirectTemporary(String targetUri) { getWrappedResponse().redirectTemporary(targetUri); } @Override public void setAge(int age) { wrappedResponse.setAge(age); } @Override public void setAllowedMethods(Set allowedMethods) { wrappedResponse.setAllowedMethods(allowedMethods); } @Override public void setAuthenticationInfo(AuthenticationInfo authenticationInfo) { wrappedResponse.setAuthenticationInfo(authenticationInfo); } @Override public void setAutoCommitting(boolean autoCommitting) { wrappedResponse.setAutoCommitting(autoCommitting); } /** * Sets the authentication request sent by an origin server to a client. * * @param request * The authentication request sent by an origin server to a * client. */ @Override @Deprecated public void setChallengeRequest(ChallengeRequest request) { getWrappedResponse().setChallengeRequest(request); } /** * Sets the list of authentication requests sent by an origin server to a * client. * * @param requests * The list of authentication requests sent by an origin server * to a client. */ @Override public void setChallengeRequests(List requests) { getWrappedResponse().setChallengeRequests(requests); } @Override public void setCommitted(boolean committed) { wrappedResponse.setCommitted(committed); } @Override public void setCookieSettings(Series cookieSettings) { wrappedResponse.setCookieSettings(cookieSettings); } @Override public void setDimensions(Set dimensions) { wrappedResponse.setDimensions(dimensions); } /** * Sets the entity representation. * * @param entity * The entity representation. */ @Override public void setEntity(Representation entity) { getWrappedResponse().setEntity(entity); } /** * Sets a textual entity. * * @param value * The represented string. * @param mediaType * The representation's media type. */ @Override public void setEntity(String value, MediaType mediaType) { getWrappedResponse().setEntity(value, mediaType); } /** * Sets the reference that the client should follow for redirections or * resource creations. * * @param locationRef * The reference to set. */ @Override public void setLocationRef(Reference locationRef) { getWrappedResponse().setLocationRef(locationRef); } /** * Sets the reference that the client should follow for redirections or * resource creations. * * @param locationUri * The URI to set. */ @Override public void setLocationRef(String locationUri) { getWrappedResponse().setLocationRef(locationUri); } /** * Sets the list of authentication requests sent by a proxy to a client. * * @param requests * The list of authentication requests sent by a proxy to a * client. */ @Override public void setProxyChallengeRequests(List requests) { getWrappedResponse().setProxyChallengeRequests(requests); } /** * Sets the associated request. * * @param request * The associated request */ @Override public void setRequest(Request request) { getWrappedResponse().setRequest(request); } /** * Sets the associated request. * * @param request * The associated request */ public void setRequest(WrapperRequest request) { getWrappedResponse().setRequest(request); } @Override public void setRetryAfter(Date retryAfter) { wrappedResponse.setRetryAfter(retryAfter); } @Override public void setServerInfo(ServerInfo serverInfo) { wrappedResponse.setServerInfo(serverInfo); } /** * Sets the status. * * @param status * The status to set. */ @Override public void setStatus(Status status) { getWrappedResponse().setStatus(status); } /** * Sets the status. * * @param status * The status to set. * @param message * The status message. */ @Override public void setStatus(Status status, String message) { getWrappedResponse().setStatus(status, message); } @Override public void setStatus(Status status, Throwable throwable) { wrappedResponse.setStatus(status, throwable); } @Override public void setStatus(Status status, Throwable throwable, String message) { wrappedResponse.setStatus(status, throwable, message); } @Override public String toString() { return wrappedResponse.toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/util/WrapperMap.java0000664000175000017500000001461511757206346025164 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Map wrapper. Modifiable map that delegates all methods to a wrapped map. This * allows an easy subclassing. * * @author Jerome Louvel * @see The decorator (aka * wrapper) pattern * @see java.util.Collections * @see java.util.List */ public class WrapperMap implements Map { /** The delegate map. */ private final Map delegate; /** * Constructor. */ public WrapperMap() { this.delegate = new TreeMap(); } /** * Constructor. * * @param delegate * The delegate list. */ public WrapperMap(Map delegate) { this.delegate = delegate; } /** * Removes all mappings from this Map. */ public void clear() { getDelegate().clear(); } /** * Returns true if this map contains a mapping for the specified key. * * @param key * The key to look up. * @return True if this map contains a mapping for the specified key. */ public boolean containsKey(Object key) { return getDelegate().containsKey(key); } /** * Returns true if this map maps one or more keys to the specified value. * * @param value * The value to look up * @return True if this map maps one or more keys to the specified value. */ public boolean containsValue(Object value) { return getDelegate().containsValue(value); } /** * Returns a set view of the mappings contained in this map. * * @return A set view of the mappings contained in this map. */ public Set> entrySet() { return getDelegate().entrySet(); } /** * Compares the specified object with this map for equality. * * @param o * Object to be compared for equality with this map. * @return True if the specified object is equal to this map. */ @Override public boolean equals(Object o) { return getDelegate().equals(o); } /** * Returns the value to which this map maps the specified key. * * @param key * Key whose associated value is to be returned. * @return The value to which this map maps the specified key, or null if * the map contains no mapping for this key. */ public V get(Object key) { return getDelegate().get(key); } /** * Returns the delegate list. * * @return The delegate list. */ protected Map getDelegate() { return this.delegate; } /** * Returns the hash code value for this map. * * @return The hash code value for this map. */ @Override public int hashCode() { return getDelegate().hashCode(); } /** * Returns true if this map contains no key-value mappings. * * @return True if this map contains no key-value mappings. */ public boolean isEmpty() { return getDelegate().isEmpty(); } /** * Returns a set view of the keys contained in this map. * * @return A set view of the keys contained in this map. */ public Set keySet() { return getDelegate().keySet(); } /** * Associates the specified value with the specified key in this map * (optional operation). * * @param key * Key with which the specified value is to be associated. * @param value * Value to be associated with the specified key. * @return The previous value associated with specified key, or null if * there was no mapping for key. A null return can also indicate * that the map previously associated null with the specified key, * if the implementation supports null values. */ public V put(K key, V value) { return getDelegate().put(key, value); } /** * Copies all of the mappings from the specified map to this map (optional * operation). * * @param t * Mappings to be stored in this map. */ public void putAll(Map t) { getDelegate().putAll(t); } /** * Removes the mapping for this key from this map if it is present (optional * operation). * * @param key * Key whose mapping is to be removed from the map. * @return The previous value associated with specified key, or null if * there was no mapping for key. */ public V remove(Object key) { return getDelegate().remove(key); } /** * Returns the number of key-value mappings in this map. * * @return The number of key-value mappings in this map. */ public int size() { return getDelegate().size(); } /** * Returns a collection view of the values contained in this map. * * @return A collection view of the values contained in this map. */ public Collection values() { return getDelegate().values(); } } restlet-2.0.14/org.restlet/src/org/restlet/util/package.html0000664000175000017500000000032211757206350024505 0ustar jamespagejamespage Various utility classes.

    @since Restlet 1.0 @see User Guide - Util package restlet-2.0.14/org.restlet/src/org/restlet/util/ClientList.java0000664000175000017500000000542411757206346025156 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Client; import org.restlet.Context; import org.restlet.data.Protocol; /** * Modifiable list of client connectors. * * @author Jerome Louvel */ public final class ClientList extends WrapperList { /** The context. */ private volatile Context context; /** * Constructor. * * @param context * The context. */ public ClientList(Context context) { super(new CopyOnWriteArrayList()); this.context = context; } @Override public boolean add(Client client) { // Set the client's context, if the client does not have already one. if (client.getContext() == null) { client.setContext(getContext()); } return super.add(client); } /** * Adds a new client connector in the map supporting the given protocol. * * @param protocol * The connector protocol. * @return The added client. */ public Client add(Protocol protocol) { final Client result = new Client(protocol); result.setContext(getContext()); add(result); return result; } /** * Returns the context. * * @return The context. */ public Context getContext() { return this.context; } /** * Sets the context. * * @param context * The context. */ public void setContext(Context context) { this.context = context; } } restlet-2.0.14/org.restlet/src/org/restlet/util/Series.java0000664000175000017500000004473011757206346024341 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.engine.Edition; /** * Modifiable list of entries with many helper methods. Note that this class * uses the Parameter class as the template type. This allows you to use an * instance of this class as any other java.util.List, in particular all the * helper methods in java.util.Collections. * * @author Jerome Louvel * @param * The contained type * @see org.restlet.data.Parameter * @see java.util.Collections * @see java.util.List */ public abstract class Series extends WrapperList { /** * A marker for empty values to differentiate from non existing values * (null). */ public static final Object EMPTY_VALUE = new Object(); /** * Returns an unmodifiable view of the specified series. Attempts to call a * modification method will throw an UnsupportedOperationException. * * @param series * The series for which an unmodifiable view should be returned. * @return The unmodifiable view of the specified series. */ @SuppressWarnings("unchecked") public static Series unmodifiableSeries( Series series) { if (Edition.CURRENT != Edition.GWT) { return new Form(java.util.Collections.unmodifiableList(series .getDelegate())); } return new Form((List) series.getDelegate()); } /** * Constructor. */ public Series() { super(); } /** * Constructor. * * @param initialCapacity * The initial list capacity. */ public Series(int initialCapacity) { super(initialCapacity); } /** * Constructor. * * @param delegate * The delegate list. */ public Series(List delegate) { super(delegate); } /** * Creates then adds a parameter at the end of the list. * * @param name * The parameter name. * @param value * The parameter value. * @return True (as per the general contract of the Collection.add method). */ public boolean add(String name, String value) { return add(createEntry(name, value)); } /** * Copies the parameters whose name is a key in the given map.
    * If a matching parameter is found, its value is put in the map.
    * If multiple values are found, a list is created and set in the map. * * @param params * The map controlling the copy. */ @SuppressWarnings("unchecked") public void copyTo(Map params) { Parameter param; Object currentValue = null; for (final Iterator iter = iterator(); iter.hasNext();) { param = iter.next(); if (params.containsKey(param.getName())) { currentValue = params.get(param.getName()); if (currentValue != null) { List values = null; if (currentValue instanceof List) { // Multiple values already found for this entry values = (List) currentValue; } else { // Second value found for this entry // Create a list of values values = new ArrayList(); values.add(currentValue); params.put(param.getName(), values); } if (param.getValue() == null) { values.add(Series.EMPTY_VALUE); } else { values.add(param.getValue()); } } else { if (param.getValue() == null) { params.put(param.getName(), Series.EMPTY_VALUE); } else { params.put(param.getName(), param.getValue()); } } } } } /** * Creates a new entry. * * @param name * The name of the entry. * @param value * The value of the entry. * @return A new entry. */ public abstract E createEntry(String name, String value); /** * Creates a new series. * * @param delegate * Optional delegate series. * @return A new series. */ public abstract Series createSeries(List delegate); /** * Tests the equality of two string, potentially null, which a case * sensitivity flag. * * @param value1 * The first value. * @param value2 * The second value. * @param ignoreCase * Indicates if the test should be case insensitive. * @return True if both values are equal. */ private boolean equals(String value1, String value2, boolean ignoreCase) { boolean result = (value1 == value2); if (!result) { if ((value1 != null) && (value2 != null)) { if (ignoreCase) { result = value1.equalsIgnoreCase(value2); } else { result = value1.equals(value2); } } } return result; } /** * Returns the first parameter found with the given name. * * @param name * The parameter name (case sensitive). * @return The first parameter found with the given name. */ public E getFirst(String name) { return getFirst(name, false); } /** * Returns the first parameter found with the given name. * * @param name * The parameter name. * @param ignoreCase * Indicates if the name comparison is case insensitive. * @return The first parameter found with the given name. */ public E getFirst(String name, boolean ignoreCase) { for (final E param : this) { if (equals(param.getName(), name, ignoreCase)) { return param; } } return null; } /** * Returns the value of the first parameter found with the given name. * * @param name * The parameter name (case sensitive). * @return The value of the first parameter found with the given name. */ public String getFirstValue(String name) { return getFirstValue(name, false); } /** * Returns the value of the first parameter found with the given name. * * @param name * The parameter name. * @param ignoreCase * Indicates if the name comparison is case sensitive. * @return The value of the first parameter found with the given name. */ public String getFirstValue(String name, boolean ignoreCase) { return getFirstValue(name, ignoreCase, null); } /** * Returns the value of the first parameter found with the given name. * * @param name * The parameter name. * @param ignoreCase * Indicates if the name comparison is case sensitive. * @param defaultValue * The default value to return if no matching parameter found or * if the parameter has a null value. * @return The value of the first parameter found with the given name or the * default value. */ public String getFirstValue(String name, boolean ignoreCase, String defaultValue) { String result = defaultValue; final Parameter param = getFirst(name, ignoreCase); if ((param != null) && (param.getValue() != null)) { result = param.getValue(); } return result; } /** * Returns the value of the first parameter found with the given name. * * @param name * The parameter name (case sensitive). * @param defaultValue * The default value to return if no matching parameter found or * if the parameter has a null value. * @return The value of the first parameter found with the given name or the * default value. */ public String getFirstValue(String name, String defaultValue) { return getFirstValue(name, false, defaultValue); } /** * Returns the set of parameter names (case sensitive). * * @return The set of parameter names. */ public Set getNames() { final Set result = new HashSet(); for (final Parameter param : this) { result.add(param.getName()); } return result; } /** * Returns the values of the parameters with a given name. If multiple * parameters with the same name are found, all values are concatenated and * separated by a comma (like for HTTP message headers). * * @param name * The parameter name (case insensitive). * @return The values of the parameters with a given name. */ public String getValues(String name) { return getValues(name, ",", true); } /** * Returns the parameter values with a given name. If multiple parameters * with the same name are found, all values are concatenated and separated * by the given separator. * * @param name * The parameter name. * @param separator * The separator character. * @param ignoreCase * Indicates if the name comparison is case sensitive. * @return The sequence of values. */ public String getValues(String name, String separator, boolean ignoreCase) { String result = null; StringBuilder sb = null; for (final E param : this) { if ((ignoreCase && param.getName().equalsIgnoreCase(name)) || param.getName().equals(name)) { if (sb == null) { if (result == null) { result = param.getValue(); } else { sb = new StringBuilder(); sb.append(result).append(separator).append( param.getValue()); } } else { sb.append(separator).append(param.getValue()); } } } if (sb != null) { result = sb.toString(); } return result; } /** * Returns an array of all the values associated to the given parameter * name. * * @param name * The parameter name to match. * @return The array of values. */ public String[] getValuesArray(String name) { return getValuesArray(name, false); } /** * Returns an array of all the values associated to the given parameter * name. * * @param name * The parameter name to match. * @param ignoreCase * Indicates if the name comparison is case sensitive. * @return The array of values. */ public String[] getValuesArray(String name, boolean ignoreCase) { List params = subList(name, ignoreCase); String[] result = new String[params.size()]; for (int i = 0; i < params.size(); i++) { result[i] = params.get(i).getValue(); } return result; } /** * Returns a map of name, value pairs. The order of the map keys is * respected based on the series order. When a name has multiple values, * only the first one is put in the map. * * @return The map of name, value pairs. */ public Map getValuesMap() { final Map result = new LinkedHashMap(); for (final Parameter param : this) { if (!result.containsKey(param.getName())) { result.put(param.getName(), param.getValue()); } } return result; } /** * Removes all the parameters with a given name. * * @param name * The parameter name (case sensitive). * @return True if the list changed. */ public boolean removeAll(String name) { return removeAll(name, false); } /** * Removes all the parameters with a given name. * * @param name * The parameter name. * @param ignoreCase * Indicates if the name comparison is case insensitive. * @return True if the list changed. */ public boolean removeAll(String name, boolean ignoreCase) { boolean changed = false; Parameter param = null; for (final Iterator iter = iterator(); iter.hasNext();) { param = iter.next(); if (equals(param.getName(), name, ignoreCase)) { iter.remove(); changed = true; } } return changed; } /** * Removes from this list the first entry whose name equals the specified * name ignoring the case. * * @param name * The name of the entries to be removed (case sensitive). * @return false if no entry has been removed, true otherwise. */ public boolean removeFirst(String name) { return removeFirst(name, false); } /** * Removes from this list the first entry whose name equals the specified * name ignoring the case or not. * * @param name * The name of the entries to be removed. * @param ignoreCase * Indicates if the name comparison is case insensitive. * @return false if no entry has been removed, true otherwise. */ public boolean removeFirst(String name, boolean ignoreCase) { boolean changed = false; Parameter param = null; for (final Iterator iter = iterator(); iter.hasNext() && !changed;) { param = iter.next(); if (equals(param.getName(), name, ignoreCase)) { iter.remove(); changed = true; } } return changed; } /** * Replaces the value of the first parameter with the given name and removes * all other parameters with the same name. The name matching is case * sensitive. * * @param name * The parameter name. * @param value * The value to set. * @return The parameter set or added. */ public E set(String name, String value) { return set(name, value, false); } /** * Replaces the value of the first parameter with the given name and removes * all other parameters with the same name. * * @param name * The parameter name. * @param value * The value to set. * @param ignoreCase * Indicates if the name comparison is case insensitive. * @return The parameter set or added. */ public E set(String name, String value, boolean ignoreCase) { E result = null; E param = null; boolean found = false; for (final Iterator iter = iterator(); iter.hasNext();) { param = iter.next(); if (equals(param.getName(), name, ignoreCase)) { if (found) { // Remove other entries with the same name iter.remove(); } else { // Change the value of the first matching entry found = true; param.setValue(value); result = param; } } } if (!found) { add(name, value); } return result; } /** * Returns a view of the portion of this list between the specified * fromIndex, inclusive, and toIndex, exclusive. * * @param fromIndex * The start position. * @param toIndex * The end position (exclusive). * @return The sub-list. */ @Override public Series subList(int fromIndex, int toIndex) { return createSeries(getDelegate().subList(fromIndex, toIndex)); } /** * Returns a list of all the values associated to the parameter name. * * @param name * The parameter name (case sensitive). * @return The list of values. */ public Series subList(String name) { return subList(name, false); } /** * Returns a list of all the values associated to the parameter name. * * @param name * The parameter name. * @param ignoreCase * Indicates if the name comparison is case insensitive. * @return The list of values. */ public Series subList(String name, boolean ignoreCase) { final Series result = createSeries(null); for (final E param : this) { if (equals(param.getName(), name, ignoreCase)) { result.add(param); } } return result; } } restlet-2.0.14/org.restlet/src/org/restlet/util/RouteList.java0000664000175000017500000001732311757206346025037 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.routing.Route; /** * Modifiable list of routes with some helper methods. Note that this class * implements the {@link List} interface using the Route class as the generic * type. This allows you to use an instance of this class as any other * {@link List}, in particular all the helper methods in {@link Collections}.
    *
    * Note that structural changes to this list are thread-safe, using an * underlying {@link CopyOnWriteArrayList}. * * @author Jerome Louvel * @see java.util.Collections * @see java.util.List */ @SuppressWarnings("deprecation") public final class RouteList extends WrapperList { /** The index of the last route used in the round robin mode. */ private volatile int lastIndex; /** * Constructor. */ public RouteList() { super(new CopyOnWriteArrayList()); this.lastIndex = -1; } /** * Constructor. * * @param delegate * The delegate list. */ public RouteList(List delegate) { super(new CopyOnWriteArrayList(delegate)); this.lastIndex = -1; } /** * Returns the best route match for a given call. * * @param request * The request to score. * @param response * The response to score. * @param requiredScore * The minimum score required to have a match. * @return The best route match or null. */ public Route getBest(Request request, Response response, float requiredScore) { Route result = null; float bestScore = 0F; float score; for (final Route current : this) { score = current.score(request, response); if ((score > bestScore) && (score >= requiredScore)) { bestScore = score; result = current; } } return result; } /** * Returns the first route match for a given call. * * @param request * The request to score. * @param response * The response to score. * @param requiredScore * The minimum score required to have a match. * @return The first route match or null. */ public Route getFirst(Request request, Response response, float requiredScore) { for (final Route current : this) { if (current.score(request, response) >= requiredScore) { return current; } } // No match found return null; } /** * Returns the last route match for a given call. * * @param request * The request to score. * @param response * The response to score. * @param requiredScore * The minimum score required to have a match. * @return The last route match or null. */ public synchronized Route getLast(Request request, Response response, float requiredScore) { for (int j = size() - 1; (j >= 0); j--) { final Route route = get(j); if (route.score(request, response) >= requiredScore) { return route; } } // No match found return null; } /** * Returns a next route match in a round robin mode for a given call. * * @param request * The request to score. * @param response * The response to score. * @param requiredScore * The minimum score required to have a match. * @return A next route or null. */ public synchronized Route getNext(Request request, Response response, float requiredScore) { if (!isEmpty()) { for (final int initialIndex = this.lastIndex++; initialIndex != this.lastIndex; this.lastIndex++) { if (this.lastIndex >= size()) { this.lastIndex = 0; } final Route route = get(this.lastIndex); if (route.score(request, response) >= requiredScore) { return route; } } } // No match found return null; } /** * Returns a random route match for a given call. Note that the current * implementation doesn't uniformly return routes unless they all score * above the required score. * * @param request * The request to score. * @param response * The response to score. * @param requiredScore * The minimum score required to have a match. * @return A random route or null. */ public synchronized Route getRandom(Request request, Response response, float requiredScore) { final int length = size(); if (length > 0) { int j = new Random().nextInt(length); Route route = get(j); if (route.score(request, response) >= requiredScore) { return route; } boolean loopedAround = false; do { if ((j == length) && (loopedAround == false)) { j = 0; loopedAround = true; } route = get(j++); if (route.score(request, response) >= requiredScore) { return route; } } while ((j < length) || !loopedAround); } // No match found return null; } /** * Removes all routes routing to a given target. * * @param target * The target Restlet to detach. */ public synchronized void removeAll(Restlet target) { for (int i = size() - 1; i >= 0; i--) { if (get(i).getNext() == target) { remove(i); } } } /** * Returns a view of the portion of this list between the specified * fromIndex, inclusive, and toIndex, exclusive. * * @param fromIndex * The start position. * @param toIndex * The end position (exclusive). * @return The sub-list. */ @Override public RouteList subList(int fromIndex, int toIndex) { return new RouteList(getDelegate().subList(fromIndex, toIndex)); } } restlet-2.0.14/org.restlet/src/org/restlet/util/ServiceList.java0000664000175000017500000001275511757206346025345 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import org.restlet.Context; import org.restlet.service.Service; /** * Modifiable list of services. * * @author Jerome Louvel */ public final class ServiceList extends WrapperList { /** The context. */ private volatile Context context; /** * Constructor. * * @param context * The context. */ public ServiceList(Context context) { super(new CopyOnWriteArrayList()); this.context = context; } @Override public void add(int index, Service service) { service.setContext(getContext()); super.add(index, service); } @Override public boolean add(Service service) { service.setContext(getContext()); return super.add(service); } @Override public boolean addAll(Collection services) { if (services != null) { for (Service service : services) { service.setContext(getContext()); } } return super.addAll(services); } @Override public boolean addAll(int index, Collection services) { if (services != null) { for (Service service : services) { service.setContext(getContext()); } } return super.addAll(index, services); } /** * Returns a service matching a given service class. * * @param * The service type. * @param clazz * The service class to match. * @return The matched service instance. */ @SuppressWarnings("unchecked") public T get(Class clazz) { for (Service service : this) { if (clazz.isAssignableFrom(service.getClass())) { return (T) service; } } return null; } /** * Returns the context. * * @return The context. */ public Context getContext() { return this.context; } /** * Sets the list of services. * * @param services * The list of services. */ public synchronized void set(List services) { clear(); if (services != null) { addAll(services); } } /** * Replaces or adds a service. The replacement is based on the service * class. * * @param newService * The new service to set. */ public synchronized void set(Service newService) { List services = new CopyOnWriteArrayList(); Service service; boolean replaced = false; for (int i = 0; (i < size()); i++) { service = get(i); if (service != null) { if (service.getClass().isAssignableFrom(newService.getClass())) { try { service.stop(); } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to stop service replaced", e); } services.add(newService); replaced = true; } else { services.add(service); } } } if (!replaced) { services.add(newService); } set(services); } /** * Sets the context. By default, it also updates the context of already * registered services. * * @param context * The context. */ public void setContext(Context context) { this.context = context; for (Service service : this) { service.setContext(context); } } /** * Starts each service. * * @throws Exception */ public void start() throws Exception { for (Service service : this) { service.start(); } } /** * Stops each service. * * @throws Exception */ public void stop() throws Exception { for (Service service : this) { service.stop(); } } } restlet-2.0.14/org.restlet/src/org/restlet/util/ServerList.java0000664000175000017500000001303611757206350025177 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.resource.Finder; /** * Modifiable list of server connectors. * * @author Jerome Louvel */ public final class ServerList extends WrapperList { /** The context. */ private volatile Context context; /** The next Restlet of added servers. */ private volatile Restlet next; /** * Constructor. * * @param context * The context. * @param next * The next Restlet of added servers. */ public ServerList(Context context, Restlet next) { super(new CopyOnWriteArrayList()); this.context = context; this.next = next; } /** * Adds a new server connector in the map supporting the given protocol. * * @param protocol * The connector protocol. * @return The added server. */ public Server add(Protocol protocol) { Server result = new Server(protocol, null, protocol.getDefaultPort(), getTarget()); add(result); return result; } /** * Adds a new server connector in the map supporting the given protocol on * the specified port. * * @param protocol * The connector protocol. * @param port * The listening port. * @return The added server. */ public Server add(Protocol protocol, int port) { Server result = new Server(protocol, null, port, getTarget()); add(result); return result; } /** * Adds a new server connector in the map supporting the given protocol on * the specified IP address and port. * * @param protocol * The connector protocol. * @param address * The optional listening IP address (useful if multiple IP * addresses available). * @param port * The listening port. * @return The added server. */ public Server add(Protocol protocol, String address, int port) { Server result = new Server(protocol, address, port, getTarget()); add(result); return result; } /** * Adds a server at the end of the list. * * @return True (as per the general contract of the Collection.add method). */ @Override public boolean add(Server server) { // Set the server's context, if the server does not have already one. if (server.getContext() == null) { server.setContext(getContext()); } server.setNext(getTarget()); return super.add(server); } /** * Returns the context. * * @return The context. */ public Context getContext() { return this.context; } /** * Returns the next Restlet. * * @return The next Restlet. */ public Restlet getNext() { return getTarget(); } /** * Returns the next Restlet. * * @return The next Restlet. * @deprecated Use the {@link #getNext()} method instead. */ @Deprecated public Restlet getTarget() { return this.next; } /** * Sets the context. * * @param context * The context. */ public void setContext(Context context) { this.context = context; } /** * Sets the next Restlet as a Finder for a given resource class. When the * call is delegated to the Finder instance, a new instance of the resource * class will be created and will actually handle the request. * * @param nextClass * The next resource class to attach. */ public void setNext(Class nextClass) { setTarget(new Finder(getContext(), nextClass)); } /** * Sets the next Restlet. * * @param next * The next Restlet. */ public void setNext(Restlet next) { setTarget(next); } /** * Sets the next Restlet. * * @param next * The next Restlet. * @deprecated Use the {@link #setNext(Restlet)} method instead. */ @Deprecated public void setTarget(Restlet next) { this.next = next; } } restlet-2.0.14/org.restlet/src/org/restlet/util/Couple.java0000664000175000017500000000660211757206346024332 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import org.restlet.engine.util.SystemUtils; /** * Relationship between two typed objects. * * @author Jerome Louvel * * @param * The first object's type. * @param * The second object's type. */ public class Couple { /** The first object. */ private volatile T first; /** The second object. */ private volatile U second; /** * Constructor. * * @param first * The first object. * @param second * The second object. */ public Couple(T first, U second) { this.first = first; this.second = second; } @Override public boolean equals(Object other) { boolean result = (this == other); if (!result && (other instanceof Couple)) { Couple couple = (Couple) other; if (((couple.getFirst() == null) && (getFirst() == null)) || ((getFirst() != null) && getFirst().equals( couple.getFirst()))) { result = (((couple.getSecond() == null) && (getSecond() == null)) || ((getSecond() != null) && getSecond() .equals(couple.getSecond()))); } } return result; } /** * Returns the first object. * * @return The first object. */ public T getFirst() { return first; } /** * Returns the second object. * * @return The second object. */ public U getSecond() { return second; } /** * Sets the first object. * * @param first * The first object. */ public void setFirst(T first) { this.first = first; } /** * Sets the second object. * * @param second * The second object. */ public void setSecond(U second) { this.second = second; } /** {@inheritDoc} */ @Override public int hashCode() { return SystemUtils.hashCode(getFirst(), getSecond()); } @Override public String toString() { return "(" + getFirst() + "," + getSecond() + ")"; } } restlet-2.0.14/org.restlet/src/org/restlet/util/WrapperList.java0000664000175000017500000002413311757206346025356 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Vector; /** * List wrapper. Modifiable list that delegates all methods to a wrapped list. * This allows an easy sub-classing. By default, it wraps a thread-safe * {@link Vector} instance. * * @author Jerome Louvel * @see The decorator (aka * wrapper) pattern * @see java.util.Collections * @see java.util.List */ public class WrapperList implements List { /** The delegate list. */ private final List delegate; /** * Constructor. Uses a default initial capacity of 10 items. */ public WrapperList() { this(10); } /** * Constructor. * * @param initialCapacity * The initial list capacity. */ public WrapperList(int initialCapacity) { this(new Vector(initialCapacity)); } /** * Constructor. * * @param delegate * The delegate list. */ public WrapperList(List delegate) { this.delegate = delegate; } /** * Adds a element at the end of the list. * * @return True (as per the general contract of the Collection.add method). */ public boolean add(E element) { return getDelegate().add(element); } /** * Inserts the specified element at the specified position in this list. * * @param index * The insertion position. * @param element * The element to insert. */ public void add(int index, E element) { getDelegate().add(index, element); } /** * Appends all of the elements in the specified collection to the end of * this list. * * @param elements * The collection of elements to append. */ public boolean addAll(Collection elements) { return getDelegate().addAll(elements); } /** * Inserts all of the elements in the specified collection into this list at * the specified position. * * @param index * The insertion position. * @param elements * The collection of elements to insert. */ public boolean addAll(int index, Collection elements) { return getDelegate().addAll(index, elements); } /** * Removes all of the elements from this list. */ public void clear() { getDelegate().clear(); } /** * Returns true if this list contains the specified element. * * @param element * The element to find. * @return True if this list contains the specified element. */ public boolean contains(Object element) { return getDelegate().contains(element); } /** * Returns true if this list contains all of the elements of the specified * collection. * * @param elements * The collection of elements to find. * @return True if this list contains all of the elements of the specified * collection. */ public boolean containsAll(Collection elements) { return getDelegate().containsAll(elements); } /** * Compares the specified object with this list for equality. * * @param o * The object to be compared for equality with this list. * @return True if the specified object is equal to this list. */ @Override public boolean equals(Object o) { return getDelegate().equals(o); } /** * Returns the element at the specified position in this list. * * @param index * The element position. * @return The element at the specified position in this list. */ public E get(int index) { return getDelegate().get(index); } /** * Returns the delegate list. * * @return The delegate list. */ protected List getDelegate() { return this.delegate; } /** * Returns the hash code value for this list. * * @return The hash code value for this list. */ @Override public int hashCode() { return getDelegate().hashCode(); } /** * Returns the index in this list of the first occurrence of the specified * element, or -1 if this list does not contain this element. * * @param element * The element to find. * @return The index of the first occurrence. */ public int indexOf(Object element) { return getDelegate().indexOf(element); } /** * Returns true if this list contains no elements. */ public boolean isEmpty() { return getDelegate().isEmpty(); } /** * Returns an iterator over the elements in this list in proper sequence. * * @return An iterator over the elements in this list in proper sequence. */ public Iterator iterator() { return getDelegate().iterator(); } /** * Returns the index in this list of the last occurrence of the specified * element, or -1 if this list does not contain this element. */ public int lastIndexOf(Object element) { return getDelegate().lastIndexOf(element); } /** * Returns a list iterator of the elements in this list (in proper * sequence). * * @return A list iterator of the elements in this list (in proper * sequence). */ public ListIterator listIterator() { return getDelegate().listIterator(); } /** * Returns a list iterator of the elements in this list (in proper * sequence), starting at the specified position in this list. * * @param index * The starting position. */ public ListIterator listIterator(int index) { return getDelegate().listIterator(index); } /** * Removes the element at the specified position in this list. * * @return The removed element. */ public E remove(int index) { return getDelegate().remove(index); } /** * Removes the first occurrence in this list of the specified element. * * @return True if the list was changed. */ public boolean remove(Object element) { return getDelegate().remove(element); } /** * Removes from this list all the elements that are contained in the * specified collection. * * @param elements * The collection of element to remove. * @return True if the list changed. */ public boolean removeAll(Collection elements) { return getDelegate().removeAll(elements); } /** * RemovesRetains only the elements in this list that are contained in the * specified collection. * * @param elements * The collection of element to retain. * @return True if the list changed. */ public boolean retainAll(Collection elements) { return getDelegate().retainAll(elements); } /** * Replaces the element at the specified position in this list with the * specified element. * * @param index * The position of the element to replace. * @param element * The new element. */ public E set(int index, E element) { return getDelegate().set(index, element); } /** * Returns the number of elements in this list. * * @return The number of elements in this list. */ public int size() { return getDelegate().size(); } /** * Returns a view of the portion of this list between the specified * fromIndex, inclusive, and toIndex, exclusive. * * @param fromIndex * The start position. * @param toIndex * The end position (exclusive). * @return The sub-list. */ public List subList(int fromIndex, int toIndex) { return new WrapperList(getDelegate().subList(fromIndex, toIndex)); } /** * Returns an array containing all of the elements in this list in proper * sequence. * * @return An array containing all of the elements in this list in proper * sequence. */ public Object[] toArray() { return getDelegate().toArray(); } /** * Returns an array containing all of the elements in this list in proper * sequence; the runtime type of the returned array is that of the specified * array. * * @param a * The sample array. */ public T[] toArray(T[] a) { return getDelegate().toArray(a); } /** * Returns a string representation of the list. * * @return A string representation of the list. */ @Override public String toString() { return getDelegate().toString(); } } restlet-2.0.14/org.restlet/src/org/restlet/util/WrapperRepresentation.java0000664000175000017500000002201411757206346027441 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Date; import java.util.List; import org.restlet.data.CharacterSet; import org.restlet.data.Disposition; import org.restlet.data.Encoding; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.Tag; import org.restlet.representation.Representation; /** * Representation wrapper. Useful for application developer who need to enrich * the representation with application related properties and behavior. * * @see The decorator (aka * wrapper) pattern * @author Jerome Louvel */ public class WrapperRepresentation extends Representation { /** The wrapped representation. */ private final Representation wrappedRepresentation; /** * Constructor. * * @param wrappedRepresentation * The wrapped representation. */ public WrapperRepresentation(Representation wrappedRepresentation) { this.wrappedRepresentation = wrappedRepresentation; } @Override @Deprecated public boolean checkDigest() { return getWrappedRepresentation().checkDigest(); } @Override @Deprecated public boolean checkDigest(String algorithm) { return getWrappedRepresentation().checkDigest(algorithm); } @Override @Deprecated public org.restlet.data.Digest computeDigest(String algorithm) { return getWrappedRepresentation().computeDigest(algorithm); } @Override public long exhaust() throws IOException { return getWrappedRepresentation().exhaust(); } @Override public long getAvailableSize() { return getWrappedRepresentation().getAvailableSize(); } @Override public java.nio.channels.ReadableByteChannel getChannel() throws IOException { return getWrappedRepresentation().getChannel(); } @Override public CharacterSet getCharacterSet() { return getWrappedRepresentation().getCharacterSet(); } @Override public org.restlet.data.Digest getDigest() { return getWrappedRepresentation().getDigest(); } @Override public Disposition getDisposition() { return getWrappedRepresentation().getDisposition(); } @Override @Deprecated public String getDownloadName() { return getWrappedRepresentation().getDownloadName(); } @Override public List getEncodings() { return getWrappedRepresentation().getEncodings(); } @Override public Date getExpirationDate() { return getWrappedRepresentation().getExpirationDate(); } @SuppressWarnings("deprecation") @Override public Reference getIdentifier() { return getWrappedRepresentation().getIdentifier(); } @Override public List getLanguages() { return getWrappedRepresentation().getLanguages(); } @Override public Reference getLocationRef() { return getWrappedRepresentation().getLocationRef(); } @Override public MediaType getMediaType() { return getWrappedRepresentation().getMediaType(); } @Override public Date getModificationDate() { return getWrappedRepresentation().getModificationDate(); } @Override public org.restlet.data.Range getRange() { return getWrappedRepresentation().getRange(); } @Override public Reader getReader() throws IOException { return getWrappedRepresentation().getReader(); } @Override public long getSize() { return getWrappedRepresentation().getSize(); } @Override public InputStream getStream() throws IOException { return getWrappedRepresentation().getStream(); } @Override public Tag getTag() { return getWrappedRepresentation().getTag(); } @Override public String getText() throws IOException { return getWrappedRepresentation().getText(); } /** * Returns the wrapped representation. * * @return The wrapped representation. */ public Representation getWrappedRepresentation() { return this.wrappedRepresentation; } @Override public boolean isAvailable() { return getWrappedRepresentation().isAvailable(); } @Override @Deprecated public boolean isDownloadable() { return getWrappedRepresentation().isDownloadable(); } @Override public boolean isTransient() { return getWrappedRepresentation().isTransient(); } @Override public void release() { getWrappedRepresentation().release(); } @Override public void setAvailable(boolean isAvailable) { getWrappedRepresentation().setAvailable(isAvailable); } @Override public void setCharacterSet(CharacterSet characterSet) { getWrappedRepresentation().setCharacterSet(characterSet); } @Override public void setDigest(org.restlet.data.Digest digest) { getWrappedRepresentation().setDigest(digest); } @Override public void setDisposition(Disposition disposition) { getWrappedRepresentation().setDisposition(disposition); } @Override @Deprecated public void setDownloadable(boolean downloadable) { getWrappedRepresentation().setDownloadable(downloadable); } @Override @Deprecated public void setDownloadName(String fileName) { getWrappedRepresentation().setDownloadName(fileName); } @Override public void setEncodings(List encodings) { getWrappedRepresentation().setEncodings(encodings); } @Override public void setExpirationDate(Date expirationDate) { getWrappedRepresentation().setExpirationDate(expirationDate); } @SuppressWarnings("deprecation") @Override public void setIdentifier(Reference identifier) { getWrappedRepresentation().setIdentifier(identifier); } @SuppressWarnings("deprecation") @Override public void setIdentifier(String identifierUri) { getWrappedRepresentation().setIdentifier(identifierUri); } @Override public void setLanguages(List languages) { getWrappedRepresentation().setLanguages(languages); } @Override public void setLocationRef(Reference location) { getWrappedRepresentation().setLocationRef(location); } @Override public void setLocationRef(String locationUri) { getWrappedRepresentation().setLocationRef(locationUri); } @Override public void setMediaType(MediaType mediaType) { getWrappedRepresentation().setMediaType(mediaType); } @Override public void setModificationDate(Date modificationDate) { getWrappedRepresentation().setModificationDate(modificationDate); } @Override public void setRange(org.restlet.data.Range range) { getWrappedRepresentation().setRange(range); } @Override public void setSize(long expectedSize) { getWrappedRepresentation().setSize(expectedSize); } @Override public void setTag(Tag tag) { getWrappedRepresentation().setTag(tag); } @Override public void setTransient(boolean isTransient) { getWrappedRepresentation().setTransient(isTransient); } @Override public void write(java.io.OutputStream outputStream) throws IOException { getWrappedRepresentation().write(outputStream); } @Override public void write(java.io.Writer writer) throws IOException { getWrappedRepresentation().write(writer); } @Override public void write(java.nio.channels.WritableByteChannel writableChannel) throws IOException { getWrappedRepresentation().write(writableChannel); } } restlet-2.0.14/org.restlet/src/org/restlet/Uniform.java0000664000175000017500000000442611757206350023542 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; /** * Uniform REST interface. "The central feature that distinguishes the REST * architectural style from other network-based styles is its emphasis on a * uniform interface between components. By applying the software engineering * principle of generality to the component interface, the overall system * architecture is simplified and the visibility of interactions is improved. * Implementations are decoupled from the services they provide, which * encourages independent evolvability." Roy T. Fielding * * @see Source * dissertation * @author Jerome Louvel */ public interface Uniform { /** * Handles a uniform call. It is important to realize that this interface * can be used either on the client-side or on the server-side. * * @param request * The request to handle. * @param response * The associated response. */ public void handle(Request request, Response response); } restlet-2.0.14/org.restlet/src/org/restlet/Component.java0000664000175000017500000005375711757206346024105 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ 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.RestletHelper; import org.restlet.engine.component.ComponentHelper; import org.restlet.engine.component.ComponentXmlParser; 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; import org.restlet.service.LogService; import org.restlet.service.StatusService; import org.restlet.util.ClientList; import org.restlet.util.ServerList; import org.restlet.util.ServiceList; /** * Restlet managing a set of Connectors, VirtualHosts, Services and * Applications. Applications are expected to be directly attached to virtual * hosts or to the internal router (see RIAP pseudo-protocol for usage). * Components also expose several services: access logging and status setting.
    *
    * From an architectural point of view, here is the REST definition: "A * component is an abstract unit of software instructions and internal state * 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 both online and 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://www.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: *
      *
    • "logService" to configure access logging.
    • *
    • "statusService" to provide common representations for exception status.
    • *
    * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @see Source * dissertation * * @author Jerome Louvel */ 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. */ 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; /** The default host. */ private volatile VirtualHost defaultHost; /** The helper provided by the implementation. */ private volatile RestletHelper helper; /** The modifiable list of virtual hosts. */ private final List hosts; /** * The private internal router that can be addressed via the RIAP client * connector. */ private volatile Router internalRouter; /** The modifiable list of security realms. */ private final List realms; /** The modifiable list of server connectors. */ private final ServerList servers; /** The list of services. */ private final ServiceList services; /** * Constructor. */ public Component() { super(); this.hosts = new CopyOnWriteArrayList(); this.clients = new ClientList(null); this.servers = new ServerList(null, this); this.realms = new CopyOnWriteArrayList(); this.services = new ServiceList(getContext()); if (Engine.getInstance() != null) { this.helper = new ComponentHelper(this); Context childContext = getContext().createChildContext(); this.defaultHost = new VirtualHost(childContext); this.internalRouter = new InternalRouter(childContext); this.services.add(new LogService()); getLogService().setContext(childContext); this.services.add(new StatusService()); getStatusService().setContext(childContext); this.clients.setContext(childContext); this.servers.setContext(childContext); } } /** * Constructor with the reference to the XML configuration file. * * @param xmlConfigRef * The URI reference to the XML configuration file. */ 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 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. */ public Component(Representation xmlConfigRepresentation) { this(); if (xmlConfigRepresentation != null) { new 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. */ public Component(String xmlConfigurationRef) { this((xmlConfigurationRef == null) ? null : new Reference( xmlConfigurationRef)); } /** * Returns a modifiable list of client connectors. * * @return A modifiable list of client connectors. */ public ClientList getClients() { return this.clients; } /** * Returns the default virtual host. * * @return The default virtual host. */ public VirtualHost getDefaultHost() { return this.defaultHost; } /** * Returns the helper provided by the implementation. * * @return The helper provided by the implementation. */ private RestletHelper getHelper() { return this.helper; } /** * Returns the modifiable list of virtual hosts. Note that the order of * virtual hosts in this list will be used to check the first one that * matches. * * @return The modifiable list of virtual hosts. */ public List getHosts() { return this.hosts; } /** * Returns the private internal router where Restlets like Applications can * be attached. Those Restlets can be addressed via the * {@link org.restlet.data.Protocol#RIAP} (Restlet Internal Access Protocol) * client connector. This is used to manage private, internal and optimized * access to local applications.
    *
    * The first use case is the modularization of a large application into * modules or layers. This can also be achieved using the * {@link Context#getServerDispatcher()} method, but the internal router is * easily addressable via an URI scheme and can be fully private to the * current Component.
    *
    * The second use case is the composition/mash-up of several representations * via the {@link org.restlet.ext.xml.Transformer} class for example. For * this you can leverage the XPath's document() function or the XSLT's * include and import elements with RIAP URIs. * * @return The private internal router. */ public Router getInternalRouter() { return this.internalRouter; } /** * Returns the global log service. On the first call, if no log service was * defined via the {@link #setLogService(LogService)} method, then a default * logger service is created. This service will be enabled by default and * has a logger name composed the "org.restlet." prefix followed by the * simple component class name (without packages), followed by the * ".LogService" suffix. * * @return The global log service. */ public LogService getLogService() { return getServices().get(LogService.class); } /** * Finds the realm with the given name. * * @param name * The name. * @return The realm found or null. */ public Realm getRealm(String name) { if (name != null) { for (Realm realm : getRealms()) { if (name.equals(realm.getName())) { return realm; } } } return null; } /** * Returns the modifiable list of security realms. * * @return The modifiable list of security realms. */ public List getRealms() { return realms; } /** * Returns the modifiable list of server connectors. * * @return The modifiable list of server connectors. */ public ServerList getServers() { return this.servers; } /** * Returns the modifiable list of services. * * @return The modifiable list of services. */ public ServiceList getServices() { return services; } /** * Returns the status service, enabled by default. * * @return The status service. */ public StatusService getStatusService() { return getServices().get(StatusService.class); } @Override public void handle(Request request, Response response) { super.handle(request, response); if (getHelper() != null) { getHelper().handle(request, response); } } /** * Sets the modifiable list of client connectors. This method clears the * current list and adds all entries in the parameter list. * * @param clients * A list of client connectors. */ public void setClients(ClientList clients) { synchronized (getClients()) { if (clients != getClients()) { getClients().clear(); if (clients != null) { getClients().addAll(clients); } } } } /** * Sets the default virtual host. * * @param defaultHost * The default virtual host. */ public void setDefaultHost(VirtualHost defaultHost) { this.defaultHost = defaultHost; } /** * Sets the modifiable list of virtual hosts. Note that the order of virtual * hosts in this list will be used to check the first one that matches. This * method clears the current list and adds all entries in the parameter * list. * * @param hosts * A list of virtual hosts. */ public void setHosts(List hosts) { synchronized (getHosts()) { if (hosts != getHosts()) { getHosts().clear(); if (hosts != null) { getHosts().addAll(hosts); } } } } /** * Sets the private internal router were Restlets like Applications can be * attached. * * @param internalRouter * The private internal router. * @see #getInternalRouter() */ public void setInternalRouter(Router internalRouter) { this.internalRouter = internalRouter; } /** * Sets the global log service. * * @param logService * The global log service. */ public void setLogService(LogService logService) { getServices().set(logService); } /** * Sets the list of realms. This method clears the current list and adds all * entries in the parameter list. * * @param realms * A list of realms. */ public void setRealms(List realms) { synchronized (getRealms()) { if (realms != getRealms()) { getRealms().clear(); if (realms != null) { getRealms().addAll(realms); } } } } /** * Sets the modifiable list of server connectors. This method clears the * current list and adds all entries in the parameter list. * * @param servers * A list of server connectors. */ public void setServers(ServerList servers) { synchronized (getServers()) { if (servers != getServers()) { getServers().clear(); if (servers != null) { getServers().addAll(servers); } } } } /** * Sets the status service. * * @param statusService * The status service. */ public void setStatusService(StatusService statusService) { getServices().set(statusService); } /** * Starts the component. First it starts all the connectors (clients then * servers), the routers, the services, the realms and then the component's * internal helper. Finally it calls the start method of the super class. * * @see #startClients() * @see #startServers() * @see #startRouters() * @see #startServices() * @see #startRealms() * @see #startHelper() */ @Override public synchronized void start() throws Exception { if (isStopped()) { startClients(); startServers(); startRouters(); startServices(); startRealms(); startHelper(); super.start(); } } /** * Starts the client connectors. * * @throws Exception */ protected synchronized void startClients() throws Exception { if (this.clients != null) { for (final Client client : this.clients) { client.start(); } } } /** * Starts the internal helper allowing incoming requests to be served. * * @throws Exception */ protected synchronized void startHelper() throws Exception { if (getHelper() != null) { getHelper().start(); } } /** * Starts the realms. * * @throws Exception */ protected synchronized void startRealms() throws Exception { if (this.realms != null) { for (Realm realm : this.realms) { realm.start(); } } } /** * Starts the virtual hosts and the internal router. * * @throws Exception */ protected synchronized void startRouters() throws Exception { if (this.internalRouter != null) { this.internalRouter.start(); } if (this.defaultHost != null) { this.defaultHost.start(); } for (VirtualHost host : getHosts()) { host.start(); } } /** * Starts the server connectors. * * @throws Exception */ protected synchronized void startServers() throws Exception { if (this.servers != null) { for (final Server server : this.servers) { server.start(); } } } /** * Starts the associated services. * * @throws Exception */ protected synchronized void startServices() throws Exception { getServices().start(); } /** * Stops the component. First it stops the component's internal helper, the * realms, the services, the routers and then stops all the connectors * (servers then clients) Finally it calls the stop method of the super * class. * * @see #stopHelper() * @see #stopRealms() * @see #stopServices() * @see #stopRouters() * @see #stopServers() * @see #stopClients() */ @Override public synchronized void stop() throws Exception { stopHelper(); stopRealms(); stopServices(); stopRouters(); stopServers(); stopClients(); super.stop(); } /** * Stops the client connectors. * * @throws Exception */ protected synchronized void stopClients() throws Exception { if (this.clients != null) { for (final Client client : this.clients) { client.stop(); } } } /** * Stops the internal helper allowing incoming requests to be served. * * @throws Exception */ protected synchronized void stopHelper() throws Exception { if (getHelper() != null) { getHelper().stop(); } } /** * Stops the realms. * * @throws Exception */ protected synchronized void stopRealms() throws Exception { if (this.realms != null) { for (Realm realm : this.realms) { realm.stop(); } } } /** * Stops the virtual hosts and the internal router. * * @throws Exception */ protected synchronized void stopRouters() throws Exception { for (VirtualHost host : getHosts()) { host.stop(); } if (this.defaultHost != null) { this.defaultHost.stop(); } if (this.internalRouter != null) { this.internalRouter.stop(); } } /** * Stops the server connectors. * * @throws Exception */ protected synchronized void stopServers() throws Exception { if (this.servers != null) { for (final Server server : this.servers) { server.stop(); } } } /** * Stops the associated services. * * @throws Exception */ protected synchronized void stopServices() throws Exception { getServices().stop(); } /** * Updates the component to take into account changes to the virtual hosts. * This method doesn't stop the connectors or the applications or Restlets * attached to the virtual hosts. It just updates the internal routes * between the virtual hosts and the attached Restlets or applications.
    */ public synchronized void updateHosts() throws Exception { getHelper().update(); } } restlet-2.0.14/org.restlet/src/org/restlet/security/0000775000175000017500000000000011757206350023121 5ustar jamespagejamespagerestlet-2.0.14/org.restlet/src/org/restlet/security/MethodAuthorizer.java0000664000175000017500000001247011757206346027272 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; /** * Authorizer based on authorized methods. Note that this authorizer makes the * difference between authenticated and anonymous users. * * @author Jerome Louvel */ public class MethodAuthorizer extends Authorizer { /** The modifiable list of methods authorized for anonymous users. */ private List anonymousMethods; /** The modifiable list of methods authorized for authenticated users. */ private List authenticatedMethods; /** * Default constructor. */ public MethodAuthorizer() { this(null); } /** * Constructor. * * @param identifier * The identifier unique within an application. */ public MethodAuthorizer(String identifier) { super(identifier); this.anonymousMethods = new CopyOnWriteArrayList(); this.authenticatedMethods = new CopyOnWriteArrayList(); } /** * Authorizes the request only if its method is one of the authorized * methods. * * @param request * The request sent. * @param response * The response to update. * @return True if the authorization succeeded. */ @Override public boolean authorize(Request request, Response response) { boolean authorized = false; if (request.getClientInfo().isAuthenticated()) { // Verify if the request method is one of the forbidden methods for (Method authenticatedMethod : getAuthenticatedMethods()) { authorized = authorized || request.getMethod().equals(authenticatedMethod); } } else { // Verify if the request method is one of the authorized methods for (Method authorizedMethod : getAnonymousMethods()) { authorized = authorized || request.getMethod().equals(authorizedMethod); } } return authorized; } /** * Returns the modifiable list of methods authorized for anonymous users. * * @return The modifiable list of methods authorized for anonymous users. */ public List getAnonymousMethods() { return anonymousMethods; } /** * Returns the modifiable list of methods authorized for authenticated * users. * * @return The modifiable list of methods authorized for authenticated * users. */ public List getAuthenticatedMethods() { return authenticatedMethods; } /** * Sets the modifiable list of methods authorized for anonymous users. This * method clears the current list and adds all entries in the parameter * list. * * @param anonymousMethods * A list of methods authorized for anonymous users. */ public void setAnonymousMethods(List anonymousMethods) { synchronized (getAnonymousMethods()) { if (anonymousMethods != getAnonymousMethods()) { getAnonymousMethods().clear(); if (anonymousMethods != null) { getAnonymousMethods().addAll(anonymousMethods); } } } } /** * Sets the modifiable list of methods authorized for authenticated users. * This method clears the current list and adds all entries in the parameter * list. * * @param authenticatedMethods * A list of methods authorized for authenticated users. */ public void setAuthenticatedMethods(List authenticatedMethods) { synchronized (getAuthenticatedMethods()) { if (authenticatedMethods != getAuthenticatedMethods()) { getAuthenticatedMethods().clear(); if (authenticatedMethods != null) { getAuthenticatedMethods().addAll(authenticatedMethods); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/security/Realm.java0000664000175000017500000001302611757206346025033 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.util.Series; /** * Security realm capable of providing an enroler and a verifier. * * @author Jerome Louvel */ public abstract class Realm { /** The name. */ private volatile String name; /** The modifiable series of parameters. */ private final Series parameters; /** * The enroler that can add the user roles based on user principals. */ private volatile Enroler enroler; /** * The verifier that can check the validity of the user credentials * associated to a request. */ private volatile Verifier verifier; /** Indicates if the realm was started. */ private volatile boolean started; /** * Constructor. */ public Realm() { this(null, null); } /** * Constructor. * * @param verifier * The verifier that can check the validity of the credentials * associated to a request. * * @param enroler * The enroler that can add the user roles based on user * principals. */ public Realm(Verifier verifier, Enroler enroler) { this.enroler = enroler; this.verifier = verifier; this.parameters = new Form(new CopyOnWriteArrayList()); this.started = false; } /** * Returns an enroler that can add the user roles based on user principals. * * @return An enroler. */ public Enroler getEnroler() { return enroler; } /** * Returns the name. * * @return The name. */ public String getName() { return name; } /** * Returns the modifiable series of parameters. A parameter is a pair * composed of a name and a value and is typically used for configuration * purpose, like Java properties. Note that multiple parameters with the * same name can be declared and accessed. * * @return The modifiable series of parameters. */ public Series getParameters() { return this.parameters; } /** * Returns a verifier that can check the validity of the credentials * associated to a request. * * @return A verifier. */ public Verifier getVerifier() { return this.verifier; } /** * Indicates if the realm is started. * * @return True if the realm is started. */ public boolean isStarted() { return this.started; } /** * Indicates if the realm is stopped. * * @return True if the realm is stopped. */ public boolean isStopped() { return !this.started; } /** * Sets an enroler that can add the user roles based on user principals. * * @param enroler * An enroler. */ public void setEnroler(Enroler enroler) { this.enroler = enroler; } /** * Sets the name. * * @param name * The name. */ public void setName(String name) { this.name = name; } /** * Sets the modifiable series of parameters. This method clears the current * series and adds all entries in the parameter series. * * @param parameters * A series of parameters. */ public void setParameters(Series parameters) { synchronized (getParameters()) { if (parameters != getParameters()) { getParameters().clear(); if (parameters != null) { getParameters().addAll(parameters); } } } } /** * Sets a verifier that can check the validity of the credentials associated * to a request. * * @param verifier * A local verifier. */ public void setVerifier(Verifier verifier) { this.verifier = verifier; } /** Starts the realm. */ public synchronized void start() throws Exception { this.started = true; } /** Stops the realm. */ public synchronized void stop() throws Exception { this.started = false; } @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/security/Enroler.java0000664000175000017500000000430211757206346025376 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.security.Principal; import org.restlet.data.ClientInfo; /** * Updates an authenticated client user with assigned roles. Typically, it is * invoked by an {@link Authenticator} after successful authentication to add * {@link Role} instances based on available {@link User}. * * @see Authenticator#getEnroler() * @see Authenticator#setEnroler(Enroler) * @see ClientInfo#getUser() * @see ClientInfo#getRoles() * @author Jerome Louvel */ public interface Enroler { /** * Attempts to update an authenticated client, with a {@link User} properly * defined, by adding the {@link Role} that are assigned to this user. Note * that principals could also be added to the {@link ClientInfo} if * necessary. The addition could also potentially be based on the presence * of {@link Principal}. * * @param clientInfo * The clientInfo to update. */ public void enrole(ClientInfo clientInfo); } restlet-2.0.14/org.restlet/src/org/restlet/security/Authenticator.java0000664000175000017500000001657111757206346026615 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.routing.Filter; /** * Filter authenticating the client sending the request. * * @author Jerome Louvel */ public abstract class Authenticator extends Filter { /** * Indicates if the authenticator is not required to succeed. In those * cases, the attached Restlet is invoked. */ private volatile boolean optional; /** * Invoked upon successful authentication to update the subject with new * principals. */ private volatile Enroler enroler; /** * Constructor setting the mode to "required". * * @param context * The context. * @see #Authenticator(Context, boolean) */ public Authenticator(Context context) { this(context, false); } /** * Constructor using the context's default enroler. * * @param context * The context. * @param optional * The authentication mode. * @see #Authenticator(Context, boolean, Enroler) */ public Authenticator(Context context, boolean optional) { this(context, optional, (context != null) ? context.getDefaultEnroler() : null); } /** * Constructor. * * @param context * The context. * @param optional * The authentication mode. * @param enroler * The enroler to invoke upon successful authentication. */ public Authenticator(Context context, boolean optional, Enroler enroler) { super(context); this.optional = optional; this.enroler = enroler; } /** * Attempts to authenticate the subject sending the request. * * @param request * The request sent. * @param response * The response to update. * @return True if the authentication succeeded. */ protected abstract boolean authenticate(Request request, Response response); /** * Handles the authentication by first invoking the * {@link #authenticate(Request, Response)} method. Then, depending on the * result and the mode set, it invokes the * {@link #authenticated(Request, Response)} or the * {@link #unauthenticated(Request, Response)} method. */ @Override protected int beforeHandle(Request request, Response response) { if (authenticate(request, response)) { return authenticated(request, response); } else if (isOptional()) { response.setStatus(Status.SUCCESS_OK); return CONTINUE; } else { return unauthenticated(request, response); } } /** * Invoked upon successful authentication. By default, it updates the * request's clientInfo and challengeResponse "authenticated" properties, * clears the existing challenge requests on the response, calls the enroler * and finally returns {@link Filter#CONTINUE}. * * @param request * The request sent. * @param response * The response to update. * @return The filter continuation code. */ @SuppressWarnings("deprecation") protected int authenticated(Request request, Response response) { // Update the challenge response accordingly if (request.getChallengeResponse() != null) { request.getChallengeResponse().setAuthenticated(true); } // Update the client info accordingly if (request.getClientInfo() != null) { request.getClientInfo().setAuthenticated(true); } // Clear previous challenge requests response.getChallengeRequests().clear(); // Add the roles for the authenticated subject if (getEnroler() != null) { getEnroler().enrole(request.getClientInfo()); } return CONTINUE; } /** * Invoked upon failed authentication. By default, it updates the request's * clientInfo and challengeResponse "authenticated" properties, and returns * {@link Filter#STOP}. * * @param request * The request sent. * @param response * The response to update. * @return The filter continuation code. */ @SuppressWarnings("deprecation") protected int unauthenticated(Request request, Response response) { if (isOptional()) { response.setStatus(Status.SUCCESS_OK); return CONTINUE; } // Update the challenge response accordingly if (request.getChallengeResponse() != null) { request.getChallengeResponse().setAuthenticated(false); } // Update the client info accordingly if (request.getClientInfo() != null) { request.getClientInfo().setAuthenticated(false); } // Stop the filtering chain return STOP; } /** * Returns the enroler invoked upon successful authentication to update the * subject with new principals. Typically new {@link Role} are added based * on the available {@link User} instances available. * * @return The enroler invoked upon successful authentication */ public Enroler getEnroler() { return enroler; } /** * Indicates if the authenticator is not required to succeed. In those * cases, the attached Restlet is invoked. * * @return True if the authentication success is optional. */ public boolean isOptional() { return optional; } /** * Sets the enroler invoked upon successful authentication. * * @param enroler * The enroler invoked upon successful authentication. */ public void setEnroler(Enroler enroler) { this.enroler = enroler; } /** * Indicates if the authenticator is not required to succeed. In those * cases, the attached Restlet is invoked. * * @param optional * True if the authentication success is optional. */ public void setOptional(boolean optional) { this.optional = optional; } } restlet-2.0.14/org.restlet/src/org/restlet/security/ChallengeAuthenticator.java0000664000175000017500000002654211757206346030417 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.ClientInfo; import org.restlet.data.Status; /** * Authenticator based on a challenge scheme. This is typically used to support * the HTTP BASIC and DIGEST challenge schemes. * * @see ChallengeScheme * @see ChallengeRequest * @see ChallengeResponse * @see User * Guide - Authentication * @author Jerome Louvel */ public class ChallengeAuthenticator extends Authenticator { /** The authentication realm. */ private volatile String realm; /** * Indicates if a new challenge should be sent when invalid credentials are * received (true by default to conform to HTTP recommendations). */ private volatile boolean rechallenging; /** The expected challenge scheme. */ private final ChallengeScheme scheme; /** The credentials verifier. */ private volatile Verifier verifier; /** * Constructor using the context's default verifier. * * @param context * The context. * @param optional * Indicates if the authentication success is optional. * @param challengeScheme * The authentication scheme to use. * @param realm * The authentication realm. * * @see #ChallengeAuthenticator(Context, boolean, ChallengeScheme, String, * Verifier) */ public ChallengeAuthenticator(Context context, boolean optional, ChallengeScheme challengeScheme, String realm) { this(context, optional, challengeScheme, realm, (context != null) ? context.getDefaultVerifier() : null); } /** * Constructor. * * @param context * The context. * @param optional * Indicates if the authentication success is optional. * @param challengeScheme * The authentication scheme to use. * @param realm * The authentication realm. * @param verifier * The credentials verifier. */ public ChallengeAuthenticator(Context context, boolean optional, ChallengeScheme challengeScheme, String realm, Verifier verifier) { super(context, optional); this.realm = realm; this.rechallenging = true; this.scheme = challengeScheme; this.verifier = verifier; } /** * Constructor setting the optional property to false. * * @param context * The context. * @param challengeScheme * The authentication scheme to use. * @param realm * The authentication realm. * @see #ChallengeAuthenticator(Context, boolean, ChallengeScheme, String, * Verifier) */ public ChallengeAuthenticator(Context context, ChallengeScheme challengeScheme, String realm) { this(context, false, challengeScheme, realm); } /** * Authenticates the call, relying on the verifier to check the credentials * provided (in general an identifier + secret couple). If the credentials * are valid, the next Restlet attached is invoked.
    *
    * If the credentials are missing, then * {@link #challenge(Response, boolean)} is invoked.
    *
    * If the credentials are invalid and if the "rechallenge" property is true * then {@link #challenge(Response, boolean)} is invoked. Otherwise, * {@link #forbid(Response)} is invoked.
    *
    * If the credentials are stale, then {@link #challenge(Response, boolean)} * is invoked with the "stale" parameter to true.
    *
    * At the end of the process, the * {@link ChallengeResponse#setAuthenticated(boolean)} and * {@link ClientInfo#setAuthenticated(boolean)} methods are invoked. */ @Override protected boolean authenticate(Request request, Response response) { boolean result = false; final boolean loggable = getLogger().isLoggable(Level.FINE); if (getVerifier() != null) { switch (getVerifier().verify(request, response)) { case Verifier.RESULT_VALID: // Valid credentials provided result = true; if (loggable) { ChallengeResponse challengeResponse = request .getChallengeResponse(); if (challengeResponse != null) { getLogger().fine( "Authentication succeeded. Valid credentials provided for identifier: " + request.getChallengeResponse() .getIdentifier() + "."); } else { getLogger() .fine("Authentication succeeded. Valid credentials provided."); } } break; case Verifier.RESULT_MISSING: // No credentials provided if (loggable) { getLogger().fine( "Authentication failed. No credentials provided."); } if (!isOptional()) { challenge(response, false); } break; case Verifier.RESULT_INVALID: // Invalid credentials provided if (loggable) { getLogger() .fine("Authentication failed. Invalid credentials provided."); } if (!isOptional()) { if (isRechallenging()) { challenge(response, false); } else { forbid(response); } } break; case Verifier.RESULT_STALE: if (loggable) { getLogger() .fine("Authentication failed. Stale credentials provided."); } if (!isOptional()) { challenge(response, true); } break; case Verifier.RESULT_UNKNOWN: if (loggable) { getLogger().fine( "Authentication failed. Identifier is unknown."); } if (!isOptional()) { if (isRechallenging()) { challenge(response, false); } else { forbid(response); } } break; } } else { getLogger().warning("Authentication failed. No verifier provided."); } return result; } /** * Challenges the client by adding a challenge request to the response and * by setting the status to {@link Status#CLIENT_ERROR_UNAUTHORIZED}. * * @param response * The response to update. * @param stale * Indicates if the new challenge is due to a stale response. */ public void challenge(Response response, boolean stale) { response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); response.getChallengeRequests().add(createChallengeRequest(stale)); } /** * Creates a new challenge request. * * @param stale * Indicates if the new challenge is due to a stale response. * @return A new challenge request. */ protected ChallengeRequest createChallengeRequest(boolean stale) { return new ChallengeRequest(getScheme(), getRealm()); } /** * Rejects the call due to a failed authentication or authorization. This * can be overridden to change the default behavior, for example to display * an error page. By default, if authentication is required, the challenge * method is invoked, otherwise the call status is set to * CLIENT_ERROR_FORBIDDEN. * * @param response * The reject response. */ public void forbid(Response response) { response.setStatus(Status.CLIENT_ERROR_FORBIDDEN); } /** * Returns the authentication realm. * * @return The authentication realm. */ public String getRealm() { return this.realm; } /** * Returns the authentication challenge scheme. * * @return The authentication challenge scheme. */ public ChallengeScheme getScheme() { return scheme; } /** * Returns the credentials verifier. * * @return The credentials verifier. */ public Verifier getVerifier() { return verifier; } /** * Indicates if a new challenge should be sent when invalid credentials are * received (true by default to conform to HTTP recommendations). If set to * false, upon reception of invalid credentials, the method * {@link #forbid(Response)} will be called. * * @return True if invalid credentials result in a new challenge. */ public boolean isRechallenging() { return this.rechallenging; } /** * Sets the authentication realm. * * @param realm * The authentication realm. */ public void setRealm(String realm) { this.realm = realm; } /** * Indicates if a new challenge should be sent when invalid credentials are * received. * * @param rechallenging * True if invalid credentials result in a new challenge. * @see #isRechallenging() */ public void setRechallenging(boolean rechallenging) { this.rechallenging = rechallenging; } /** * Sets the credentials verifier. * * @param verifier * The credentials verifier. */ public void setVerifier(Verifier verifier) { this.verifier = verifier; } } restlet-2.0.14/org.restlet/src/org/restlet/security/MapVerifier.java0000664000175000017500000000570511757206346026211 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Verifier that stores its local secrets in a map indexed by the identifier. * Note that this verifier isn't very secure by itself. * * @author Jerome Louvel */ public class MapVerifier extends LocalVerifier { /** The map of local secrets. */ private final ConcurrentMap localSecrets; /** * Constructor. */ public MapVerifier() { this(new ConcurrentHashMap()); } /** * Constructor. * * @param localSecrets * The map of local secrets. */ public MapVerifier(ConcurrentMap localSecrets) { this.localSecrets = localSecrets; } @Override public char[] getLocalSecret(String identifier) { return (identifier == null) ? null : getLocalSecrets().get(identifier); } /** * Returns the map of local secrets. * * @return The map of local secrets. */ public ConcurrentMap getLocalSecrets() { return localSecrets; } /** * Sets the modifiable map of local secrets. This method clears the current * map and puts all entries in the parameter map. * * @param localSecrets * A map of local secrets. */ public void setLocalSecrets(Map localSecrets) { synchronized (getLocalSecrets()) { if (localSecrets != getLocalSecrets()) { getLocalSecrets().clear(); if (localSecrets != null) { getLocalSecrets().putAll(localSecrets); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/security/Authorizer.java0000664000175000017500000001223311757206346026126 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ClientInfo; import org.restlet.data.Status; import org.restlet.routing.Filter; /** * Filter authorizing requests. * * @see User * Guide - Authorization * @author Jerome Louvel */ public abstract class Authorizer extends Filter { /** Authorizer returning true all the time. */ public static final Authorizer ALWAYS = new Authorizer() { @Override public boolean authorize(Request request, Response response) { return true; } }; /** * Authorizer returning true for all authenticated requests. For * unauthenticated requests, it sets the response's status to * {@link Status#CLIENT_ERROR_UNAUTHORIZED} instead of the default * {@link Status#CLIENT_ERROR_FORBIDDEN}. * * @see ClientInfo#isAuthenticated() */ public static final Authorizer AUTHENTICATED = new Authorizer() { @Override public boolean authorize(Request request, Response response) { return request.getClientInfo().isAuthenticated(); } @Override protected int unauthorized(Request request, Response response) { response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); return STOP; } }; /** Authorizer returning false all the time. */ public static final Authorizer NEVER = new Authorizer() { @Override public boolean authorize(Request request, Response response) { return false; } }; /** The identifier unique within an application. */ private volatile String identifier; /** * Default constructor. */ public Authorizer() { } /** * Constructor. * * @param identifier * The identifier unique within an application. */ public Authorizer(String identifier) { this.identifier = identifier; } /** * Attempts to authorize the request. * * @param request * The request sent. * @param response * The response to update. * @return True if the authorization succeeded. */ protected abstract boolean authorize(Request request, Response response); /** * Invoked upon successful authorization. Returns {@link Filter#CONTINUE} by * default. * * @param request * The request sent. * @param response * The response to update. * @return The filter continuation code. */ protected int authorized(Request request, Response response) { return CONTINUE; } @Override protected int beforeHandle(Request request, Response response) { if (authorize(request, response)) { return authorized(request, response); } return unauthorized(request, response); } /** * Returns the identifier unique within an application. * * @return The identifier unique within an application. */ public String getIdentifier() { return identifier; } /** * Sets the identifier unique within an application. * * @param identifier * The identifier unique within an application. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Invoked upon failed authorization. Sets the status to * {@link Status#CLIENT_ERROR_FORBIDDEN} and returns {@link Filter#STOP} by * default. * * @param request * The request sent. * @param response * The response to update. * @return The filter continuation code. */ protected int unauthorized(Request request, Response response) { response.setStatus(Status.CLIENT_ERROR_FORBIDDEN); return STOP; } } restlet-2.0.14/org.restlet/src/org/restlet/security/package.html0000664000175000017500000000032011757206350025375 0ustar jamespagejamespage Classes related to security.

    @since Restlet 2.0 @see User Guide - Security package restlet-2.0.14/org.restlet/src/org/restlet/security/SecretVerifier.java0000664000175000017500000001227611757206346026722 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ClientInfo; /** * Verifier of identifier/secret couples. By default, it extracts the identifier * and the secret from the {@link ChallengeResponse}. If the verification is * successful, it automatically adds a new {@link User} for the given * identifier. * * @author Jerome Louvel */ public abstract class SecretVerifier implements Verifier { /** * Compares that two secrets are equal. * * @param secret1 * The input secret. * @param secret2 * The output secret. * @return True if both are equal. */ public static boolean compare(char[] secret1, char[] secret2) { boolean result = false; if ((secret1 == null) || (secret2 == null)) { // Check if both are null result = (secret1 == secret2); } else { // None is null if (secret1.length == secret2.length) { boolean equals = true; for (int i = 0; (i < secret1.length) && equals; i++) { equals = (secret1[i] == secret2[i]); } result = equals; } } return result; } /** * Returns the user identifier. * * @param request * The request to inspect. * @param response * The response to inspect. * @return The user identifier. */ protected String getIdentifier(Request request, Response response) { return request.getChallengeResponse().getIdentifier(); } /** * Returns the secret provided by the user. * * @param request * The request to inspect. * @param response * The response to inspect. * @return The secret provided by the user. */ protected char[] getSecret(Request request, Response response) { return request.getChallengeResponse().getSecret(); } /** * Verifies that the proposed secret is correct for the specified request. * By default, it compares the inputSecret of the request's authentication * response with the one obtain by the {@link ChallengeResponse#getSecret()} * method and sets the {@link org.restlet.security.User} instance of the * request's {@link ClientInfo} if successful. * * @param request * The request to inspect. * @param response * The response to inspect. * @return True if the proposed secret was correct and the subject updated. */ public int verify(Request request, Response response) { int result = RESULT_VALID; if (request.getChallengeResponse() == null) { result = RESULT_MISSING; } else { String identifier = getIdentifier(request, response); char[] secret = getSecret(request, response); try { if (verify(identifier, secret)) { request.getClientInfo().setUser(new User(identifier)); } else { result = RESULT_INVALID; } } catch (IllegalArgumentException iae) { // The identifier is unknown. result = RESULT_UNKNOWN; } } return result; } /** * Verifies that the identifier/secret couple is valid. It throws an * IllegalArgumentException in case the identifier is either null or does * not identify a user. * * @param identifier * The user identifier to match. * @param secret * The provided secret to verify. * @return true if the identifier/secret couple is valid. * @throws IllegalArgumentException * In case the identifier is unknown. */ public abstract boolean verify(String identifier, char[] secret) throws IllegalArgumentException; } restlet-2.0.14/org.restlet/src/org/restlet/security/Role.java0000664000175000017500000001306011757206346024672 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.security.Principal; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Application specific role. Common examples are "administrator", "user", * "anonymous", "supervisor". Note that for reusability purpose, it is * recommended that those role don't reflect an actual organization, but more * the functional requirements of your application. * * @author Jerome Louvel */ public class Role implements Principal { /** * Unmodifiable role that covers all existing roles. Its name is "*" by * convention. */ public static final Role ALL = new Role("*", "Role that covers all existing roles.") { @Override public void setDescription(String description) { throw new IllegalStateException("Unmodifiable role"); } @Override public void setName(String name) { throw new IllegalStateException("Unmodifiable role"); } }; /** The modifiable list of child roles. */ private final List childRoles; /** The description. */ private volatile String description; /** The name. */ private volatile String name; /** * Default constructor. */ public Role() { this(null, null); } /** * Constructor. * * @param name * The name. * @param description * The description. */ public Role(String name, String description) { this.name = name; this.description = description; this.childRoles = new CopyOnWriteArrayList(); } @Override public boolean equals(Object target) { boolean result = false; if (this.name == null) { return target == null; } if (target instanceof Role) { Role r = (Role) target; // Test equality of names and child roles. result = this.name.equals(r.getName()) && getChildRoles().size() == r.getChildRoles().size(); if (result && !getChildRoles().isEmpty()) { for (int i = 0; result && i < getChildRoles().size(); i++) { result = getChildRoles().get(i).equals( r.getChildRoles().get(i)); } } } return result; } /** * Returns the modifiable list of child roles. * * @return The modifiable list of child roles. */ public List getChildRoles() { return childRoles; } /** * Returns the description. * * @return The description. */ public String getDescription() { return description; } /** * Returns the name. * * @return The name. */ public String getName() { return name; } @Override public int hashCode() { int result; if (name == null) { result = super.hashCode(); } else if (getChildRoles().isEmpty()) { result = name.hashCode(); } else { StringBuilder sb = new StringBuilder(name).append("("); for (Role role : getChildRoles()) { sb.append(role.hashCode()).append("-"); } sb.append(")"); result = sb.toString().hashCode(); } return result; } /** * Sets the modifiable list of child roles. This method clears the current * list and adds all entries in the parameter list. * * @param childRoles * A list of child roles. */ public void setChildRoles(List childRoles) { synchronized (getChildRoles()) { if (childRoles != getChildRoles()) { getChildRoles().clear(); if (childRoles != null) { getChildRoles().addAll(childRoles); } } } } /** * Sets the description. * * @param description * The description. */ public void setDescription(String description) { this.description = description; } /** * Sets the name. * * @param name * The name. */ public void setName(String name) { this.name = name; } @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/security/Group.java0000664000175000017500000001356211757206350025067 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Group that contains member groups and users. * * @author Jerome Louvel */ public class Group { /** The description. */ private volatile String description; /** * Indicates if the roles of the parent group should be inherited. Those * roles indirectly cover the granted or denied permissions. */ private volatile boolean inheritingRoles; /** The modifiable list of child groups. */ private final List memberGroups; /** The modifiable list of members user references. */ private final List memberUsers; /** The display name. */ private volatile String name; /** * Default constructor. Note that roles are inherited by default. */ public Group() { this(null, null); } /** * Constructor. Note that roles are inherited by default. * * @param name * The display name. * @param description * The description. */ public Group(String name, String description) { this(name, description, true); } /** * Constructor. * * @param name * The display name. * @param description * The description. * @param inheritingRoles * Indicates if the roles of the parent group should be * inherited. */ public Group(String name, String description, boolean inheritingRoles) { this.name = name; this.description = description; this.inheritingRoles = inheritingRoles; this.memberGroups = new CopyOnWriteArrayList(); this.memberUsers = new CopyOnWriteArrayList(); } /** * Returns the description. * * @return The description */ public String getDescription() { return this.description; } /** * Returns the modifiable list of member groups. * * @return The modifiable list of member groups. */ public List getMemberGroups() { return memberGroups; } public List getMemberUsers() { return memberUsers; } /** * Returns the display name. * * @return The display name. */ public String getName() { return this.name; } /** * Indicates if the roles of the parent group should be inherited. Those * roles indirectly cover the granted or denied permissions. * * @return True if the roles of the parent group should be inherited. */ public boolean isInheritingRoles() { return inheritingRoles; } /** * Sets the description. * * @param description * The description. */ public void setDescription(String description) { this.description = description; } /** * Indicates if the roles of the parent group should be inherited. Those * roles indirectly cover the granted or denied permissions. * * @param inheritingRoles * True if the roles of the parent group should be inherited. */ public void setInheritingRoles(boolean inheritingRoles) { this.inheritingRoles = inheritingRoles; } /** * Sets the modifiable list of member groups. This method clears the current * list and adds all entries in the parameter list. * * @param memberGroups * A list of member groups. */ public void setMemberGroups(List memberGroups) { synchronized (getMemberGroups()) { if (memberGroups != getMemberGroups()) { getMemberGroups().clear(); if (memberGroups != null) { getMemberGroups().addAll(memberGroups); } } } } /** * Sets the modifiable list of member user references. This method clears * the current list and adds all entries in the parameter list. * * @param memberUsers * A list of member user references. */ public void setMemberUsers(List memberUsers) { synchronized (getMemberUsers()) { if (memberUsers != getMemberUsers()) { getMemberUsers().clear(); if (memberUsers != null) { getMemberUsers().addAll(memberUsers); } } } } /** * Sets the display name. * * @param name * The display name. */ public void setName(String name) { this.name = name; } @Override public String toString() { return getName(); } } restlet-2.0.14/org.restlet/src/org/restlet/security/RoleAuthorizer.java0000664000175000017500000001206511757206346026753 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.Request; import org.restlet.Response; /** * Authorizer based on authorized and forbidden roles. Note that if no role is * added to the "authorizedRoles" list, then only the "forbiddenRoles" list is * considered. * * @author Jerome Louvel */ public class RoleAuthorizer extends Authorizer { /** The modifiable list of authorized roles. */ private List authorizedRoles; /** The modifiable list of forbidden roles. */ private List forbiddenRoles; /** * Default constructor. */ public RoleAuthorizer() { this(null); } /** * Constructor. * * @param identifier * The identifier unique within an application. */ public RoleAuthorizer(String identifier) { super(identifier); this.authorizedRoles = new CopyOnWriteArrayList(); this.forbiddenRoles = new CopyOnWriteArrayList(); } /** * Authorizes the request only if its subject is in one of the authorized * roles and in none of the forbidden ones. * * @param request * The request sent. * @param response * The response to update. * @return True if the authorization succeeded. */ @Override public boolean authorize(Request request, Response response) { boolean authorized = false; boolean forbidden = false; // Verify if the subject is in one of the authorized roles if (getAuthorizedRoles().isEmpty()) { authorized = true; } else { for (Role authorizedRole : getAuthorizedRoles()) { authorized = authorized || request.getClientInfo().getRoles().contains( authorizedRole); } } // Verify if the subject is in one of the forbidden roles for (Role forbiddenRole : getForbiddenRoles()) { forbidden = forbidden || request.getClientInfo().getRoles().contains( forbiddenRole); } return authorized && !forbidden; } /** * Returns the modifiable list of authorized roles. * * @return The modifiable list of authorized roles. */ public List getAuthorizedRoles() { return authorizedRoles; } /** * Returns the modifiable list of forbidden roles. * * @return The modifiable list of forbidden roles. */ public List getForbiddenRoles() { return forbiddenRoles; } /** * Sets the modifiable list of authorized roles. This method clears the * current list and adds all entries in the parameter list. * * @param authorizedRoles * A list of authorized roles. */ public void setAuthorizedRoles(List authorizedRoles) { synchronized (getAuthorizedRoles()) { if (authorizedRoles != getAuthorizedRoles()) { getAuthorizedRoles().clear(); if (authorizedRoles != null) { getAuthorizedRoles().addAll(authorizedRoles); } } } } /** * Sets the modifiable list of forbidden roles. This method clears the * current list and adds all entries in the parameter list. * * @param forbiddenRoles * A list of forbidden roles. */ public void setForbiddenRoles(List forbiddenRoles) { synchronized (getForbiddenRoles()) { if (forbiddenRoles != getForbiddenRoles()) { getForbiddenRoles().clear(); if (forbiddenRoles != null) { getForbiddenRoles().addAll(forbiddenRoles); } } } } } restlet-2.0.14/org.restlet/src/org/restlet/security/Verifier.java0000664000175000017500000000447311757206346025554 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import org.restlet.Request; import org.restlet.Response; /** * Verifies the credentials provided by a client user sending a request. * * @author Jerome Louvel */ public interface Verifier { /** Invalid credentials provided. */ public final static int RESULT_INVALID = -1; /** No credentials provided. */ public final static int RESULT_MISSING = 0; /** Stale credentials provided. */ public final static int RESULT_STALE = 1; /** Unsupported credentials. */ public final static int RESULT_UNSUPPORTED = 3; /** Unknown user. */ public final static int RESULT_UNKNOWN = 5; /** Valid credentials provided. */ public final static int RESULT_VALID = 4; /** * Attempts to verify the credentials provided by the client user sending * the request. * * @param request * The request sent. * @param response * The response to update. * @return Result of the verification based on the RESULT_* constants. */ public int verify(Request request, Response response); } restlet-2.0.14/org.restlet/src/org/restlet/security/Guard.java0000664000175000017500000004476511757206346025053 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.ClientInfo; import org.restlet.data.Status; import org.restlet.engine.security.AuthenticatorUtils; import org.restlet.routing.Filter; import org.restlet.util.Resolver; /** * Filter guarding the access to an attached Restlet. More concretely, it guards * from unauthenticated and unauthorized requests, providing facilities to check * credentials such as passwords. It is also a relatively generic class which * can work with several challenge schemes such as HTTP Basic and HTTP Digest. *

    * Here are the processing steps of a Guard when a request reaches it: *

      *
    1. It first attempts to authenticate it, i.e. to make sure that the * challenge scheme used is supported and that the credentials given by the * client (such as a login and password) are valid. The actual implementation of * the authentication is delegated to the matching authentication helper. The * result of this authentication can be: *
        *
      1. Valid: the authentication credentials are valid, the right scheme was * used and the credentials could be verified by calling back the checkSecret() * method on Guard. Here are the next steps: *
          *
        1. The authorize() method is called and if authorization is given the * accept() method is invoked, which delegates to the attached Restlet or * Resource by default. Otherwise, the forbid method is called, which sets the * response status to {@link Status#CLIENT_ERROR_FORBIDDEN} (403).
        2. *
        *
      2. *
      3. Missing: no credentials could be found, the challenge() method is invoked * which delegates to the matching authenticator helper.
      4. *
      5. Invalid: bad credentials were given such as a wrong password or * unsupported scheme was used. If the "rechallenge" property is true, the * challenge() method is invoked otherwise, the forbid() method is invoked.
      6. *
      7. Stale: the credentials expired and must be renew. Therefore, the * challenge() method is invoked.
      8. *
      *
    * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Jerome Louvel * @deprecated Use the {@link ChallengeAuthenticator} class instead. */ @Deprecated public class Guard extends Filter { /** Indicates that an authentication response is considered invalid. */ public static final int AUTHENTICATION_INVALID = -1; /** Indicates that an authentication response couldn't be found. */ public static final int AUTHENTICATION_MISSING = 0; /** Indicates that an authentication response is stale. */ public static final int AUTHENTICATION_STALE = 2; /** Indicates that an authentication response is valid. */ public static final int AUTHENTICATION_VALID = 1; /** Default lifespan for generated nonces (5 minutes). */ public static final long DEFAULT_NONCE_LIFESPAN_MILLIS = 5 * 60 * 1000L; /** The URIs that define the HTTP DIGEST authentication protection domains. */ private volatile Collection domainUris = Collections.singleton("/"); /** Lifespan of nonce in milliseconds */ private volatile long nonceLifespan = DEFAULT_NONCE_LIFESPAN_MILLIS; /** The authentication realm. */ private volatile String realm; /** * Indicates if a new challenge should be sent when invalid credentials are * received (true by default to conform to HTTP recommendations). */ private volatile boolean rechallengeEnabled; /** The authentication challenge scheme. */ private volatile ChallengeScheme scheme; /** The secret resolver. */ private volatile Resolver secretResolver; /** Map of secrets (login/password combinations). */ private final ConcurrentMap secrets; /** * The secret key known only to server (use for HTTP DIGEST authentication). */ private volatile String serverKey = "serverKey"; /** * Constructor. * * @param context * The context. * @param scheme * The authentication scheme to use. * @param realm * The authentication realm. * @throws IllegalArgumentException * if the scheme is null */ public Guard(Context context, ChallengeScheme scheme, String realm) throws IllegalArgumentException { super(context); if (scheme == null) { throw new IllegalArgumentException( "Please specify an authentication scheme. Use the 'None' challenge if no authentication is required."); } this.rechallengeEnabled = true; this.secretResolver = new Resolver() { @Override public char[] resolve(String identifier) { return getSecrets().get(identifier); } }; this.secrets = new ConcurrentHashMap(); this.scheme = scheme; this.realm = realm; } /** * Alternate Constructor for HTTP DIGEST authentication scheme. * * @param context * context * @param realm * authentication realm * @param baseUris * protection domain as a collection of base URIs * @param serverKey * secret key known only to server */ public Guard(Context context, String realm, Collection baseUris, String serverKey) { this(context, ChallengeScheme.HTTP_DIGEST, realm); this.domainUris = baseUris; this.serverKey = serverKey; } /** * Accepts the call. By default, it is invoked if the request is * authenticated and authorized. The default behavior is to ask to the * attached Restlet to handle the call. * * @param request * The request to accept. * @param response * The response to accept. */ public void accept(Request request, Response response) { // Invoke the attached Restlet super.doHandle(request, response); } /** * Indicates if the call is properly authenticated. By default, this * delegates credentials checking to checkSecret(). Note that the * {@link ChallengeResponse#setAuthenticated(boolean)} and * {@link ClientInfo#setAuthenticated(boolean)} methods are always called * after authentication. * * @param request * The request to authenticate. * @return -1 if the given credentials were invalid, 0 if no credentials * were found and 1 otherwise. * @see #checkSecret(Request, String, char[]) */ public int authenticate(Request request) { // Delegate processing to the Engine return AuthenticatorUtils.authenticate(request, this); } /** * Indicates if the request is authorized to pass through the Guard. This * method is only called if the call was successfully authenticated. It * always returns true by default. If specific checks are required, they * could be added by overriding this method. * * @param request * The request to authorize. * @return True if the request is authorized. */ public boolean authorize(Request request) { // Authorize everything by default return true; } /** * Challenges the client by adding a challenge request to the response and * by setting the status to CLIENT_ERROR_UNAUTHORIZED. * * @param response * The response to update. * @param stale * Indicates if the new challenge is due to a stale response. */ public void challenge(Response response, boolean stale) { // Delegate processing to the Engine AuthenticatorUtils.challenge(response, stale, this); } /** * Indicates if the secret is valid for the given identifier. By default, * this returns true given the correct login/password couple as verified via * the findSecret() method. * * @param request * The Request * @param identifier * the identifier * @param secret * the identifier's secret * @return true if the secret is valid for the given identifier */ public boolean checkSecret(Request request, String identifier, char[] secret) { boolean result = false; final char[] secret2 = findSecret(identifier); if ((secret == null) || (secret2 == null)) { // check if both are null result = (secret == secret2); } else { if (secret.length == secret2.length) { boolean equals = true; for (int i = 0; (i < secret.length) && equals; i++) { equals = (secret[i] == secret2[i]); } result = equals; } } return result; } /** * Handles the call by distributing it to the next Restlet. * * @param request * The request to handle. * @param response * The response to update. * @return The continuation status. */ @Override public int doHandle(Request request, Response response) { final boolean loggable = getLogger().isLoggable(Level.FINE); switch (authenticate(request)) { case AUTHENTICATION_VALID: // Valid credentials provided ChallengeResponse challengeResponse = request .getChallengeResponse(); if (loggable) { if (challengeResponse != null) { getLogger().fine( "Authentication succeeded. Valid credentials provided for identifier: " + request.getChallengeResponse() .getIdentifier() + "."); } else { getLogger() .fine("Authentication succeeded. Valid credentials provided."); } } if (authorize(request)) { if (loggable) { if (challengeResponse != null) { getLogger().fine( "Request authorized for identifier: " + request.getChallengeResponse() .getIdentifier() + "."); } else { getLogger().fine("Request authorized."); } } accept(request, response); } else { if (loggable) { if (challengeResponse != null) { getLogger().fine( "Request not authorized for identifier: " + request.getChallengeResponse() .getIdentifier() + "."); } else { getLogger().fine("Request not authorized."); } } forbid(response); } break; case AUTHENTICATION_MISSING: // No credentials provided if (loggable) { getLogger().fine( "Authentication failed. No credentials provided."); } challenge(response, false); break; case AUTHENTICATION_INVALID: // Invalid credentials provided if (loggable) { getLogger().fine( "Authentication failed. Invalid credentials provided."); } if (isRechallengeEnabled()) { challenge(response, false); } else { forbid(response); } break; case AUTHENTICATION_STALE: if (loggable) { getLogger().fine( "Authentication failed. Stale credentials provided."); } challenge(response, true); break; } return CONTINUE; } /** * Finds the secret associated to a given identifier. By default it looks up * into the secrets map, but this behavior can be overriden by setting a * custom secret resolver using the {@link #setSecretResolver(Resolver)} * method. * * @param identifier * The identifier to lookup. * @return The secret associated to the identifier or null. */ public char[] findSecret(String identifier) { return getSecretResolver().resolve(identifier); } /** * Rejects the call due to a failed authentication or authorization. This * can be overridden to change the default behavior, for example to display * an error page. By default, if authentication is required, the challenge * method is invoked, otherwise the call status is set to * CLIENT_ERROR_FORBIDDEN. * * @param response * The reject response. */ public void forbid(Response response) { response.setStatus(Status.CLIENT_ERROR_FORBIDDEN); } /** * Returns the base URIs that collectively define the protected domain for * HTTP Digest Authentication. * * @return The base URIs. */ public Collection getDomainUris() { return this.domainUris; } /** * Returns the number of milliseconds between each mandatory nonce refresh. * * @return The nonce lifespan. */ public long getNonceLifespan() { return this.nonceLifespan; } /** * Returns the authentication realm. * * @return The authentication realm. */ public String getRealm() { return this.realm; } /** * Returns the authentication challenge scheme. * * @return The authentication challenge scheme. */ public ChallengeScheme getScheme() { return this.scheme; } /** * Returns the secret resolver. * * @return The secret resolver. */ public Resolver getSecretResolver() { return this.secretResolver; } /** * Returns the modifiable map of identifiers and secrets. * * @return The map of identifiers and secrets. */ public ConcurrentMap getSecrets() { return this.secrets; } /** * Returns the secret key known only by server. This is used by the HTTP * DIGEST authentication scheme. * * @return The server secret key. */ public String getServerKey() { return this.serverKey; } /** * Indicates if a new challenge should be sent when invalid credentials are * received (true by default to conform to HTTP recommendations). If set to * false, upon reception of invalid credentials, the Guard will forbid the * access ({@link Status#CLIENT_ERROR_FORBIDDEN}). * * @return True if invalid credentials result in a new challenge. */ public boolean isRechallengeEnabled() { return this.rechallengeEnabled; } /** * Sets the URIs that define the HTTP DIGEST authentication protection * domains. * * @param domainUris * The URIs of protection domains. */ public void setDomainUris(Collection domainUris) { this.domainUris = domainUris; } /** * Sets the number of milliseconds between each mandatory nonce refresh. * * @param lifespan * The nonce lifespan in ms. */ public void setNonceLifespan(long lifespan) { this.nonceLifespan = lifespan; } /** * Sets the authentication realm. * * @param realm * The authentication realm. */ public void setRealm(String realm) { this.realm = realm; } /** * Indicates if a new challenge should be sent when invalid credentials are * received. * * @param rechallengeEnabled * True if invalid credentials result in a new challenge. * @see #isRechallengeEnabled() */ public void setRechallengeEnabled(boolean rechallengeEnabled) { this.rechallengeEnabled = rechallengeEnabled; } /** * Sets the authentication challenge scheme. * * @param scheme * The authentication challenge scheme. */ public void setScheme(ChallengeScheme scheme) { this.scheme = scheme; } /** * Sets the secret resolver. * * @param secretResolver * The secret resolver. */ public void setSecretResolver(Resolver secretResolver) { this.secretResolver = secretResolver; } /** * Sets the secret key known only by server. This is used by the HTTP DIGEST * authentication scheme. * * @param serverKey * The server secret key. */ public void setServerKey(String serverKey) { this.serverKey = serverKey; } } restlet-2.0.14/org.restlet/src/org/restlet/security/MemoryRealm.java0000664000175000017500000002737611757206346026241 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.ClientInfo; import org.restlet.engine.security.RoleMapping; /** * Security realm based on a memory model. The model is composed of root groups, * users and mapping to associated roles. * * @author Jerome Louvel */ public class MemoryRealm extends Realm { /** * Enroler based on the default security model. */ private class DefaultEnroler implements Enroler { public void enrole(ClientInfo clientInfo) { User user = findUser(clientInfo.getUser().getIdentifier()); if (user != null) { // Find all the inherited groups of this user Set userGroups = findGroups(user); // Add roles specific to this user Set userRoles = findRoles(user); for (Role role : userRoles) { clientInfo.getRoles().add(role); } // Add roles common to group members Set groupRoles = findRoles(userGroups); for (Role role : groupRoles) { clientInfo.getRoles().add(role); } } } } /** * Verifier based on the default security model. It looks up users in the * mapped organizations. */ private class DefaultVerifier extends LocalVerifier { @Override public char[] getLocalSecret(String identifier) { char[] result = null; User user = findUser(identifier); if (user != null) { result = user.getSecret(); } return result; } } /** The modifiable list of role mappings. */ private final List roleMappings; /** The modifiable list of root groups. */ private final List rootGroups; /** The modifiable list of users. */ private final List users; /** * Constructor. */ public MemoryRealm() { setVerifier(new DefaultVerifier()); setEnroler(new DefaultEnroler()); this.rootGroups = new CopyOnWriteArrayList(); this.roleMappings = new CopyOnWriteArrayList(); this.users = new CopyOnWriteArrayList(); } /** * Recursively adds groups where a given user is a member. * * @param user * The member user. * @param userGroups * The set of user groups to update. * @param currentGroup * The current group to inspect. * @param stack * The stack of ancestor groups. * @param inheritOnly * Indicates if only the ancestors groups that have their * "inheritRoles" property enabled should be added. */ private void addGroups(User user, Set userGroups, Group currentGroup, List stack, boolean inheritOnly) { if ((currentGroup != null) && !stack.contains(currentGroup)) { stack.add(currentGroup); if (currentGroup.getMemberUsers().contains(user)) { userGroups.add(currentGroup); // Add the ancestor groups as well boolean inherit = !inheritOnly || currentGroup.isInheritingRoles(); Group group; for (int i = stack.size() - 2; inherit && (i >= 0); i--) { group = stack.get(i); userGroups.add(group); inherit = !inheritOnly || group.isInheritingRoles(); } } for (Group group : currentGroup.getMemberGroups()) { addGroups(user, userGroups, group, stack, inheritOnly); } } } /** * Finds the set of groups where a given user is a member. Note that * inheritable ancestors groups are also returned. * * @param user * The member user. * @return The set of groups. */ public Set findGroups(User user) { return findGroups(user, true); } /** * Finds the set of groups where a given user is a member. * * @param user * The member user. * @param inheritOnly * Indicates if only the ancestors groups that have their * "inheritRoles" property enabled should be added. * @return The set of groups. */ public Set findGroups(User user, boolean inheritOnly) { Set result = new HashSet(); List stack; // Recursively find user groups for (Group group : getRootGroups()) { stack = new ArrayList(); addGroups(user, result, group, stack, inheritOnly); } return result; } /** * Finds the roles mapped to given user group. * * @param userGroup * The user group. * @return The roles found. */ public Set findRoles(Group userGroup) { Set result = new HashSet(); Object source; for (RoleMapping mapping : getRoleMappings()) { source = mapping.getSource(); if ((userGroup != null) && userGroup.equals(source)) { result.add(mapping.getTarget()); } } return result; } /** * Finds the roles mapped to given user groups. * * @param userGroups * The user groups. * @return The roles found. */ public Set findRoles(Set userGroups) { Set result = new HashSet(); Object source; for (RoleMapping mapping : getRoleMappings()) { source = mapping.getSource(); if ((userGroups != null) && userGroups.contains(source)) { result.add(mapping.getTarget()); } } return result; } /** * Finds the roles mapped to a given user. * * @param user * The user. * @return The roles found. */ public Set findRoles(User user) { Set result = new HashSet(); Object source; for (RoleMapping mapping : getRoleMappings()) { source = mapping.getSource(); if ((user != null) && user.equals(source)) { result.add(mapping.getTarget()); } } return result; } /** * Finds a user in the organization based on its identifier. * * @param userIdentifier * The identifier to match. * @return The matched user or null. */ public User findUser(String userIdentifier) { User result = null; User user; for (int i = 0; (result == null) && (i < getUsers().size()); i++) { user = getUsers().get(i); if (user.getIdentifier().equals(userIdentifier)) { result = user; } } return result; } /** * Returns the modifiable list of role mappings. * * @return The modifiable list of role mappings. */ private List getRoleMappings() { return roleMappings; } /** * Returns the modifiable list of root groups. * * @return The modifiable list of root groups. */ public List getRootGroups() { return rootGroups; } /** * Returns the modifiable list of users. * * @return The modifiable list of users. */ public List getUsers() { return users; } /** * Maps a group defined in a component to a role defined in the application. * * @param group * The source group. * @param role * The target role. */ public void map(Group group, Role role) { getRoleMappings().add(new RoleMapping(group, role)); } /** * Maps a user defined in a component to a role defined in the application. * * @param user * The source user. * @param role * The target role. */ public void map(User user, Role role) { getRoleMappings().add(new RoleMapping(user, role)); } /** * Sets the modifiable list of root groups. This method clears the current * list and adds all entries in the parameter list. * * @param rootGroups * A list of root groups. */ public void setRootGroups(List rootGroups) { synchronized (getRootGroups()) { if (rootGroups != getRootGroups()) { getRootGroups().clear(); if (rootGroups != null) { getRootGroups().addAll(rootGroups); } } } } /** * Sets the modifiable list of users. This method clears the current list * and adds all entries in the parameter list. * * @param users * A list of users. */ public void setUsers(List users) { synchronized (getUsers()) { if (users != getUsers()) { getUsers().clear(); if (users != null) { getUsers().addAll(users); } } } } /** * Unmaps a group defined in a component from a role defined in the * application. * * @param group * The source group. * @param role * The target role. */ public void unmap(Group group, Role role) { unmap((Object) group, role); } /** * Unmaps an element (user, group or organization) defined in a component * from a role defined in the application. * * @param group * The source group. * @param role * The target role. */ private void unmap(Object source, Role role) { RoleMapping mapping; for (int i = getRoleMappings().size(); i >= 0; i--) { mapping = getRoleMappings().get(i); if (mapping.getSource().equals(source) && mapping.getTarget().equals(role)) { getRoleMappings().remove(i); } } } /** * Unmaps a user defined in a component from a role defined in the * application. * * @param user * The source user. * @param role * The target role. */ public void unmap(User user, Role role) { unmap((Object) user, role); } } restlet-2.0.14/org.restlet/src/org/restlet/security/User.java0000664000175000017500000001330211757206350024701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import java.security.Principal; /** * User part of a security realm. Note the same user can be member of several * groups. * * @see Realm * @see Group * @author Jerome Louvel */ public class User implements Principal { /** The email. */ private volatile String email; /** The first name. */ private volatile String firstName; /** The identifier. */ private volatile String identifier; /** The last name. */ private volatile String lastName; /** The secret. */ private volatile char[] secret; /** * Default constructor. */ public User() { this(null, (char[]) null, null, null, null); } /** * Constructor. * * @param identifier * The identifier (login). */ public User(String identifier) { this(identifier, (char[]) null, null, null, null); } /** * Constructor. * * @param identifier * The identifier (login). * @param secret * The identification secret. */ public User(String identifier, char[] secret) { this(identifier, secret, null, null, null); } /** * Constructor. * * @param identifier * The identifier (login). * @param secret * The identification secret. * @param firstName * The first name. * @param lastName * The last name. * @param email * The email. */ public User(String identifier, char[] secret, String firstName, String lastName, String email) { this.identifier = identifier; this.secret = secret; this.firstName = firstName; this.lastName = lastName; this.email = email; } /** * Constructor. * * @param identifier * The identifier (login). * @param secret * The identification secret. */ public User(String identifier, String secret) { this(identifier, secret.toCharArray()); } /** * Constructor. * * @param identifier * The identifier (login). * @param secret * The identification secret. * @param firstName * The first name. * @param lastName * The last name. * @param email * The email. */ public User(String identifier, String secret, String firstName, String lastName, String email) { this(identifier, secret.toCharArray(), firstName, lastName, email); } /** * Returns the email. * * @return The email. */ public String getEmail() { return email; } /** * Returns the first name. * * @return The first name. */ public String getFirstName() { return firstName; } /** * Returns the identifier. * * @return The identifier. */ public String getIdentifier() { return identifier; } /** * Returns the last name. * * @return The last name. */ public String getLastName() { return lastName; } /** * Returns the user identifier. * * @see #getIdentifier() */ public String getName() { return getIdentifier(); } /** * Returns the secret. * * @return The secret. */ public char[] getSecret() { return secret; } /** * Sets the email. * * @param email * The email. */ public void setEmail(String email) { this.email = email; } /** * Sets the first name. * * @param firstName * The first name. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Sets the identifier. * * @param identifier * The identifier. */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Sets the last name. * * @param lastName * The last name. */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Sets the secret. * * @param secret * The secret. */ public void setSecret(char[] secret) { this.secret = secret; } @Override public String toString() { return getIdentifier(); } } restlet-2.0.14/org.restlet/src/org/restlet/security/LocalVerifier.java0000664000175000017500000000370711757206350026521 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; /** * Verifier that can locally retrieve the secrets. This verifier assumes that * the secret associated to an identifier can be retrieved, which isn't always * possible or even desirable. * * @author Jerome Louvel */ public abstract class LocalVerifier extends SecretVerifier { /** * Returns the local secret associated to a given identifier. * * @param identifier * The identifier to lookup. * @return The secret associated to the identifier or null. */ public abstract char[] getLocalSecret(String identifier); @Override public boolean verify(String identifier, char[] secret) { return compare(secret, getLocalSecret(identifier)); } } restlet-2.0.14/org.restlet/src/org/restlet/Response.java0000664000175000017500000006433211757206350023723 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet; import java.util.Date; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import org.restlet.data.AuthenticationInfo; import org.restlet.data.ChallengeRequest; import org.restlet.data.CookieSetting; import org.restlet.data.Dimension; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.ServerInfo; import org.restlet.data.Status; import org.restlet.engine.util.CookieSettingSeries; import org.restlet.util.Series; /** * Generic response sent by server connectors. It is then received by client * connectors. Responses are uniform across all types of connectors, protocols * and components. * * @see org.restlet.Request * @see org.restlet.Uniform * @author Jerome Louvel */ public class Response extends Message { private static final ThreadLocal CURRENT = new ThreadLocal(); /** * Returns the response associated to the current thread. * * Warning: this method should only be used under duress. You should by * default prefer obtaining the current context using methods such as * {@link org.restlet.resource.Resource#getResponse()}. * * This variable is stored internally as a thread local variable and updated * each time a call is handled by a Restlet via the * {@link Restlet#handle(org.restlet.Request, org.restlet.Response)} method. * * @return The current context. */ public static Response getCurrent() { return CURRENT.get(); } /** * Sets the response associated with the current thread. * * @param response * The thread's response. */ public static void setCurrent(Response response) { CURRENT.set(response); } /** * Estimated amount of time since a response was generated or revalidated by * the origin server. */ private volatile int age; /** The set of methods allowed on the requested resource. */ private volatile Set allowedMethods; /** * The authentication information sent by an origin server to a client in * the case of a successful authentication attempt. */ private volatile AuthenticationInfo authenticationInfo; /** Indicates if the response should be automatically committed. */ private volatile boolean autoCommitting; /** The authentication requests sent by an origin server to a client. */ private volatile List challengeRequests; /** Indicates if the response has been committed. */ private volatile boolean committed; /** The cookie settings provided by the server. */ private volatile Series cookieSettings; /** The set of dimensions on which the response entity may vary. */ private volatile Set dimensions; /** The reference used for redirections or creations. */ private volatile Reference locationRef; /** The authentication requests sent by a proxy to a client. */ private volatile List proxyChallengeRequests; /** The associated request. */ private volatile Request request; /** * Indicates how long the service is expected to be unavailable to the * requesting client. */ private volatile Date retryAfter; /** The server-specific information. */ private volatile ServerInfo serverInfo; /** The status. */ private volatile Status status; /** * Constructor. * * @param request * The request associated to this response. */ public Response(Request request) { this.age = 0; this.allowedMethods = null; this.autoCommitting = true; this.challengeRequests = null; this.cookieSettings = null; this.committed = false; this.dimensions = null; this.locationRef = null; this.proxyChallengeRequests = null; this.request = request; this.retryAfter = null; this.serverInfo = null; this.status = Status.SUCCESS_OK; } /** * Ask the connector to abort the related network connection, for example * immediately closing the socket. */ public void abort() { getRequest().abort(); } /** * Asks the server connector to immediately commit the given response, * making it ready to be sent back to the client. Note that all server * connectors don't necessarily support this feature. */ public void commit() { getRequest().commit(this); } /** * Returns the estimated amount of time since a response was generated or * revalidated by the origin server. Origin servers should leave the 0 * default value. Only caches are expected to set this property.
    *
    * Note that when used with HTTP connectors, this property maps to the "Age" * header. * * @return The response age. */ public int getAge() { return age; } /** * Returns the modifiable set of methods allowed on the requested resource. * This property only has to be updated when a status * CLIENT_ERROR_METHOD_NOT_ALLOWED is set. Creates a new instance if no one * has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Allow" header. * * @return The set of allowed methods. */ public Set getAllowedMethods() { // Lazy initialization with double-check. Set a = this.allowedMethods; if (a == null) { synchronized (this) { a = this.allowedMethods; if (a == null) { this.allowedMethods = a = new CopyOnWriteArraySet(); } } } return a; } /** * Returns information sent by an origin server related to an successful * authentication attempt. If none is available, null is returned.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Authentication-Info" header. * * @return The authentication information provided by the server. */ public AuthenticationInfo getAuthenticationInfo() { return this.authenticationInfo; } /** * Returns the list of authentication requests sent by an origin server to a * client. If none is available, an empty list is returned.
    *
    * Note that when used with HTTP connectors, this property maps to the * "WWW-Authenticate" header. * * @return The list of authentication requests. */ public List getChallengeRequests() { // Lazy initialization with double-check. List cr = this.challengeRequests; if (cr == null) { synchronized (this) { cr = this.challengeRequests; if (cr == null) { this.challengeRequests = cr = new CopyOnWriteArrayList(); } } } return cr; } /** * Returns the modifiable series of cookie settings provided by the server. * Creates a new instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Set-Cookie" and "Set-Cookie2" headers. * * @return The cookie settings provided by the server. */ public Series getCookieSettings() { // Lazy initialization with double-check. Series c = this.cookieSettings; if (c == null) { synchronized (this) { c = this.cookieSettings; if (c == null) { this.cookieSettings = c = new CookieSettingSeries(); } } } return c; } /** * Returns the modifiable set of selecting dimensions on which the response * entity may vary. If some server-side content negotiation is done, this * set should be properly updated, other it can be left empty. Creates a new * instance if no one has been set.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Vary" header. * * @return The set of dimensions on which the response entity may vary. */ public Set getDimensions() { if (this.dimensions == null) { this.dimensions = new CopyOnWriteArraySet(); } return this.dimensions; } /** * Returns the location reference. This is the reference that the client * should follow for redirections or resource creations.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Location" header. * * @return The redirection reference. */ public Reference getLocationRef() { return this.locationRef; } /** * Returns the list of authentication requests sent by an origin server to a * client. If none is available, an empty list is returned.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Proxy-Authenticate" header. * * @return The list of authentication requests. */ public List getProxyChallengeRequests() { // Lazy initialization with double-check. List cr = this.proxyChallengeRequests; if (cr == null) { synchronized (this) { cr = this.proxyChallengeRequests; if (cr == null) { this.proxyChallengeRequests = cr = new CopyOnWriteArrayList(); } } } return cr; } /** * Returns the associated request * * @return The associated request */ public Request getRequest() { return this.request; } /** * Indicates how long the service is expected to be unavailable to the * requesting client. Default value is null.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Retry-After" header. * * @return Date after with a retry attempt could occur. */ public Date getRetryAfter() { return retryAfter; } /** * Returns the server-specific information. Creates a new instance if no one * has been set. * * @return The server-specific information. */ public ServerInfo getServerInfo() { // Lazy initialization with double-check. ServerInfo s = this.serverInfo; if (s == null) { synchronized (this) { s = this.serverInfo; if (s == null) { this.serverInfo = s = new ServerInfo(); } } } return s; } /** * Returns the status. * * @return The status. */ public Status getStatus() { return this.status; } /** * Indicates if the response should be automatically committed. When * processing a request on the server-side, setting this property to 'false' * let you ask to the server connector to wait before sending the response * back to the client when the initial calling thread returns. This will let * you do further updates to the response and manually calling * {@link #commit()} later on, using another thread. * * @return True if the response should be automatically committed. */ public boolean isAutoCommitting() { return autoCommitting; } /** * Indicates if the response has already been committed. * * @return True if the response has already been committed. */ public boolean isCommitted() { return committed; } @Override public boolean isConfidential() { return getRequest().isConfidential(); } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target URI reference. */ public void redirectPermanent(Reference targetRef) { setLocationRef(targetRef); setStatus(Status.REDIRECTION_PERMANENT); } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request.
    *
    * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectPermanent(String targetUri) { setLocationRef(targetUri); setStatus(Status.REDIRECTION_PERMANENT); } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource. * * @param targetRef * The target reference. */ public void redirectSeeOther(Reference targetRef) { setLocationRef(targetRef); setStatus(Status.REDIRECTION_SEE_OTHER); } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource.
    *
    * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectSeeOther(String targetUri) { setLocationRef(targetUri); setStatus(Status.REDIRECTION_SEE_OTHER); } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target reference. */ public void redirectTemporary(Reference targetRef) { setLocationRef(targetRef); setStatus(Status.REDIRECTION_TEMPORARY); } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request.
    *
    * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectTemporary(String targetUri) { setLocationRef(targetUri); setStatus(Status.REDIRECTION_TEMPORARY); } /** * Sets the estimated amount of time since a response was generated or * revalidated by the origin server. Origin servers should leave the 0 * default value. Only caches are expected to set this property.
    *
    * Note that when used with HTTP connectors, this property maps to the "Age" * header. * * @param age * The response age. */ public void setAge(int age) { this.age = age; } /** * Sets the set of methods allowed on the requested resource. The set * instance set must be thread-safe (use {@link CopyOnWriteArraySet} for * example.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Allow" header. * * @param allowedMethods * The set of methods allowed on the requested resource. */ public void setAllowedMethods(Set allowedMethods) { synchronized (getAllowedMethods()) { if (allowedMethods != this.allowedMethods) { this.allowedMethods.clear(); if (allowedMethods != null) { this.allowedMethods.addAll(allowedMethods); } } } } /** * Sets the authentication information sent by an origin server to a client * after a successful authentication attempt.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Authentication-Info" header. * * @param authenticationInfo * The data returned by the server in response to successful * authentication. */ public void setAuthenticationInfo(AuthenticationInfo authenticationInfo) { this.authenticationInfo = authenticationInfo; } /** * Indicates if the response should be automatically committed. * * @param autoCommitting * True if the response should be automatically committed */ public void setAutoCommitting(boolean autoCommitting) { this.autoCommitting = autoCommitting; } /** * Sets the authentication request sent by an origin server to a client. * * @param request * The authentication request sent by an origin server to a * client. * @deprecated Add request to {@link #getChallengeRequests()} method result * instead or use {@link #setChallengeRequests(List)}. */ @Deprecated public void setChallengeRequest(ChallengeRequest request) { final List requests = new CopyOnWriteArrayList(); requests.add(request); setChallengeRequests(requests); } /** * Sets the list of authentication requests sent by an origin server to a * client. Note that when used with HTTP connectors, this property maps to * the "WWW-Authenticate" header. This method clears the current list and * adds all entries in the parameter list. * * @param challengeRequests * A list of authentication requests sent by an origin server to * a client. */ public void setChallengeRequests(List challengeRequests) { synchronized (getChallengeRequests()) { if (challengeRequests != getChallengeRequests()) { getChallengeRequests().clear(); if (challengeRequests != null) { getChallengeRequests().addAll(challengeRequests); } } } } /** * Indicates if the response has already been committed. * * @param committed * True if the response has already been committed. */ public void setCommitted(boolean committed) { this.committed = committed; } /** * Sets the modifiable series of cookie settings provided by the server. * Note that when used with HTTP connectors, this property maps to the * "Set-Cookie" and "Set-Cookie2" headers. This method clears the current * series and adds all entries in the parameter series. * * @param cookieSettings * A series of cookie settings provided by the server. */ public void setCookieSettings(Series cookieSettings) { synchronized (getCookieSettings()) { if (cookieSettings != getCookieSettings()) { getCookieSettings().clear(); if (cookieSettings != null) { getCookieSettings().addAll(cookieSettings); } } } } /** * Sets the set of dimensions on which the response entity may vary. Note * that when used with HTTP connectors, this property maps to the "Vary" * header. This method clears the current set and adds all entries in the * parameter set. * * @param dimensions * The set of dimensions on which the response entity may vary. */ public void setDimensions(Set dimensions) { synchronized (getDimensions()) { if (dimensions != getDimensions()) { getDimensions().clear(); if (dimensions != null) { getDimensions().addAll(dimensions); } } } } /** * Sets the reference that the client should follow for redirections or * resource creations. Note that when used with HTTP connectors, this * property maps to the "Location" header. * * @param locationRef * The reference to set. */ public void setLocationRef(Reference locationRef) { this.locationRef = locationRef; } /** * Sets the reference that the client should follow for redirections or * resource creations. If you pass a relative location URI, it will be * resolved with the current base reference of the request's resource * reference (see {@link Request#getResourceRef()} and * {@link Reference#getBaseRef()}.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Location" header. * * @param locationUri * The URI to set. * @see #setLocationRef(Reference) */ public void setLocationRef(String locationUri) { Reference baseRef = null; if (getRequest().getResourceRef() != null) { if (getRequest().getResourceRef().getBaseRef() != null) { baseRef = getRequest().getResourceRef().getBaseRef(); } else { baseRef = getRequest().getResourceRef(); } } setLocationRef(new Reference(baseRef, locationUri).getTargetRef()); } /** * Sets the modifiable list of authentication requests sent by a proxy to a * client. The list instance set must be thread-safe (use * {@link CopyOnWriteArrayList} for example. Note that when used with HTTP * connectors, this property maps to the "Proxy-Authenticate" header. This * method clears the current list and adds all entries in the parameter * list. * * @param proxyChallengeRequests * A list of authentication requests sent by a proxy to a client. */ public void setProxyChallengeRequests( List proxyChallengeRequests) { synchronized (getProxyChallengeRequests()) { if (proxyChallengeRequests != getProxyChallengeRequests()) { getProxyChallengeRequests().clear(); if (proxyChallengeRequests != null) { getProxyChallengeRequests().addAll(proxyChallengeRequests); } } } } /** * Sets the associated request. * * @param request * The associated request */ public void setRequest(Request request) { this.request = request; } /** * Indicates how long the service is expected to be unavailable to the * requesting client. Default value is null.
    *
    * Note that when used with HTTP connectors, this property maps to the * "Retry-After" header. * * @param retryAfter * Date after with a retry attempt could occur. */ public void setRetryAfter(Date retryAfter) { this.retryAfter = retryAfter; } /** * Sets the server-specific information. * * @param serverInfo * The server-specific information. */ public void setServerInfo(ServerInfo serverInfo) { this.serverInfo = serverInfo; } /** * Sets the status. * * @param status * The status to set. */ public void setStatus(Status status) { this.status = status; } /** * Sets the status. * * @param status * The status to set. * @param message * The status message. */ public void setStatus(Status status, String message) { setStatus(new Status(status, message)); } /** * Sets the status. * * @param status * The status to set. * @param throwable * The related error or exception. */ public void setStatus(Status status, Throwable throwable) { setStatus(new Status(status, throwable)); } /** * Sets the status. * * @param status * The status to set. * @param throwable * The related error or exception. * @param message * The status message. */ public void setStatus(Status status, Throwable throwable, String message) { setStatus(new Status(status, throwable, message)); } /** * Displays a synthesis of the response like an HTTP status line. * * @return A synthesis of the response like an HTTP status line. */ public String toString() { return getRequest().getProtocol() + " - " + getStatus(); } } restlet-2.0.14/org.restlet.ext.velocity/0000775000175000017500000000000012001473205020632 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.velocity/pom.xml0000600000175000017500000000224512001473205022140 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.velocity Restlet Extension - Velocity Integration with Apache Velocity. commons-collections commons-collections 3.2.1 commons-lang commons-lang 2.5 org.apache.velocity velocity 1.6.3 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.velocity/src/0000775000175000017500000000000012001473204021420 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.velocity/src/META-INF/0000775000175000017500000000000011757206452022600 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.velocity/src/META-INF/services/0000775000175000017500000000000011757206352024422 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.ext.velocity/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.velocity/src/META-INF/services/org.restlet.engine.converter.Converter0000664000175000017500000000005211757206352034032 0ustar jamespagejamespageorg.restlet.ext.velocity.VelocityConverterrestlet-2.0.14/org.restlet.ext.velocity/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450024231 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.velocity/src/org/0000775000175000017500000000000011757206352022226 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/0000775000175000017500000000000011757206352023710 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/0000775000175000017500000000000011757206352024510 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/velocity/0000775000175000017500000000000011757206352026346 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/velocity/VelocityConverter.java0000664000175000017500000000705311757206352032704 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.velocity; import java.io.IOException; import java.util.List; import org.apache.velocity.Template; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between the Velocity Template objects and Representations. The * adjoined data model is based on the request and response objects. * * @author Thierry Boileau. */ public class VelocityConverter extends ConverterHelper { private static final VariantInfo VARIANT_ALL = new VariantInfo( MediaType.ALL); @Override public List> getObjectClasses(Variant source) { return null; } @Override public List getVariants(Class source) { List result = null; if (Template.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_ALL); } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { return -1.0f; } @Override public float score(Object source, Variant target, UniformResource resource) { if (source instanceof Template) { return 1.0f; } return -1.0f; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { return null; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { if (source instanceof Template) { TemplateRepresentation tr = new TemplateRepresentation( (Template) source, target.getMediaType()); tr.setDataModel(resource.getRequest(), resource.getResponse()); return tr; } return null; } @Override public void updatePreferences(List> preferences, Class entity) { if (Template.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.ALL, 1.0F); } } } restlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/velocity/package.html0000664000175000017500000000046411757206352030633 0ustar jamespagejamespage Integration with Apache Velocity 1.6. Velocity is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. @since Restlet 1.0 @see Velocity template engine ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/velocity/RepresentationResourceLoader.javarestlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/velocity/RepresentationResourceLoader.ja0000664000175000017500000000762511757206352034535 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.velocity; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.collections.ExtendedProperties; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.runtime.resource.Resource; import org.apache.velocity.runtime.resource.loader.ResourceLoader; import org.restlet.representation.Representation; /** * Velocity resource loader based on a static map of representations or on a * default representation. * * @author Jerome Louvel */ public class RepresentationResourceLoader extends ResourceLoader { /** The cache of template representations. */ private static final Map store = new ConcurrentHashMap(); /** * Returns the cache of template representations. * * @return The cache of template representations. */ public static Map getStore() { return store; } /** The default representation to load. */ private final Representation defaultRepresentation; /** * Constructor. * * @param defaultRepresentation * The default representation to use. */ public RepresentationResourceLoader(Representation defaultRepresentation) { this.defaultRepresentation = defaultRepresentation; } @Override public long getLastModified(Resource resource) { final Representation original = getStore().get(resource.getName()); return (original != null) ? original.getModificationDate().getTime() : 0; } @Override public InputStream getResourceStream(String name) throws ResourceNotFoundException { InputStream result = null; try { Representation resultRepresentation = getStore().get(name); if (resultRepresentation == null) { resultRepresentation = this.defaultRepresentation; if (resultRepresentation == null) { throw new ResourceNotFoundException( "Could not locate resource '" + name + "'"); } result = resultRepresentation.getStream(); } else { result = resultRepresentation.getStream(); } } catch (IOException ioe) { throw new ResourceNotFoundException(ioe); } return result; } @Override public void init(ExtendedProperties configuration) { } @Override public boolean isSourceModified(Resource resource) { return getLastModified(resource) != resource.getLastModified(); } } restlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/velocity/TemplateFilter.java0000664000175000017500000001236611757206352032142 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.velocity; import java.io.IOException; import java.util.Map; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Encoding; import org.restlet.data.Status; import org.restlet.routing.Filter; import org.restlet.util.Resolver; /** * Filter response's entity and wrap it with a Velocity's template * representation. By default, the template representation provides a data model * based on the request and response objects. In order for the wrapping to * happen, the representations must have the {@link Encoding#VELOCITY} encoding * set.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Thierry Boileau */ public class TemplateFilter extends Filter { /** The template's data model as a map. */ private volatile Map mapDataModel; /** The template's data model as a resolver. */ private volatile Resolver resolverDataModel; /** * Constructor. */ public TemplateFilter() { super(); } /** * Constructor. * * @param context * The context. */ public TemplateFilter(Context context) { super(context); } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. */ public TemplateFilter(Context context, Restlet next) { super(context, next); this.mapDataModel = null; this.resolverDataModel = null; } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. * @param dataModel * The filter's data model. */ public TemplateFilter(Context context, Restlet next, Map dataModel) { super(context, next); this.mapDataModel = dataModel; this.resolverDataModel = null; } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. * @param dataModel * The filter's data model. */ public TemplateFilter(Context context, Restlet next, Resolver dataModel) { super(context, next); this.mapDataModel = null; this.resolverDataModel = dataModel; } @Override protected void afterHandle(Request request, Response response) { if (response.isEntityAvailable() && response.getEntity().getEncodings().contains( Encoding.VELOCITY)) { try { final TemplateRepresentation representation = new TemplateRepresentation( response.getEntity(), response.getEntity() .getMediaType()); if ((this.mapDataModel == null) && (this.resolverDataModel == null)) { representation.setDataModel(request, response); } else { if (this.mapDataModel == null) { representation.setDataModel(this.resolverDataModel); } else { representation.setDataModel(this.mapDataModel); } } response.setEntity(representation); } catch (ResourceNotFoundException e) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND, e); } catch (ParseErrorException e) { response.setStatus(Status.SERVER_ERROR_INTERNAL, e); } catch (IOException e) { response.setStatus(Status.SERVER_ERROR_INTERNAL, e); } } } } restlet-2.0.14/org.restlet.ext.velocity/src/org/restlet/ext/velocity/TemplateRepresentation.java0000664000175000017500000003130211757206352033706 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.velocity; import java.io.IOException; import java.io.Writer; import java.util.Date; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.runtime.RuntimeSingleton; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.restlet.util.Resolver; /** * Velocity template representation. Useful for dynamic string-based * representations. * * @see Velocity home page * @author Jerome Louvel */ public class TemplateRepresentation extends WriterRepresentation { /** * Velocity context based on a Resolver. * * @see Resolver */ private class ResolverContext implements org.apache.velocity.context.Context { /** The inner resolver instance. */ private final Resolver resolver; /** * Constructor. * * @param resolver * The resolver. */ public ResolverContext(Resolver resolver) { super(); this.resolver = resolver; } /** * Indicates whether the specified key is in the context. * * @param key * The key to look for. * @Return True if the key is in the context, false otherwise. */ public boolean containsKey(Object key) { return this.resolver.resolve((String) key) != null; } /** * Gets the value corresponding to the provided key from the context. * * @Param key The name of the desired value. * @Return The value corresponding to the provided key. */ public Object get(String key) { return this.resolver.resolve(key); } /** * Returns null since a resolver does not know by advance the whole * values. * * @Return null. */ public Object[] getKeys() { return null; } /** * Returns null since a resolver as a data model cannot be updated. * * @param key * The name to key the provided value with. * @param value * The corresponding value. * @return null. */ public Object put(String key, Object value) { return null; } /** * Does nothing since resolver as a data model cannot be updated. * * @param value * The name of the value to remove. * @return null. */ public Object remove(Object value) { return null; } } /** The template's data model. */ private volatile org.apache.velocity.context.Context context; /** The Velocity engine. */ private volatile VelocityEngine engine; /** The template. */ private volatile Template template; /** The template name. */ private volatile String templateName; /** * Constructor based on a Velocity 'encoded' representation. * * @param templateRepresentation * The representation to 'decode'. * @param dataModel * The Velocity template's data model. * @param mediaType * The representation's media type. * @throws IOException * @throws ParseErrorException * @throws ResourceNotFoundException */ public TemplateRepresentation(Representation templateRepresentation, Map dataModel, MediaType mediaType) throws ResourceNotFoundException, ParseErrorException, IOException { super(mediaType); setDataModel(dataModel); this.engine = null; this.template = new Template(); CharacterSet charSet = (templateRepresentation.getCharacterSet() != null) ? templateRepresentation .getCharacterSet() : CharacterSet.DEFAULT; this.template.setEncoding(charSet.getName()); if (templateRepresentation.getModificationDate() != null) { this.template.setLastModified(templateRepresentation .getModificationDate().getTime()); } this.template.setName("org.restlet.resource.representation"); this.template.setRuntimeServices(RuntimeSingleton.getRuntimeServices()); this.template.setResourceLoader(new RepresentationResourceLoader( templateRepresentation)); this.template.process(); this.templateName = null; } /** * Constructor based on a Velocity 'encoded' representation. * * @param templateRepresentation * The representation to 'decode'. * @param mediaType * The representation's media type. * @throws IOException * @throws ParseErrorException * @throws ResourceNotFoundException */ public TemplateRepresentation(Representation templateRepresentation, MediaType mediaType) throws ResourceNotFoundException, ParseErrorException, IOException { super(mediaType); this.engine = null; this.template = new Template(); CharacterSet charSet = (templateRepresentation.getCharacterSet() != null) ? templateRepresentation .getCharacterSet() : CharacterSet.DEFAULT; this.template.setEncoding(charSet.getName()); this.template.setLastModified((templateRepresentation .getModificationDate() == null) ? new Date().getTime() : templateRepresentation.getModificationDate().getTime()); this.template.setName("org.restlet.resource.representation"); this.template.setRuntimeServices(RuntimeSingleton.getRuntimeServices()); this.template.setResourceLoader(new RepresentationResourceLoader( templateRepresentation)); this.template.process(); this.templateName = null; } /** * Constructor. * * @param templateName * The Velocity template's name. The actual template is retrieved * using the Velocity configuration. * @param dataModel * The Velocity template's data model. * @param mediaType * The representation's media type. */ public TemplateRepresentation(String templateName, Map dataModel, MediaType mediaType) { super(mediaType); try { setDataModel(dataModel); this.engine = new VelocityEngine(); this.template = null; this.templateName = templateName; } catch (Exception e) { e.printStackTrace(); } } /** * Constructor. * * @param templateName * The Velocity template's name. The full path is resolved by the * configuration. * @param mediaType * The representation's media type. */ public TemplateRepresentation(String templateName, MediaType mediaType) { this(templateName, new TreeMap(), mediaType); } /** * Constructor. * * @param template * The Velocity template. * @param dataModel * The Velocity template's data model. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Template template, Map dataModel, MediaType mediaType) { super(mediaType); setDataModel(dataModel); this.engine = null; this.template = template; this.templateName = null; } /** * Constructor. * * @param template * The Velocity template. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Template template, MediaType mediaType) { super(mediaType); this.engine = null; this.template = template; this.templateName = null; } /** * Returns the Velocity context. * * @return The Velocity context. */ private org.apache.velocity.context.Context getContext() { return this.context; } /** * Returns the Velocity engine. * * @return The Velocity engine. */ public VelocityEngine getEngine() { return this.engine; } /** * Returns the Velocity template. * * @return The Velocity template. */ public Template getTemplate() { if (this.template == null) { if (this.templateName != null) { try { getEngine().init(); this.template = getEngine().getTemplate(this.templateName); } catch (Exception e) { final Context context = Context.getCurrent(); if (context != null) { context.getLogger().log(Level.WARNING, "Unable to get template", e); } } } } return this.template; } /** * Sets the Velocity context. * * @param context * The Velocity context */ private void setContext(org.apache.velocity.context.Context context) { this.context = context; } /** * Sets the template's data model. * * @param dataModel * The template's data model. */ public void setDataModel(Map dataModel) { setContext(new VelocityContext(dataModel)); } /** * Sets the template's data model from a request/response pair. This default * implementation uses a Resolver. * * @see Resolver * @see Resolver#createResolver(Request, Response) * * @param request * The request where data are located. * @param response * The response where data are located. */ public void setDataModel(Request request, Response response) { setContext(new ResolverContext(Resolver.createResolver(request, response))); } /** * Sets the template's data model from a resolver. * * @param resolver * The resolver. */ public void setDataModel(Resolver resolver) { setContext(new ResolverContext(resolver)); } /** * Writes the datum as a stream of characters. * * @param writer * The writer to use when writing. */ @Override public void write(Writer writer) throws IOException { try { // Load the template // Process the template getTemplate().merge(getContext(), writer); } catch (Exception e) { final Context context = Context.getCurrent(); if (context != null) { context.getLogger().log(Level.WARNING, "Unable to process the template", e); } e.printStackTrace(); throw new IOException("Template processing error. " + e.getMessage()); } } } restlet-2.0.14/org.restlet.ext.grizzly/0000775000175000017500000000000012001473204020505 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/pom.xml0000600000175000017500000000204012001473204022004 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.grizzly Restlet Extension - Grizzly Integration with Grizzly NIO framework. com.sun.grizzly grizzly-framework 1.9.18-i com.sun.grizzly grizzly-utils 1.9.18-i org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.grizzly/src/0000775000175000017500000000000012001473204021274 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/META-INF/0000775000175000017500000000000011757206450022452 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/META-INF/services/0000775000175000017500000000000011757206352024276 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/META-INF/services/org.restlet.engine.ServerHelper0000664000175000017500000000014411757206352032341 0ustar jamespagejamespageorg.restlet.ext.grizzly.HttpServerHelper # HTTP org.restlet.ext.grizzly.HttpsServerHelper # HTTPS restlet-2.0.14/org.restlet.ext.grizzly/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446024112 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.grizzly/src/org/0000775000175000017500000000000011757206352022102 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/0000775000175000017500000000000011757206352023564 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/0000775000175000017500000000000011757206352024364 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/0000775000175000017500000000000011757206352026076 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/internal/0000775000175000017500000000000011757206352027712 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/internal/GrizzlyServerCall.java0000664000175000017500000002140111757206352034210 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.grizzly.internal; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; import java.security.cert.Certificate; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import org.restlet.Response; import org.restlet.Server; import org.restlet.engine.http.ServerCall; import org.restlet.engine.http.io.ChunkedInputStream; import org.restlet.engine.http.io.ChunkedOutputStream; import org.restlet.engine.http.io.ReadableEntityChannel; import org.restlet.engine.io.NioUtils; import com.sun.grizzly.util.InputReader; import com.sun.grizzly.util.OutputWriter; import com.sun.grizzly.util.SSLOutputWriter; /** * HTTP server call specialized for Grizzly. * * @author Jerome Louvel */ public class GrizzlyServerCall extends ServerCall { /** The NIO byte buffer. */ private final ByteBuffer byteBuffer; /** Recycled request stream. */ private final InputReader requestStream; /** The underlying socket channel. */ private final SocketChannel socketChannel; /** * Constructor. * * @param server * The parent server. * @param byteBuffer * The NIO byte buffer. * @param key * The NIO selection key. * @param confidential * Indicates if the call is confidential. */ public GrizzlyServerCall(Server server, ByteBuffer byteBuffer, SelectionKey key, boolean confidential) { super(server); setConfidential(confidential); this.byteBuffer = byteBuffer; this.requestStream = new InputReader(); this.requestStream.setSelectionKey(key); this.requestStream.setByteBuffer(byteBuffer); this.socketChannel = (SocketChannel) key.channel(); getRequestHeaders().clear(); try { // Read the request header readRequestHead(this.requestStream); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Unable to parse the HTTP request", ioe); } } @Override public void complete() { // Exhaust the socket channel before closing in case // the client is still writing to it // TODO: support NIO exhausting // ByteUtils.exhaust(getRequestEntityStream(getContentLength())); } @Override public String getClientAddress() { return getSocket().getInetAddress().getHostAddress(); } @Override public int getClientPort() { return getSocket().getPort(); } @Override public ReadableByteChannel getRequestEntityChannel(long size) { if (isRequestChunked()) { // Leave chunked encoding to the stream mode return null; } return new ReadableEntityChannel(this.byteBuffer, getSocketChannel(), size); } @Override public InputStream getRequestEntityStream(long size) { if (isRequestChunked()) { return new ChunkedInputStream(null, this.requestStream); } // Leave normal encoding to the channel mode return null; } @Override public ReadableByteChannel getRequestHeadChannel() { return getSocketChannel(); } @Override public InputStream getRequestHeadStream() { return null; } @Override public WritableByteChannel getResponseEntityChannel() { if (isResponseChunked()) { // Leave chunked encoding to the stream mode return null; } return getWritableChannel(); } @Override public OutputStream getResponseEntityStream() { if (isResponseChunked()) { return new ChunkedOutputStream(NioUtils .getStream(getWritableChannel())); } // Leave normal encoding to the channel mode return null; } /** * Returns the socket associated to the socket channel. * * @return The socket. */ private Socket getSocket() { return getSocketChannel().socket(); } /** * Returns the readable socket channel. * * @return The readable socket channel. */ private SocketChannel getSocketChannel() { return this.socketChannel; } @Override public String getSslCipherSuite() { Socket socket = getSocket(); if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; SSLSession sslSession = sslSocket.getSession(); if (sslSession != null) { return sslSession.getCipherSuite(); } } return null; } @Override public List getSslClientCertificates() { Socket socket = getSocket(); if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; SSLSession sslSession = sslSocket.getSession(); if (sslSession != null) { try { List clientCertificates = Arrays .asList(sslSession.getPeerCertificates()); return clientCertificates; } catch (SSLPeerUnverifiedException e) { getLogger().log(Level.FINE, "Can't get the client certificates.", e); } } } return null; } @Override protected byte[] getSslSessionIdBytes() { Socket socket = getSocket(); if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; SSLSession sslSession = sslSocket.getSession(); if (sslSession != null) { return sslSession.getId(); } } return null; } /** * Return the underlying socket channel. * * @return The underlying socket channel. */ public WritableByteChannel getWritableChannel() { if (isConfidential()) { return new WritableByteChannel() { public void close() throws IOException { } public boolean isOpen() { return getSocketChannel().isOpen(); } public int write(ByteBuffer src) throws IOException { int nWrite = src.limit(); SSLOutputWriter.flushChannel(getSocketChannel(), src); return nWrite; } }; } return getSocketChannel(); } @Override public void writeResponseHead(Response response) throws IOException { final ByteArrayOutputStream headStream = new ByteArrayOutputStream(8192); writeResponseHead(response, headStream); final ByteBuffer buffer = ByteBuffer.wrap(headStream.toByteArray()); if (isConfidential()) { SSLOutputWriter.flushChannel(getSocketChannel(), buffer); } else { OutputWriter.flushChannel(getSocketChannel(), buffer); } buffer.clear(); } /** * Closes the socket. */ @Override public boolean abort() { try { getSocket().close(); } catch (IOException e) { } return true; } } restlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/internal/HttpParserFilter.java0000664000175000017500000000677411757206352034035 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.grizzly.internal; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import org.restlet.ext.grizzly.GrizzlyServerHelper; import org.restlet.ext.grizzly.HttpsServerHelper; import com.sun.grizzly.Context; import com.sun.grizzly.ProtocolFilter; import com.sun.grizzly.util.WorkerThread; /** * HTTP parser filter for Grizzly. * * @author Jerome Louvel */ public class HttpParserFilter implements ProtocolFilter { /** The parent HTTP server helper. */ private volatile GrizzlyServerHelper helper; /** * Constructor. * * @param helper * The parent HTTP server helper. */ public HttpParserFilter(GrizzlyServerHelper helper) { this.helper = helper; } /** * Execute a call. * * @param context * The call's context. */ public boolean execute(Context context) throws IOException { // Create the HTTP call ByteBuffer byteBuffer = ((WorkerThread) Thread.currentThread()) .getByteBuffer(); byteBuffer.flip(); if (byteBuffer.hasRemaining()) { boolean keepAlive = false; SelectionKey key = context.getSelectionKey(); GrizzlyServerCall serverCall = new GrizzlyServerCall(this.helper .getHelped(), byteBuffer, key, (this.helper instanceof HttpsServerHelper)); // Handle the call this.helper.handle(serverCall); // TODO Should we use httpCall#isKeepAlive? // TODO The "keepAlive" boolean is always set to false at this time. // Prepare for additional calls? if (keepAlive) { context .setKeyRegistrationState(Context.KeyRegistrationState.REGISTER); } else { context .setKeyRegistrationState(Context.KeyRegistrationState.CANCEL); } } // Clean up byteBuffer.clear(); // This is the last filter return true; } /** * Post execute method. * * @param context * The call's context. */ public boolean postExecute(Context context) throws IOException { return true; } } restlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/GrizzlyServerHelper.java0000664000175000017500000001326111757206352032745 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.grizzly; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.restlet.Server; import org.restlet.engine.http.HttpServerHelper; import org.restlet.engine.io.NioUtils; import com.sun.grizzly.Controller; import com.sun.grizzly.ControllerStateListener; import com.sun.grizzly.TCPSelectorHandler; /** * Base Grizzly connector. * * @author Jerome Louvel */ public abstract class GrizzlyServerHelper extends HttpServerHelper { /** The Grizzly controller. */ private volatile Controller controller; /** The Grizzly TCP selector handler. */ private volatile TCPSelectorHandler selectorHandler; /** * Constructor. * * @param server * The server to help. */ public GrizzlyServerHelper(Server server) { super(server); this.controller = null; } /** * Returns the Grizzly TCP selector handler. * * @return The Grizzly TCP selector handler. */ public TCPSelectorHandler getSelectorHandler() { // Lazy initialization with double-check. TCPSelectorHandler s = this.selectorHandler; if (s == null) { synchronized (this) { s = this.selectorHandler; if (s == null) { this.selectorHandler = s = new TCPSelectorHandler(); } } } return s; } /** * Configures the Grizzly controller. * * @param controller * The controller to configure. */ protected abstract void configure(Controller controller) throws Exception; @Override public synchronized void start() throws Exception { super.start(); if (this.controller == null) { this.controller = new Controller(); // We should make this handler configurable via parameters this.controller.setSelectorHandler(getSelectorHandler()); // Configure a new controller configure(this.controller); } getLogger().info( "Starting the Grizzly " + getProtocols() + " server on port " + getHelped().getPort()); final CountDownLatch latch = new CountDownLatch(1); final Controller controller = this.controller; final TCPSelectorHandler selectorHandler = getSelectorHandler(); new Thread() { @Override public void run() { try { controller.addStateListener(new ControllerStateListener() { public void onException(Throwable arg0) { latch.countDown(); } public void onReady() { if (getHelped().getPort() == 0) { setEphemeralPort(selectorHandler.getPort()); } latch.countDown(); } public void onStarted() { } public void onStopped() { } }); controller.start(); } catch (IOException e) { getLogger().log(Level.WARNING, "Error while starting the Grizzly controller", e); } } }.start(); // Wait for the listener to start up and count down the latch // This blocks until the server is ready to receive connections try { if (!latch.await(NioUtils.NIO_TIMEOUT, TimeUnit.MILLISECONDS)) { // Timeout detected getLogger() .warning( "The calling thread timed out while waiting for the connector to be ready to accept connections."); } } catch (InterruptedException ex) { getLogger() .log(Level.WARNING, "Interrupted while waiting for starting latch. Stopping...", ex); stop(); } } @Override public synchronized void stop() throws Exception { super.stop(); if (this.controller != null) { getLogger().info( "Stopping the Grizzly " + getProtocols() + " server"); this.controller.stop(); } } } restlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/package.html0000664000175000017500000000041411757206352030356 0ustar jamespagejamespage Integration with Grizzly NIO framework 1.9. The Grizzly framework has been designed to help developers to take advantage of the Java NIO API. @since Restlet 1.1 @see Grizzly Framework restlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/HttpsServerHelper.java0000664000175000017500000002031011757206352032366 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.grizzly; import java.io.File; import java.net.InetAddress; import javax.net.ssl.SSLContext; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.security.SslUtils; import org.restlet.engine.security.SslContextFactory; import org.restlet.ext.grizzly.internal.HttpParserFilter; import com.sun.grizzly.Controller; import com.sun.grizzly.DefaultProtocolChain; import com.sun.grizzly.DefaultProtocolChainInstanceHandler; import com.sun.grizzly.ProtocolChain; import com.sun.grizzly.TCPSelectorHandler; import com.sun.grizzly.filter.SSLReadFilter; /** * HTTPS connector based on Grizzly. Here is the list of additional parameters * that are supported. They should be set in the Server's context before it is * started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    sslContextFactoryStringnullLet you specify a {@link SslContextFactory} class name as a parameter, or * an instance as an attribute for a more complete and flexible SSL context * setting. If set, it takes precedence over the other SSL parameters below.
    keystorePathString${user.home}/.keystoreSSL keystore path.
    keystorePasswordStringSSL keystore password.
    keystoreTypeStringJKSSSL keystore type
    keyPasswordString${keystorePassword}SSL key password.
    certAlgorithmStringSunX509SSL certificate algorithm.
    enabledCipherSuitesStringnullWhitespace-separated list of enabled cipher suites and/or can be * specified multiple times.
    needClientAuthenticationbooleanfalseIndicates if we require client certificate authentication.
    sslProtocolStringTLSSSL protocol.
    wantClientAuthenticationbooleanfalseIndicates if we would like client certificate authentication (only for * the BIO connector type).
    * * @author Jerome Louvel */ public class HttpsServerHelper extends GrizzlyServerHelper { /** * Constructor. * * @param server * The helped server. */ public HttpsServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTPS); } @Override protected void configure(Controller controller) throws Exception { // Initialize the SSL context SslContextFactory sslContextFactory = SslUtils .getSslContextFactory(this); SSLContext sslContext = sslContextFactory.createSslContext(); // Get the TCP select handler of the controller final TCPSelectorHandler selectorHandler = getSelectorHandler(); // Configure it selectorHandler.setPort(getHelped().getPort()); if (getHelped().getAddress() != null) { selectorHandler.setInet(InetAddress.getByName(getHelped() .getAddress())); } // Create the Grizzly filters final SSLReadFilter readFilter = new SSLReadFilter(); readFilter.setSSLContext(sslContext); final String[] enabledCipherSuites = SslUtils .getEnabledCipherSuites(this); if (enabledCipherSuites != null) { readFilter.setEnabledCipherSuites(enabledCipherSuites); } if (isNeedClientAuthentication()) { readFilter.setNeedClientAuth(isNeedClientAuthentication()); } else if (isWantClientAuthentication()) { readFilter.setWantClientAuth(isWantClientAuthentication()); } final HttpParserFilter httpParserFilter = new HttpParserFilter(this); // Create the Grizzly controller controller .setProtocolChainInstanceHandler(new DefaultProtocolChainInstanceHandler() { @Override public ProtocolChain poll() { ProtocolChain protocolChain = this.protocolChains .poll(); if (protocolChain == null) { protocolChain = new DefaultProtocolChain(); protocolChain.addFilter(readFilter); protocolChain.addFilter(httpParserFilter); } return protocolChain; } }); } /** * Returns the SSL certificate algorithm. * * @return The SSL certificate algorithm. */ @Deprecated public String getCertAlgorithm() { return getHelpedParameters().getFirstValue("certAlgorithm", "SunX509"); } /** * Returns the SSL key password. * * @return The SSL key password. */ @Deprecated public String getKeyPassword() { return getHelpedParameters().getFirstValue("keyPassword", getKeystorePassword()); } /** * Returns the SSL keystore password. * * @return The SSL keystore password. */ @Deprecated public String getKeystorePassword() { return getHelpedParameters().getFirstValue("keystorePassword", ""); } /** * Returns the SSL keystore path. * * @return The SSL keystore path. */ @Deprecated public String getKeystorePath() { return getHelpedParameters().getFirstValue("keystorePath", System.getProperty("user.home") + File.separator + ".keystore"); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getKeystoreType() { return getHelpedParameters().getFirstValue("keystoreType", "JKS"); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getSslProtocol() { return getHelpedParameters().getFirstValue("sslProtocol", "TLS"); } /** * Indicates if we require client certificate authentication. * * @return True if we require client certificate authentication. */ public boolean isNeedClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "needClientAuthentication", "false")); } /** * Indicates if we would like client certificate authentication. * * @return True if we would like client certificate authentication. */ public boolean isWantClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "wantClientAuthentication", "false")); } } restlet-2.0.14/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/HttpServerHelper.java0000664000175000017500000000651411757206352032215 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.grizzly; import java.net.InetAddress; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.ext.grizzly.internal.HttpParserFilter; import com.sun.grizzly.Controller; import com.sun.grizzly.DefaultProtocolChain; import com.sun.grizzly.DefaultProtocolChainInstanceHandler; import com.sun.grizzly.ProtocolChain; import com.sun.grizzly.TCPSelectorHandler; import com.sun.grizzly.filter.ReadFilter; /** * HTTP connector based on Grizzly. * * @author Jerome Louvel */ public class HttpServerHelper extends GrizzlyServerHelper { /** * Constructor. * * @param server * The helped server. */ public HttpServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTP); } @Override protected void configure(Controller controller) throws Exception { // Get the TCP select handler of the controller TCPSelectorHandler selectorHandler = getSelectorHandler(); // Configure it selectorHandler.setPort(getHelped().getPort()); if (getHelped().getAddress() != null) { selectorHandler.setInet(InetAddress.getByName(getHelped() .getAddress())); } // Create the Grizzly filters final ReadFilter readFilter = new ReadFilter(); final HttpParserFilter httpParserFilter = new HttpParserFilter(this); // Create the Grizzly controller controller .setProtocolChainInstanceHandler(new DefaultProtocolChainInstanceHandler() { @Override public ProtocolChain poll() { ProtocolChain protocolChain = this.protocolChains .poll(); if (protocolChain == null) { protocolChain = new DefaultProtocolChain(); protocolChain.addFilter(readFilter); protocolChain.addFilter(httpParserFilter); } return protocolChain; } }); } } restlet-2.0.14/org.restlet.ext.netty/0000775000175000017500000000000012001473177020147 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/pom.xml0000600000175000017500000000155212001473176021454 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.netty Restlet Extension - Netty Integration with Netty. org.jboss.netty netty 3.2.2 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.netty/src/0000775000175000017500000000000012001473176020735 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/src/META-INF/0000775000175000017500000000000011757206452022105 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/src/META-INF/services/0000775000175000017500000000000011757206352023727 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/src/META-INF/services/org.restlet.engine.ServerHelper0000664000175000017500000000014011757206352031766 0ustar jamespagejamespageorg.restlet.ext.netty.HttpServerHelper # HTTP org.restlet.ext.netty.HttpsServerHelper # HTTPS restlet-2.0.14/org.restlet.ext.netty/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023536 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.netty/src/org/0000775000175000017500000000000011757206352021533 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/0000775000175000017500000000000011757206352023215 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/0000775000175000017500000000000011757206352024015 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/0000775000175000017500000000000011757206352025160 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/0000775000175000017500000000000011757206352026774 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/HttpServerPipelineFactory.javarestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/HttpServerPipelineFactory.ja0000664000175000017500000000544411757206352034443 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty.internal; import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpChunkAggregator; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.stream.ChunkedWriteHandler; import org.restlet.ext.netty.NettyServerHelper; /** * HTTP server pipeline factory. * * @author Gabriel Ciuloaica (gciuloaica@gmail.com) * @author Jerome Louvel */ public class HttpServerPipelineFactory implements ChannelPipelineFactory { /** The server helper. */ private final NettyServerHelper helper; /** * Constructor. * * @param serverHelper * The server helper. */ public HttpServerPipelineFactory(NettyServerHelper serverHelper) { this.helper = serverHelper; } /** * Implements the {@link ChannelPipelineFactory#getPipeline()} method. * * @return The channel pipeline. */ public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("aggregator", new HttpChunkAggregator(65536)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("streamer", new ChunkedWriteHandler()); pipeline.addLast("handler", new HttpRequestHandler(this.helper)); return pipeline; } } restlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/NettyParams.java0000664000175000017500000001063411757206352032112 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty.internal; import java.lang.reflect.Constructor; import org.jboss.netty.buffer.ChannelBufferFactory; /** * Helper class that convert from Restlet options to Netty channel options. * * @author Gabriel Ciuloaica (gciuloaica@gmail.com) */ public enum NettyParams { keepAlive(Boolean.class, true), bufferFactoryClass( ChannelBufferFactory.class, true), connectTimeoutMillis( Integer.class, true), reuseAddress(Boolean.class, true), receiveBufferSize( Integer.class, true), sendBufferSize(Integer.class, true), trafficClass( Integer.class, true), sslContextFactory(String.class, false), keystorePath( String.class, false), keystorePassword(String.class, false), keyPassword( String.class, false), keystoreType(String.class, false), truststorePath( String.class, false), truststorePassword(String.class, false), certAlgorithm( String.class, false), sslProtocol(String.class, false), needClientAuthentication( String.class, false), wantClientAuthentication(String.class, false); /** The parameter type class. */ private final Class paramType; /** Is the parameter a channel configuration option? */ private final Boolean isChannelOption; /** * Private constructor. * * @param type * The parameter type class. * @param isChannelParam * The parameter is channel parameter or not. */ private NettyParams(Class type, Boolean isChannelParam) { this.paramType = type; this.isChannelOption = isChannelParam; } /** *

    * Get converted value from a string option value. *

    * * @param value * - option value * @return Object instance */ public Object getValue(String value) { Object ret = null; try { Constructor constructor = paramType.getConstructor(String.class); ret = constructor.newInstance(value); } catch (Exception e) { } if (ret == null) { ret = instantiateClass(value); } return ret; } /** *

    * Instantiate the class specified in the option value. *

    * * @param value * - fully qualified class name. * @return class instance */ private Object instantiateClass(String value) { Object ret = null; Class factory = null; try { factory = getClass().getClassLoader().loadClass(value); } catch (ClassNotFoundException e) { } if (factory != null) { try { Constructor constructor = factory.getConstructor(); final Object ref = constructor.newInstance(); if (ref instanceof ChannelBufferFactory) { ret = ref; } } catch (Exception e) { } } return ret; } /** * Is this a channel option or not? * * @return true if the parameter is a channel option or false otherwise */ public Boolean isChannelOption() { return isChannelOption; } } restlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/NettyServerCall.java0000664000175000017500000002027211757206352032730 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty.internal; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.security.cert.Certificate; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.logging.Level; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferInputStream; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.restlet.Response; import org.restlet.Server; import org.restlet.data.Parameter; import org.restlet.engine.http.ServerCall; import org.restlet.util.Series; /** * Call that is used by the Netty HTTP server connectors. * * @author Gabriel Ciuloaica (gciuloaica@gmail.com) * @author Jerome Louvel */ public class NettyServerCall extends ServerCall { /** The Netty HTTP request. */ private final HttpRequest request; /** The Netty HTTP response. */ private HttpResponse response; /** The content buffer. */ private final ChannelBuffer contentBuffer; /** The Netty message event. */ private final MessageEvent messageEvent; /** Indicates if HTTP request headers were added. */ private volatile boolean requestHeadersAdded; /** The underlying SSL engine. */ private final SSLEngine sslEngine; /** The remote client IP address. */ private final InetSocketAddress remoteAddress; /** The Restlet response. */ private Response restletResponse; /** * Constructor. * * @param server * The helped server. * @param messageEvent * The message event received. * @param contentBuffer * The content buffer. * @param request * The Netty request. * @param clientAddress * client information. * @param isConfidential * Indicates if the call is confidential or not. * @param sslEngine * The SSL engine. */ public NettyServerCall(Server server, MessageEvent messageEvent, ChannelBuffer contentBuffer, HttpRequest request, InetSocketAddress clientAddress, boolean isConfidential, SSLEngine sslEngine) { super(server); setConfidential(isConfidential); this.contentBuffer = contentBuffer; this.messageEvent = messageEvent; this.request = request; this.sslEngine = sslEngine; this.remoteAddress = clientAddress; } /** * Closes the socket. */ @Override public boolean abort() { messageEvent.getChannel().close(); return true; } @Override public String getClientAddress() { return this.remoteAddress.getAddress().getHostAddress(); } @Override public int getClientPort() { return this.remoteAddress.getPort(); } @Override public String getMethod() { return request.getMethod().getName(); } @Override public ReadableByteChannel getRequestEntityChannel(long size) { return null; } @Override public InputStream getRequestEntityStream(long size) { return new ChannelBufferInputStream(contentBuffer); } @Override public ReadableByteChannel getRequestHeadChannel() { return null; } @Override public Series getRequestHeaders() { final Series result = super.getRequestHeaders(); if (!this.requestHeadersAdded) { final Set names = this.request.getHeaderNames(); for (String name : names) { result.add(new Parameter(name, this.request.getHeader(name))); } this.requestHeadersAdded = true; } return result; } @Override public InputStream getRequestHeadStream() { return null; } @Override public String getRequestUri() { return request.getUri(); } /** * Get response. * * @return the response */ public HttpResponse getResponse() { return response; } @Override public WritableByteChannel getResponseEntityChannel() { return null; } @Override public OutputStream getResponseEntityStream() { return null; } /** * Returns the Restlet response. * * @return The Restlet response. */ public Response getRestletResponse() { return restletResponse; } @Override public String getSslCipherSuite() { final SSLEngine sslEngine = getSslEngine(); if (sslEngine != null) { final SSLSession sslSession = sslEngine.getSession(); if (sslSession != null) { return sslSession.getCipherSuite(); } } return null; } @Override public List getSslClientCertificates() { final SSLEngine sslEngine = getSslEngine(); if (sslEngine != null) { final SSLSession sslSession = sslEngine.getSession(); if (sslSession != null) { try { final List clientCertificates = Arrays .asList(sslSession.getPeerCertificates()); return clientCertificates; } catch (SSLPeerUnverifiedException e) { getLogger().log(Level.FINE, "Can't get the client certificates.", e); } } } return null; } /** * Returns the SSL engine. * * @return The SSL engine. */ private SSLEngine getSslEngine() { return this.sslEngine; } @Override protected byte[] getSslSessionIdBytes() { final SSLEngine sslEngine = getSslEngine(); if (sslEngine != null) { final SSLSession sslSession = sslEngine.getSession(); if (sslSession != null) { return sslSession.getId(); } } return null; } @Override public String getVersion() { return request.getProtocolVersion().getText(); } @Override protected boolean isClientKeepAlive() { return HttpHeaders.isKeepAlive(request); } @Override public void sendResponse(Response response) throws IOException { setRestletResponse(response); } /** * Sets the Restlet response. * * @param restletResponse * The Restlet response. */ public void setRestletResponse(Response restletResponse) { this.restletResponse = restletResponse; } @Override public void writeResponseHead(Response restletResponse) throws IOException { } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/HttpsServerPipelineFactory.javarestlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/HttpsServerPipelineFactory.j0000664000175000017500000000615311757206352034463 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty.internal; import static org.jboss.netty.channel.Channels.pipeline; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.handler.stream.ChunkedWriteHandler; import org.restlet.ext.netty.NettyServerHelper; /** * HTTPS channel pipeline factory. * * @author Gabriel Ciuloaica (gciuloaica@gmail.com) */ public class HttpsServerPipelineFactory implements ChannelPipelineFactory { /** The server helper. */ private final NettyServerHelper helper; /** The SSL context. */ private final SSLContext sslContext; /** * Constructor. * * @param serverHelper * The server helper. * @param sslContext * The SSL context. */ public HttpsServerPipelineFactory(NettyServerHelper serverHelper, SSLContext sslContext) { this.helper = serverHelper; this.sslContext = sslContext; } /** * Implements the {@link ChannelPipelineFactory#getPipeline()} method. * * @return The channel pipeline. */ public ChannelPipeline getPipeline() throws Exception { SSLEngine sslEngine = this.sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); ChannelPipeline pipeline = pipeline(); pipeline.addLast("ssl", new SslHandler(sslEngine)); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("streamer", new ChunkedWriteHandler()); pipeline.addLast("handler", new HttpRequestHandler(this.helper)); return pipeline; } } restlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/internal/HttpRequestHandler.java0000664000175000017500000002625211757206352033434 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty.internal; import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Arrays; import javax.net.ssl.SSLEngine; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.frame.TooLongFrameException; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpVersion; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.handler.stream.ChunkedStream; import org.restlet.Response; import org.restlet.data.Parameter; import org.restlet.engine.ConnectorHelper; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.ext.netty.HttpsServerHelper; import org.restlet.ext.netty.NettyServerHelper; import org.restlet.representation.Representation; import org.restlet.service.ConnectorService; /** * HTTP request handler implementation. Pass HTTP requests to Restlet and gather * HTTP response from Restlet and provide it back to the client. * * @author Gabriel Ciuloaica (gciuloaica@gmail.com) * @author Jerome Louvel */ @ChannelHandler.Sharable public class HttpRequestHandler extends SimpleChannelUpstreamHandler { /** * Carriage return */ static final byte CR = 13; /** Line feed character. */ static final byte LF = 10; /** The server helper. */ private volatile NettyServerHelper helper; /** Indicates if chunked encoding should be read. */ private volatile boolean readingChunks; /** The Netty HTTP request. */ private volatile HttpRequest request; /** Content accumulator. */ private volatile ChannelBuffer content; /** Client address. */ private volatile InetSocketAddress clientAddress; /** * Constructor. Creates a new handler instance wrapping server helper. * * @param serverHelper * The server helper. */ public HttpRequestHandler(NettyServerHelper serverHelper) { this.helper = serverHelper; } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel ch = e.getChannel(); Throwable cause = e.getCause(); if (cause instanceof TooLongFrameException) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } cause.printStackTrace(); if (ch.isConnected()) { sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception { if (clientAddress == null) { clientAddress = (InetSocketAddress) messageEvent.getRemoteAddress(); } boolean lastChunk = false; if (!readingChunks) { request = (HttpRequest) messageEvent.getMessage(); if (request.isChunked()) { readingChunks = true; } else { content = request.getContent(); } } else { HttpChunk chunk = (HttpChunk) messageEvent.getMessage(); if (chunk.isLast()) { readingChunks = false; lastChunk = true; } else { content.writeBytes(chunk.getContent()); } } if (content == null) { content = ChannelBuffers.dynamicBuffer(); } HttpResponse nettyResponse = null; NettyServerCall httpCall = null; // Let the Restlet engine handle this call only after last chunk has // been read. if ((!request.isChunked()) || lastChunk) { SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class); SSLEngine sslEngine = sslHandler == null ? null : sslHandler .getEngine(); httpCall = new NettyServerCall(this.helper.getHelped(), messageEvent, content, request, clientAddress, (this.helper instanceof HttpsServerHelper), sslEngine); this.helper.handle(httpCall); nettyResponse = httpCall.getResponse(); Response restletResponse = httpCall.getRestletResponse(); if (restletResponse != null) { // Get the connector service to callback Representation responseEntity = restletResponse.getEntity(); ConnectorService connectorService = ConnectorHelper .getConnectorService(); if (connectorService != null) { connectorService.beforeSend(responseEntity); } try { if (nettyResponse != null) { nettyResponse.clearHeaders(); } else { HttpResponseStatus status = new HttpResponseStatus( restletResponse.getStatus().getCode(), restletResponse.getStatus().getName()); nettyResponse = new DefaultHttpResponse( HttpVersion.HTTP_1_1, status); } // Copy general, response and entity headers for (Parameter header : httpCall.getResponseHeaders()) { nettyResponse.addHeader(header.getName(), header.getValue()); } // Check if 'Transfer-Encoding' header should be set if (httpCall.shouldResponseBeChunked(restletResponse)) { nettyResponse.addHeader( HeaderConstants.HEADER_TRANSFER_ENCODING, "chunked"); } // Write the response Channel ch = messageEvent.getChannel(); ChannelFuture future = null; if (responseEntity != null) { if (nettyResponse.isChunked()) { nettyResponse.setContent(null); future = ch.write(nettyResponse); ch.write(new ChunkedStream(restletResponse .getEntity().getStream())); } else { ChannelBuffer buf = dynamicBuffer(); buf.writeBytes(responseEntity.getStream(), (int) responseEntity.getAvailableSize()); nettyResponse.setContent(buf); future = ch.write(nettyResponse); } } // Close the connection after the write operation is done. if (shouldCloseConnection()) { future.addListener(ChannelFutureListener.CLOSE); } } finally { if (responseEntity != null) { responseEntity.release(); } if (connectorService != null) { connectorService.afterSend(responseEntity); } } } } } private boolean shouldCloseConnection() { boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request .getHeader(HttpHeaders.Names.CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request .getHeader(HttpHeaders.Names.CONNECTION)); return close; } /** * Sends an error to the client. * * @param ctx * The handler context. * @param status * The HTTP status. */ private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent(ChannelBuffers.copiedBuffer( "Failure: " + status.toString() + "\r\n", Charset.forName("UTF-8"))); // Close the connection as soon as the error message is sent. ctx.getChannel().write(response) .addListener(ChannelFutureListener.CLOSE); } /** * Convert a long value to hex byte array. * * @param l * - value to be converted * @return hex representation */ public static byte[] longToHex(final long l) { long v = l & 0xFFFFFFFFFFFFFFFFL; byte[] result = new byte[16]; Arrays.fill(result, 0, result.length, (byte) 0); for (int i = 0; i < result.length; i += 2) { byte b = (byte) ((v & 0xFF00000000000000L) >> 56); byte b2 = (byte) (b & 0x0F); byte b1 = (byte) ((b >> 4) & 0x0F); if (b1 > 9) b1 += 39; b1 += 48; if (b2 > 9) b2 += 39; b2 += 48; result[i] = (byte) (b1 & 0xFF); result[i + 1] = (byte) (b2 & 0xFF); v <<= 8; } return result; } } restlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/NettyServerHelper.java0000664000175000017500000001554211757206352031464 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import java.util.logging.Level; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.restlet.Server; import org.restlet.data.Parameter; import org.restlet.engine.http.HttpServerHelper; import org.restlet.ext.netty.internal.NettyParams; import org.restlet.util.Series; /** * Abstract Netty Web server connector. Parameters, listed below, are used to * configure both a parent channel and its child channels. To configure the * child channels, prepend "child." prefix to the actual parameter names of a * child channel. They should be set in the Server's context before it is * started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    bufferFactoryClassStringorg.jboss.netty.buffer.HeapChannelBufferFactoryChannel buffer allocation strategy.
    connectTimeoutMillisint0Connect timeout of the channel in milliseconds. Sets to 0 to disable it.
    keepAlivebooleanfalseTurn on/off socket keep alive.
    reuseAddressbooleanfalseEnable/Disable reuse address for socket.
    receiveBufferSizeint0Provide the size of the buffer actually used by the platform when * receiving in data on this socket.
    sendBufferSizeint0Set a hint the size of the underlying buffers for outgoing network I/O.
    trafficClassint0Sets traffic class or type-of-service octet in the IP header for packets * sent from this Socket. As the underlying network implementation may ignore * this value applications should consider it a hint.
    * * @see Netty home page * @author Gabriel Ciuloaica (gciuloaica@gmail.com) */ public abstract class NettyServerHelper extends HttpServerHelper { private static final String CHILD_CHANNEL_PREFIX = "child."; private static final String RESTLET_NETTY_SERVER = "restlet-netty-server"; private ChannelGroup allChannels = new DefaultChannelGroup( RESTLET_NETTY_SERVER); private ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); /** * Constructor. * * @param server * The server that will be helped. */ public NettyServerHelper(Server server) { super(server); } /** * Returns the Netty pipeline factory. * * @return The Netty pipeline factory. */ protected abstract ChannelPipelineFactory getPipelineFatory(); @Override public synchronized void start() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(factory); bootstrap.setPipelineFactory(getPipelineFatory()); // Copy the parameters as channel options setServerParameters(bootstrap); int port = getHelped().getPort(); Channel channel = bootstrap.bind(new InetSocketAddress(port)); InetSocketAddress address = (InetSocketAddress) channel .getLocalAddress(); setEphemeralPort(address.getPort()); allChannels.add(channel); getLogger().log( Level.INFO, "Started Netty " + getProtocols() + " server on port " + getHelped().getPort()); } /** *

    * Pass netty channel parameters through bootstrap. *

    * * @param bootstrap * - server bootstrap instance */ private void setServerParameters(final ServerBootstrap bootstrap) { Series options = getHelpedParameters(); for (Parameter option : options) { String paramName = option.getName(); if (paramName.startsWith(CHILD_CHANNEL_PREFIX)) { paramName = option.getName().substring( CHILD_CHANNEL_PREFIX.length()); } try { NettyParams param = NettyParams.valueOf(paramName); if (param != null) { final Object value = param.getValue(option.getValue()); if ((value != null) && (param.isChannelOption())) { bootstrap.setOption(option.getName(), value); } } } catch (IllegalArgumentException iae) { getLogger() .log(Level.FINE, "Unable to process the \"" + paramName + "\" parameter"); } } } @Override public synchronized void stop() throws Exception { ChannelGroupFuture future = allChannels.close(); future.awaitUninterruptibly(); factory.releaseExternalResources(); getLogger().log(Level.INFO, "Stopped Netty " + getProtocols() + " server"); super.stop(); } } restlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/package.html0000664000175000017500000000031211757206352027435 0ustar jamespagejamespage Integration with Netty 3.1. Netty is a new client and server NIO framework. @since Restlet 2.0 @see Netty NIO server restlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/HttpsServerHelper.java0000664000175000017500000001450311757206352031457 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty; import java.io.File; import javax.net.ssl.SSLContext; import org.jboss.netty.channel.ChannelPipelineFactory; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.security.SslUtils; import org.restlet.engine.security.SslContextFactory; import org.restlet.ext.netty.internal.HttpsServerPipelineFactory; /** * Netty HTTPS server connector. Here is the list of additional parameters that * are supported. They should be set in the Server's context before it is * started: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Parameter nameValue typeDefault valueDescription
    certAlgorithmStringSunX509SSL certificate algorithm
    keyPasswordStringSSL key password
    keystorePasswordStringSSL keystore password
    keystorePathString${user.home}/.keystoreSSL keystore path
    keystoreTypeStringJKSSSL keystore type
    sslProtocolStringTLSSSL protocol
    needClientAuthenticationbooleanfalseIndicates if we require client certificate authentication
    wantClientAuthenticationbooleanfalseIndicates if we would like client certificate authentication
    * * @see Netty home page * @author Gabriel Ciuloaica (gciuloaica@gmail.com) */ public class HttpsServerHelper extends NettyServerHelper { /** * This is the SSL context. */ private SSLContext sslContext; /** * Constructor. * * @param server * The helped server. */ public HttpsServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTPS); } /** * Returns the SSL certificate algorithm. * * @return The SSL certificate algorithm. */ @Deprecated public String getCertAlgorithm() { return getHelpedParameters().getFirstValue("certAlgorithm", "SunX509"); } /** * Returns the SSL key password. * * @return The SSL key password. */ @Deprecated public String getKeyPassword() { return getHelpedParameters().getFirstValue("keyPassword", ""); } /** * Returns the SSL keystore password. * * @return The SSL keystore password. */ @Deprecated public String getKeystorePassword() { return getHelpedParameters().getFirstValue("keystorePassword", ""); } /** * Returns the SSL keystore path. * * @return The SSL keystore path. */ @Deprecated public String getKeystorePath() { return getHelpedParameters().getFirstValue("keystorePath", System.getProperty("user.home") + File.separator + ".keystore"); } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getKeystoreType() { return getHelpedParameters().getFirstValue("keystoreType", "JKS"); } @Override public ChannelPipelineFactory getPipelineFatory() { return new HttpsServerPipelineFactory(this, getSslContext()); } /** * Gets the SSL context used by this server. * * @return this returns the SSL context. */ public SSLContext getSslContext() { return sslContext; } /** * Returns the SSL keystore type. * * @return The SSL keystore type. */ @Deprecated public String getSslProtocol() { return getHelpedParameters().getFirstValue("sslProtocol", "TLS"); } /** * Indicates if we require client certificate authentication. * * @return True if we require client certificate authentication. */ public boolean isNeedClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "needClientAuthentication", "false")); } /** * Indicates if we would like client certificate authentication. * * @return True if we would like client certificate authentication. */ public boolean isWantClientAuthentication() { return Boolean.parseBoolean(getHelpedParameters().getFirstValue( "wantClientAuthentication", "false")); } /** * Sets the SSL context for the server. * * @param sslContext * the SSL context */ public void setSslContext(SSLContext sslContext) { this.sslContext = sslContext; } @Override public void start() throws Exception { // Initialize the SSL context SslContextFactory sslContextFactory = SslUtils .getSslContextFactory(this); sslContext = sslContextFactory.createSslContext(); super.start(); } } restlet-2.0.14/org.restlet.ext.netty/src/org/restlet/ext/netty/HttpServerHelper.java0000664000175000017500000000376311757206352031302 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.netty; import org.jboss.netty.channel.ChannelPipelineFactory; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.ext.netty.internal.HttpServerPipelineFactory; /** * Netty HTTP server connector. * * @see Netty home page * @author Gabriel Ciuloaica (gciuloaica@gmail.com) */ public class HttpServerHelper extends NettyServerHelper { /** * Constructor. * * @param server * The helped server instance. */ public HttpServerHelper(Server server) { super(server); getProtocols().add(Protocol.HTTP); } @Override public ChannelPipelineFactory getPipelineFatory() { return new HttpServerPipelineFactory(this); } } restlet-2.0.14/org.restlet.ext.xstream/0000775000175000017500000000000012001473137020463 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xstream/pom.xml0000600000175000017500000000222612001473137021770 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.xstream Restlet Extension - XStream Integration with XStream. org.codehaus.jettison jettison 1.2 javax.xml.stream stax-api 1.0-2 com.thoughtworks.xstream xstream 1.3.1 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.xstream/src/0000775000175000017500000000000012001473137021252 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xstream/src/META-INF/0000775000175000017500000000000011757206452022425 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xstream/src/META-INF/services/0000775000175000017500000000000011757206346024252 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.ext.xstream/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.xstream/src/META-INF/services/org.restlet.engine.converter.ConverterH0000664000175000017500000000005011757206346033770 0ustar jamespagejamespageorg.restlet.ext.xstream.XstreamConverterrestlet-2.0.14/org.restlet.ext.xstream/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450024056 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.xstream/src/org/0000775000175000017500000000000011757206346022056 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xstream/src/org/restlet/0000775000175000017500000000000011757206346023540 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xstream/src/org/restlet/ext/0000775000175000017500000000000011757206346024340 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xstream/src/org/restlet/ext/xstream/0000775000175000017500000000000011757206346026023 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamConverter.java0000664000175000017500000002050011757206346032176 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xstream; import java.io.IOException; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between the XML/JSON and Representation classes based on XStream. * * @author Jerome Louvel */ public class XstreamConverter extends ConverterHelper { private static final VariantInfo VARIANT_APPLICATION_ALL_XML = new VariantInfo( MediaType.APPLICATION_ALL_XML); private static final VariantInfo VARIANT_APPLICATION_XML = new VariantInfo( MediaType.APPLICATION_XML); private static final VariantInfo VARIANT_JSON = new VariantInfo( MediaType.APPLICATION_JSON); private static final VariantInfo VARIANT_TEXT_XML = new VariantInfo( MediaType.TEXT_XML); /** * Creates the marshaling {@link XstreamRepresentation}. * * @param * @param mediaType * The target media type. * @param source * The source object to marshal. * @return The marshaling {@link XstreamRepresentation}. */ protected XstreamRepresentation create(MediaType mediaType, T source) { return new XstreamRepresentation(mediaType, source); } /** * Creates the unmarshaling {@link XstreamRepresentation}. * * @param * @param source * The source representation to unmarshal. * @return The unmarshaling {@link XstreamRepresentation}. */ protected XstreamRepresentation create(Representation source) { return new XstreamRepresentation(source); } @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_JSON.isCompatible(source) || VARIANT_APPLICATION_ALL_XML.isCompatible(source) || VARIANT_APPLICATION_XML.isCompatible(source) || VARIANT_TEXT_XML.isCompatible(source)) { result = addObjectClass(result, Object.class); result = addObjectClass(result, XstreamRepresentation.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (source != null) { result = addVariant(result, VARIANT_JSON); result = addVariant(result, VARIANT_APPLICATION_ALL_XML); result = addVariant(result, VARIANT_APPLICATION_XML); result = addVariant(result, VARIANT_TEXT_XML); } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source instanceof XstreamRepresentation) { result = 1.0F; } else { if (target == null) { result = 0.5F; } else if (VARIANT_JSON.isCompatible(target)) { result = 0.8F; } else if (VARIANT_APPLICATION_ALL_XML.isCompatible(target) || VARIANT_APPLICATION_XML.isCompatible(target) || VARIANT_TEXT_XML.isCompatible(target)) { result = 0.8F; } else { result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (target != null) { if (source instanceof XstreamRepresentation) { result = 1.0F; } else if (XstreamRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if (VARIANT_JSON.isCompatible(source)) { result = 0.8F; } else if (VARIANT_APPLICATION_ALL_XML.isCompatible(source) || VARIANT_APPLICATION_XML.isCompatible(source) || VARIANT_TEXT_XML.isCompatible(source)) { result = 0.8F; } } else { result = 0.5F; } return result; } @SuppressWarnings("unchecked") @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; // The source for the XStream conversion XstreamRepresentation xstreamSource = null; if (source instanceof XstreamRepresentation) { xstreamSource = (XstreamRepresentation) source; } else if (VARIANT_JSON.isCompatible(source)) { xstreamSource = create(source); } else if (VARIANT_APPLICATION_ALL_XML.isCompatible(source) || VARIANT_APPLICATION_XML.isCompatible(source) || VARIANT_TEXT_XML.isCompatible(source)) { xstreamSource = create(source); } if (xstreamSource != null) { // Handle the conversion if ((target != null) && XstreamRepresentation.class.isAssignableFrom(target)) { result = xstreamSource; } else { if (target != null) { // XStream 1.3.1 does not process annotations when called // using fromXML(InputStream) despite autoProcessAnnotations // being set to "true". This call forces the processing. xstreamSource.getXstream().processAnnotations(target); } result = xstreamSource.getObject(); } } return (T) result; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; if (source instanceof XstreamRepresentation) { result = (XstreamRepresentation) source; } else { if (target.getMediaType() == null) { target.setMediaType(MediaType.TEXT_XML); } if (VARIANT_JSON.isCompatible(target)) { XstreamRepresentation xstreamRepresentation = create( target.getMediaType(), source); result = xstreamRepresentation; } else if (VARIANT_APPLICATION_ALL_XML.isCompatible(target) || VARIANT_APPLICATION_XML.isCompatible(target) || VARIANT_TEXT_XML.isCompatible(target)) { result = create(target.getMediaType(), source); } } return result; } @Override public void updatePreferences(List> preferences, Class entity) { updatePreferences(preferences, MediaType.APPLICATION_ALL_XML, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_JSON, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_XML, 1.0F); updatePreferences(preferences, MediaType.TEXT_XML, 1.0F); } } restlet-2.0.14/org.restlet.ext.xstream/src/org/restlet/ext/xstream/package.html0000664000175000017500000000045611757206346030311 0ustar jamespagejamespage Integration with XStream 1.3. XStream is a simple library to serialize objects to XML and back again. It also supports JSON via a dependency on Jettison, a Stax driver for JSON. @since Restlet 2.0 @see XStream Web site restlet-2.0.14/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java0000664000175000017500000001653411757206346033245 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.xstream; import java.io.IOException; import java.io.Writer; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.xml.DomDriver; /** * Representation based on the XStream library. It can serialize and deserialize * automatically in XML. It also supports a bridge to JSON leveraging the * Jettison library. * * @see XStream project * @author Jerome Louvel * @param * The type to wrap. */ public class XstreamRepresentation extends WriterRepresentation { /** The XStream JSON driver class. */ private Class jsonDriverClass; /** The (parsed) object to format. */ private T object; /** The representation to parse. */ private Representation representation; /** The XStream XML driver class. */ private Class xmlDriverClass; /** The modifiable XStream object. */ private XStream xstream; /** * Constructor. * * @param mediaType * The target media type. * @param object * The object to format. */ public XstreamRepresentation(MediaType mediaType, T object) { super(mediaType); this.object = object; this.representation = null; this.jsonDriverClass = JettisonMappedXmlDriver.class; this.xmlDriverClass = DomDriver.class; this.xstream = null; } /** * Constructor. * * @param representation * The representation to parse. */ public XstreamRepresentation(Representation representation) { super(representation.getMediaType()); this.object = null; this.representation = representation; this.jsonDriverClass = JettisonMappedXmlDriver.class; this.xmlDriverClass = DomDriver.class; this.xstream = null; } /** * Constructor. Uses the {@link MediaType#APPLICATION_XML} media type by * default. * * @param object * The object to format. */ public XstreamRepresentation(T object) { this(MediaType.APPLICATION_XML, object); } /** * Creates an XStream object based on a media type. By default, it creates a * {@link HierarchicalStreamDriver} or a {@link DomDriver}. * * @param mediaType * The serialization media type. * @return The XStream object. */ protected XStream createXstream(MediaType mediaType) { XStream result = null; try { if (MediaType.APPLICATION_JSON.isCompatible(mediaType)) { result = new XStream(getJsonDriverClass().newInstance()); result.setMode(XStream.NO_REFERENCES); } else { result = new XStream(getXmlDriverClass().newInstance()); } result.autodetectAnnotations(true); } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to create the XStream driver.", e); } return result; } /** * Returns the XStream JSON driver class. * * @return TXStream JSON driver class. */ public Class getJsonDriverClass() { return jsonDriverClass; } @SuppressWarnings("unchecked") public T getObject() { T result = null; if (this.object != null) { result = this.object; } else if (this.representation != null) { try { result = (T) getXstream().fromXML( this.representation.getStream()); } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to parse the object with XStream.", e); } } return result; } /** * Returns the XStream XML driver class. * * @return The XStream XML driver class. */ public Class getXmlDriverClass() { return xmlDriverClass; } /** * Returns the modifiable XStream object. Useful to customize mappings. * * @return The modifiable XStream object. */ public XStream getXstream() { if (this.xstream == null) { this.xstream = createXstream(getMediaType()); } return this.xstream; } /** * Sets the XStream JSON driver class. * * @param jsonDriverClass * The XStream JSON driver class. */ public void setJsonDriverClass( Class jsonDriverClass) { this.jsonDriverClass = jsonDriverClass; } /** * Sets the XStream XML driver class. * * @param xmlDriverClass * The XStream XML driver class. */ public void setXmlDriverClass( Class xmlDriverClass) { this.xmlDriverClass = xmlDriverClass; } /** * Sets the XStream object. * * @param xstream * The XStream object. */ public void setXstream(XStream xstream) { this.xstream = xstream; } @Override public void write(Writer writer) throws IOException { if (representation != null) { representation.write(writer); } else if (object != null) { CharacterSet charSet = (getCharacterSet() == null) ? CharacterSet.ISO_8859_1 : getCharacterSet(); if (!MediaType.APPLICATION_JSON.isCompatible(getMediaType())) { writer.append("\n"); } getXstream().toXML(object, writer); } } } restlet-2.0.14/org.restlet.example/0000775000175000017500000000000012001473173017634 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/pom.xml0000600000175000017500000001105712001473173021143 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.example Restlet examples Various examples including those from the tutorial org.restlet.jse org.restlet.lib.com.db4o ${lib-db4o-version} org.restlet.jse org.restlet.lib.com.db4o.nativequery ${lib-db4o-version} org.restlet.jse org.restlet.lib.com.db4o.instrumentation ${lib-db4o-version} org.restlet.jse org.restlet.lib.com.db4o.optional ${lib-db4o-version} org.restlet.jse org.restlet.lib.com.db4o.ta ${lib-db4o-version} org.restlet.jse org.restlet.lib.com.db4o.tools ${lib-db4o-version} junit junit 4.8.1 rome rome 1.0 org.restlet.jse org.restlet 2.0.14 org.restlet.jse org.restlet.ext.atom 2.0.14 org.restlet.jse org.restlet.ext.fileupload 2.0.14 org.restlet.jse org.restlet.ext.freemarker 2.0.14 org.restlet.jse org.restlet.ext.jackson 2.0.14 org.restlet.jse org.restlet.ext.jaxb 2.0.14 org.restlet.jse org.restlet.ext.jaxrs 2.0.14 org.restlet.jse org.restlet.ext.jetty 2.0.14 org.restlet.jse org.restlet.ext.jibx 2.0.14 org.restlet.jse org.restlet.ext.json 2.0.14 org.restlet.jse org.restlet.ext.rdf 2.0.14 org.restlet.jse org.restlet.ext.spring 2.0.14 org.restlet.jse org.restlet.ext.velocity 2.0.14 org.restlet.jse org.restlet.ext.xml 2.0.14 org.restlet.jse org.restlet.ext.xstream 2.0.14 org.restlet.jse org.restlet.ext.wadl 2.0.14 org.restlet.jse org.restlet.ext.crypto 2.0.14 org.restlet.jse org.restlet.ext.jaas 2.0.14 restlet-2.0.14/org.restlet.example/src/0000775000175000017500000000000012001473173020423 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/META-INF/0000775000175000017500000000000011757206450021574 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446023234 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.example/src/org/0000775000175000017500000000000011757206350021222 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/0000775000175000017500000000000011757206350022704 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/0000775000175000017500000000000011757206352024341 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/readme.txt0000664000175000017500000000165611757206352026347 0ustar jamespagejamespage List of examples: ----------------- Book package: - rest : Examples from the "RESTful Web Services" book from O'Reilly. Misc package: - AwsTest : Illustrates authentication to Amazon Web Services - HeadersTest : Simple Restlet displaying the raw HTTP "Accept" header - SimpleClient : Simple HTTP client calling the simple server - SimpleServer : Simple HTTP server invoked by the simple client Tutorial package: - Part02a : Retrieving the content of a Web page - Part02b : Retrieving the content of a Web page (detailled) - Part03 : Listening to Web browsers - Part05 : Components and Virtual Hosts - Part06 : Serving static files - Part09a : Guarding access to sensitive resources - Part09b : Authenticating to an HTTP server - Part10 : URI rewriting and redirection - Part11 : Routers and hierarchical URIs Spring package: - Book : Spring version of Bookmarks example from Book package restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/0000775000175000017500000000000011757206350025271 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/0000775000175000017500000000000011757206350026246 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch2/0000775000175000017500000000000011757206352026724 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch2/Example2_1a.java0000664000175000017500000000470111757206350031625 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch2; import org.restlet.data.Reference; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.w3c.dom.Node; /** * Searching the web with Yahoo!'s web service using XML. * * @author Jerome Louvel */ public class Example2_1a { static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch"; public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("You need to pass a term to search"); } else { // Fetch a resource: an XML document full of search results String term = Reference.encode(args[0]); String uri = BASE_URI + "?appid=restbook&query=" + term; Representation entity = new ClientResource(uri).get(); DomRepresentation document = new DomRepresentation(entity); // Use XPath to find the interesting parts of the data structure String expr = "/ResultSet/Result/Title"; for (Node node : document.getNodes(expr)) { System.out.println(node.getTextContent()); } } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch2/Example2_9.java0000664000175000017500000000512511757206352031477 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch2; import org.json.JSONArray; import org.json.JSONObject; import org.restlet.data.Reference; import org.restlet.ext.json.JsonRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Searching the web with Yahoo!'s web service using JSON. * * @author Jerome Louvel */ public class Example2_9 { static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch"; public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("You need to pass a term to search"); } else { // Fetch a resource: a JSON document full of search results String term = Reference.encode(args[0]); String uri = BASE_URI + "?appid=restbook&output=json&query=" + term; Representation entity = new ClientResource(uri).get(); JSONObject json = new JsonRepresentation(entity).getJsonObject(); // Navigate within the JSON document to display the titles JSONObject resultSet = json.getJSONObject("ResultSet"); JSONArray results = resultSet.getJSONArray("Result"); for (int i = 0; i < results.length(); i++) { System.out.println(results.getJSONObject(i).getString("Title")); } } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch2/Example2_5.java0000664000175000017500000000544611757206352031501 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch2; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * Getting your list of recent bookmarks on del.icio.us. * * @author Jerome Louvel */ public class Example2_5 { public static void main(String[] args) throws Exception { if (args.length != 2) { System.err .println("You need to pass your del.icio.us user name and password"); } else { // Create a authenticated request ClientResource resource = new ClientResource( "https://api.del.icio.us/v1/posts/recent"); resource.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_BASIC, args[0], args[1])); // Fetch a resource: an XML document with your recent posts Representation entity = resource.get(); DomRepresentation document = new DomRepresentation(entity); // Use XPath to find the interesting parts of the data structure for (Node node : document.getNodes("/posts/post")) { NamedNodeMap attrs = node.getAttributes(); String desc = attrs.getNamedItem("description").getNodeValue(); String href = attrs.getNamedItem("href").getNodeValue(); System.out.println(desc + ": " + href); } } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch2/Example2_1b.java0000664000175000017500000000523311757206352031631 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch2; import org.restlet.data.Reference; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.w3c.dom.Node; /** * Searching the web with Yahoo!'s web service using XML. This version is * namespace aware. * * @author Jerome Louvel */ public class Example2_1b { static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch"; public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("You need to pass a term to search"); } else { // Fetch a resource: an XML document full of search results String term = Reference.encode(args[0]); String uri = BASE_URI + "?appid=restbook&query=" + term; Representation entity = new ClientResource(uri).get(); DomRepresentation document = new DomRepresentation(entity); // Associate the namespace with the prefix y document.setNamespaceAware(true); document.getNamespaces().put("y", "urn:yahoo:srch"); // Use XPath to find the interesting parts of the data structure String expr = "/y:ResultSet/y:Result/y:Title/text()"; for (Node node : document.getNodes(expr)) { System.out.println(node.getTextContent()); } } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch3/0000775000175000017500000000000011757206352026725 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch3/S3Bucket.java0000664000175000017500000001031411757206352031212 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch3; import java.util.ArrayList; import java.util.List; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.ext.xml.DomRepresentation; import org.w3c.dom.Node; /** * Amazon S3 bucket. * * @author Jerome Louvel */ public class S3Bucket extends S3Authorized { private String name; private boolean truncated; public S3Bucket(String name) { this.name = name; } /** * Deletes this bucket. */ public Status delete() { return authorizedDelete(getUri()).getStatus(); } public String getName() { return this.name; } /** * Get the objects in this bucket: all of them, or some subset. * * If S3 decides not to return the whole bucket/subset, the second return * value will be set to true. To get the rest of the objects, you'll need to * manipulate the subset options. * * Subset options are :Prefix, :Marker, :Delimiter, :MaxKeys. For details, * see the S3 docs on "Listing Keys". * * @return The objects in this nucket. */ public List getObjects(String prefix, String marker, String delimiter, Integer maxKeys) { final List result = new ArrayList(); // Construct the request URI by appending optional listing keys final StringBuilder uri = new StringBuilder().append(getUri()); String suffix = "?"; if (prefix != null) { uri.append(suffix).append("prefix=").append(prefix); suffix = "&"; } if (marker != null) { uri.append(suffix).append("marker=").append(marker); suffix = "&"; } if (delimiter != null) { uri.append(suffix).append("delimiter=").append(delimiter); suffix = "&"; } if (maxKeys != null) { uri.append(suffix).append("maxKeys=").append(maxKeys); suffix = "&"; } // Make the request and parse the document. final Response response = authorizedGet(uri.toString()); final DomRepresentation document = new DomRepresentation(response .getEntity()); // Update the truncated flag this.truncated = document.getNodes("//IsTruncated").get(0) .getTextContent().equals("true"); // Browse the list of object keys for (final Node node : document.getNodes("//Contents/Key")) { result.add(new S3Object(this, node.getTextContent())); } return result; } public String getUri() { return HOST + getName(); } public boolean isTruncated() { return this.truncated; } /** * Stores this bucket on S3. Analagous to ActiveRecord::Base#save, which * stores an object in the database. */ public Status save() { return authorizedPut(getUri(), null).getStatus(); } public void setName(String name) { this.name = name; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch3/S3Authorized.java0000664000175000017500000000571711757206350032124 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch3; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.representation.Representation; /** * Amazon S3 client. Support class handling authorized requests. Remember to * replace the access key id and secret below with your own values. For this you * need to sign-up with Amazon Web Services *and* with the S3 service. * * @author Jerome Louvel */ public class S3Authorized { public final static String ACCESS_KEY_ID = ""; public final static String SECRET_ACCESS_KEY = ""; public final static String HOST = "https://s3.amazonaws.com/"; public static Response authorizedDelete(String uri) { return handleAuthorized(Method.DELETE, uri, null); } public static Response authorizedGet(String uri) { return handleAuthorized(Method.GET, uri, null); } public static Response authorizedHead(String uri) { return handleAuthorized(Method.HEAD, uri, null); } public static Response authorizedPut(String uri, Representation entity) { return handleAuthorized(Method.PUT, uri, entity); } private static Response handleAuthorized(Method method, String uri, Representation entity) { // Send an authenticated request final Request request = new Request(method, uri, entity); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_AWS_S3, ACCESS_KEY_ID, SECRET_ACCESS_KEY)); return new Client(Protocol.HTTPS).handle(request); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch3/S3App.java0000664000175000017500000000470411757206352030523 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch3; import java.util.ArrayList; import java.util.List; import org.restlet.Response; import org.restlet.ext.xml.DomRepresentation; import org.w3c.dom.Node; /** * Amazon S3 client application. Returns a list of buckets. * * @author Jerome Louvel */ public class S3App extends S3Authorized { public static void main(String... args) { for (S3Bucket bucket : new S3App().getBuckets()) { System.out.println(bucket.getName() + " : " + bucket.getUri()); } } public List getBuckets() { List result = new ArrayList(); // Fetch a resource: an XML document with our list of buckets Response response = authorizedGet(HOST); DomRepresentation document = new DomRepresentation(response.getEntity()); if (response.getStatus().isSuccess()) { // Use XPath to find the bucket names for (Node node : document.getNodes("//Bucket/Name")) { result.add(new S3Bucket(node.getTextContent())); } } else { System.out.println("Unable to access to your S3 buckets : " + response.getStatus()); } return result; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch3/S3Object.java0000664000175000017500000000610011757206350031177 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch3; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.Variant; /** * Amazon S3 object. * * @author Jerome Louvel */ public class S3Object extends S3Authorized { private final S3Bucket bucket; private Variant metadata; private String name; public S3Object(S3Bucket bucket, String name) { this.bucket = bucket; this.name = name; } /** * Deletes this bucket. */ public Status delete() { return authorizedDelete(getUri()).getStatus(); } public S3Bucket getBucket() { return this.bucket; } /** * Retrieves the metadata hash for this object, possibly fetchingit from S3. * * @return The metadata hash for this object, possibly fetchingit from S3. */ public Variant getMetadata() { if (this.metadata == null) { this.metadata = authorizedHead(getUri()).getEntity(); } return this.metadata; } public String getName() { return this.name; } public String getUri() { return getBucket().getUri() + "/" + Reference.encode(getName()); } /** * Retrieves the value of this object, always fetching it (along with the * metadata) from S3. * * @return The value of this object. */ public Representation getValue() { return authorizedGet(getUri()).getEntity(); } /** * Store this object on S3 with a given value. * * @param value * The value of the object to store. */ public Status save(Representation value) { this.metadata = value; return authorizedPut(getUri(), value).getStatus(); } public void setName(String name) { this.name = name; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/0000775000175000017500000000000011757206352026731 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/Bookmark.java0000664000175000017500000000701011757206352031337 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch7; import java.util.Date; /** * URI saved and annotated by a user. * * @author Jerome Louvel */ public class Bookmark { private User user; private String uri; private String shortDescription; private String longDescription; private Date dateTime; private boolean restricting; public Bookmark(User user, String uri) { this.user = user; this.uri = uri; this.restricting = true; this.dateTime = null; this.shortDescription = null; this.longDescription = null; } /** * @return the dateTime */ public Date getDateTime() { return this.dateTime; } /** * @return the longDescription */ public String getLongDescription() { return this.longDescription; } /** * @return the shortDescription */ public String getShortDescription() { return this.shortDescription; } /** * @return the uri */ public String getUri() { return this.uri; } /** * @return the user */ public User getUser() { return this.user; } /** * @return the restricting */ public boolean isRestricting() { return this.restricting; } /** * @param dateTime * the dateTime to set */ public void setDateTime(Date dateTime) { this.dateTime = dateTime; } /** * @param longDescription * the longDescription to set */ public void setLongDescription(String longDescription) { this.longDescription = longDescription; } /** * @param restricting * the restricting to set */ public void setRestricting(boolean restricting) { this.restricting = restricting; } /** * @param shortDescription * the shortDescription to set */ public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } /** * @param uri * the uri to set */ public void setUri(String uri) { this.uri = uri; } /** * @param user * the user to set */ public void setUser(User user) { this.user = user; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/ApplicationTest.java0000664000175000017500000001317011757206350032677 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch7; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Form; import org.restlet.resource.ClientResource; /** * Client code that can be used to test the application developed in the chapter * 7 of the book and converted to Restlets in the chapter 13. * * @author Jerome Louvel */ public class ApplicationTest { /** Base application URI. */ public static final String APPLICATION_URI = "http://localhost:3000/v1"; public static void deleteBookmark(String userName, String password, String uri) { ClientResource resource = getAuthenticatedResource(getBookmarkUri( userName, uri), userName, password); resource.delete(); System.out.println(resource.getStatus() + " : " + resource.getLocationRef()); } public static void deleteUser(String userName, String password) { ClientResource resource = getAuthenticatedResource( getUserUri(userName), userName, password); resource.delete(); System.out.println(resource.getStatus() + " : " + resource.getLocationRef()); } /** * Creates an authenticated resour ce. * * @param uri * The target resource URI. * @param login * The login name. * @param password * The password. * @return The authenticated resource to use. */ public static ClientResource getAuthenticatedResource(String uri, String login, String password) { ClientResource result = new ClientResource(uri); result.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_BASIC, login, password)); return result; } public static String getBookmarkUri(String userName, String uri) { return APPLICATION_URI + "/users/" + userName + "/bookmarks/" + uri; } public static String getUserUri(String name) { return APPLICATION_URI + "/users/" + name; } /** * Main method to use for testing. * * @param args * The arguments or nothing for a usage description. */ public static void main(String... args) throws Exception { if (args.length == 0) { System.out.println("Usage depends on the number of arguments:"); System.out.println(" - Deletes a user : userName, password"); System.out .println(" - Deletes a bookmark : userName, password, URI"); System.out .println(" - Adds a new user : userName, password, \"full name\", email"); System.out .println(" - Adds a new bookmark: userName, password, URI, shortDescription, longDescription, restrict"); } else if (args.length == 2) { deleteUser(args[0], args[1]); } else if (args.length == 3) { deleteBookmark(args[0], args[1], args[2]); } else if (args.length == 4) { putUser(args[0], args[1], args[2], args[3]); } else if (args.length == 6) { putBookmark(args[0], args[1], args[2], args[3], args[4], Boolean .valueOf(args[5])); } } public static void putBookmark(String userName, String password, String uri, String shortDescription, String longDescription, boolean restrict) { Form form = new Form(); form.add("bookmark[short_description]", shortDescription); form.add("bookmark[long_description]", longDescription); form.add("bookmark[restrict]", Boolean.toString(restrict)); // Create an authenticated resource as a bookmark is in // the user's private area ClientResource resource = getAuthenticatedResource(getBookmarkUri( userName, uri), userName, password); resource.put(form.getWebRepresentation()); System.out.println(resource.getStatus()); } public static void putUser(String userName, String password, String fullName, String email) { Form form = new Form(); form.add("user[password]", password); form.add("user[full_name]", fullName); form.add("user[email]", email); ClientResource resource = new ClientResource(getUserUri(userName)); resource.put(form.getWebRepresentation()); System.out.println(resource.getStatus()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/BookmarksResource.java0000664000175000017500000000614611757206350033241 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch7; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.ReferenceList; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Resource for a user's list of bookmarks. * * @author Jerome Louvel */ public class BookmarksResource extends UserResource { @Override public void doInit() { super.doInit(); getVariants().clear(); if (getUser() != null) { getVariants().add(new Variant(MediaType.TEXT_HTML)); } } @Override public Representation get(Variant variant) throws ResourceException { Representation result = null; if (variant.getMediaType().equals(MediaType.TEXT_HTML)) { int code = checkAuthorization(); ReferenceList rl = new ReferenceList(); // Copy the bookmark URIs into a reference list. Make sure that we // only expose public bookmarks if the client isn't the owner. for (Bookmark bookmark : getUser().getBookmarks()) { if (!bookmark.isRestricting() || (code == 1)) { rl.add(bookmark.getUri()); } } result = rl.getWebRepresentation(); } return result; } @Override public Representation handle() { Representation result = null; // Make sure that the URI ends with a "/" without changing the query. // This is helpful when exposing the list of relative references of the // bookmarks. Reference ref = getRequest().getResourceRef(); if (!ref.getPath().endsWith("/")) { ref.setPath(ref.getPath() + "/"); redirectPermanent(ref); } else { result = super.handle(); } return result; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/UserResource.java0000664000175000017500000002172411757206350032226 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch7; import java.util.ArrayList; import java.util.List; import org.restlet.data.ChallengeRequest; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import com.db4o.ObjectContainer; import com.db4o.query.Predicate; /** * Resource for a persistent user. * * @author Jerome Louvel */ public class UserResource extends ServerResource { private String login; private boolean modifiable; private String password; private User user; private String userName; private List variants; /** * Updates the response to challenge the client for credentials. */ public void challenge() { getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT); getResponse().getChallengeRequests().add( new ChallengeRequest(ChallengeScheme.HTTP_BASIC, "Restlet")); } /** * Check the authorization credentials. * * @return 1 if authentication OK, 0 if it is missing, -1 if it is wrong */ public int checkAuthorization() { int result = 0; if (this.user != null) { if ((this.login != null) && (this.password != null)) { // Credentials provided if (this.userName.equals(this.login) && this.password.equals(this.user.getPassword())) { result = 1; } else { result = -1; } } } return result; } @Override public Representation delete() throws ResourceException { if (isModifiable()) { switch (checkAuthorization()) { case 1: // Delete all associated bookmarks for (final Bookmark bookmark : this.user.getBookmarks()) { getContainer().delete(bookmark); } // Delete the parent user getContainer().delete(this.user); // Commit the changes getContainer().commit(); setStatus(Status.SUCCESS_OK); break; case 0: // No authentication provided challenge(); break; case -1: // Wrong authentication provided setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); break; } } else { return super.delete(); } return null; } @Override public void doInit() { this.userName = (String) getRequestAttributes().get("username"); final ChallengeResponse cr = getChallengeResponse(); this.login = (cr != null) ? cr.getIdentifier() : null; this.password = (cr != null) ? new String(cr.getSecret()) : null; this.user = findUser(); if (this.user != null) { this.variants = new ArrayList(); this.variants.add(new Variant(MediaType.TEXT_PLAIN)); } modifiable = true; } /** * Finds the associated user. * * @return The user found or null. */ public User findUser() { User result = null; if (this.userName != null) { // Create the query predicate final Predicate predicate = new Predicate() { private static final long serialVersionUID = 1L; @Override public boolean match(User candidate) { return UserResource.this.userName.equals(candidate .getName()); } }; // Query the database and get the first result final List users = getContainer().query(predicate); if ((users != null) && (users.size() > 0)) { result = users.get(0); } } return result; } @Override public Representation get(Variant variant) throws ResourceException { Representation result = null; if ((variant != null) && variant.getMediaType().equals(MediaType.TEXT_PLAIN)) { // Creates a text representation final StringBuilder sb = new StringBuilder(); sb.append("------------\n"); sb.append("User details\n"); sb.append("------------\n\n"); sb.append("Name: ").append(this.user.getFullName()).append('\n'); sb.append("Email: ").append(this.user.getEmail()).append('\n'); result = new StringRepresentation(sb); } return result; } /** * Returns the parent application. * * @return the parent application. */ @Override public Application getApplication() { return (Application) super.getApplication(); } /** * Returns the database container. * * @return the database container. */ public ObjectContainer getContainer() { return getApplication().getContainer(); } /** * Returns the associated user. * * @return The associated user. */ public User getUser() { return this.user; } @Override public List getVariants() { return variants; } public boolean isModifiable() { return modifiable; } @Override public Representation put(Representation entity) throws ResourceException { if (isModifiable()) { if (entity.getMediaType().equals(MediaType.APPLICATION_WWW_FORM, true)) { boolean canSet = true; if (getUser() == null) { // The user doesn't exist, create it setUser(new User()); getUser().setName(this.userName); setStatus(Status.SUCCESS_CREATED); } else { // The user already exists, check the authentication switch (checkAuthorization()) { case 1: setStatus(Status.SUCCESS_NO_CONTENT); break; case 0: // No authentication provided challenge(); canSet = false; break; case -1: // Wrong authentication provided setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); canSet = false; break; } } if (canSet) { // Parse the entity as a web form final Form form = new Form(entity); getUser().setEmail(form.getFirstValue("user[email]")); getUser() .setFullName(form.getFirstValue("user[full_name]")); getUser().setPassword(form.getFirstValue("user[password]")); // Commit the changes getContainer().store(getUser()); getContainer().commit(); } } } else { return super.put(entity); } return null; } public void setModifiable(boolean modifiable) { this.modifiable = modifiable; } /** * Sets the associated user. * * @param user * The user to set. */ public void setUser(User user) { this.user = user; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/Application.java0000664000175000017500000000655211757206350032045 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch7; import java.io.File; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; import org.restlet.routing.TemplateRoute; import org.restlet.routing.Variable; import com.db4o.Db4oEmbedded; import com.db4o.ObjectContainer; import com.db4o.config.EmbeddedConfiguration; /** * The main Web application. * * @author Jerome Louvel */ public class Application extends org.restlet.Application { public static void main(String... args) throws Exception { // Create a component with an HTTP server connector final Component comp = new Component(); comp.getServers().add(Protocol.HTTP, 3000); // Attach the application to the default host and start it comp.getDefaultHost().attach("/v1", new Application()); comp.start(); } private final ObjectContainer container; /** * Constructor. */ public Application() { /** Open and keep the db4o object container. */ EmbeddedConfiguration config = Db4oEmbedded.newConfiguration(); config.common().updateDepth(2); this.container = Db4oEmbedded.openFile(config, System .getProperty("user.home") + File.separator + "restbook.dbo"); } @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); // Add a route for user resources router.attach("/users/{username}", UserResource.class); // Add a route for user's bookmarks resources router.attach("/users/{username}/bookmarks", BookmarksResource.class); // Add a route for bookmark resources final TemplateRoute uriRoute = router.attach( "/users/{username}/bookmarks/{URI}", BookmarkResource.class); uriRoute.getTemplate().getVariables().put("URI", new Variable(Variable.TYPE_URI_ALL)); return router; } /** * Returns the database container. * * @return the database container. */ public ObjectContainer getContainer() { return this.container; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/BookmarkResource.java0000664000175000017500000001367311757206350033061 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch7; import java.util.Date; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Resource for a user's bookmark. * * @author Jerome Louvel */ public class BookmarkResource extends UserResource { private Bookmark bookmark; private String uri; @Override public Representation delete() throws ResourceException { if (isModifiable()) { if ((this.bookmark != null) && (checkAuthorization() == 1)) { // Delete the bookmark getUser().getBookmarks().remove(this.bookmark); getContainer().delete(this.bookmark); getContainer().store(getUser()); getContainer().commit(); setStatus(Status.SUCCESS_OK); } else { // Intentionally hide the bookmark existence setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } else { return super.delete(); } return null; } @Override public void doInit() { super.doInit(); if (getUser() != null) { this.uri = (String) getRequestAttributes().get("URI"); this.bookmark = getUser().getBookmark(this.uri); if (this.bookmark != null) { if ((checkAuthorization() != 1) && this.bookmark.isRestricting()) { // Intentionally hide the bookmark existence setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } else { // Bookmark not found, remove the variant added by the super // class (UserResource). getVariants().clear(); } } else { // User not found setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } @Override public Representation get(Variant variant) throws ResourceException { Representation result = null; if (variant.getMediaType().equals(MediaType.TEXT_PLAIN)) { // Creates a text representation final StringBuilder sb = new StringBuilder(); sb.append("----------------\n"); sb.append("Bookmark details\n"); sb.append("----------------\n\n"); sb.append("User: ").append(this.bookmark.getUser().getName()) .append('\n'); sb.append("URI: ").append(this.bookmark.getUri()).append('\n'); sb.append("Short: ").append(this.bookmark.getShortDescription()) .append('\n'); sb.append("Long: ").append(this.bookmark.getLongDescription()) .append('\n'); sb.append("Date: ").append(this.bookmark.getDateTime()).append( '\n'); sb.append("Restrict: ").append( Boolean.toString(this.bookmark.isRestricting())).append('\n'); result = new StringRepresentation(sb); } return result; } @Override public Representation put(Representation entity) throws ResourceException { if (checkAuthorization() == 1) { if (entity.getMediaType().equals(MediaType.APPLICATION_WWW_FORM, true)) { // Parse the entity as a web form final Form form = new Form(entity); // If the bookmark doesn't exist, create it if (this.bookmark == null) { this.bookmark = new Bookmark(getUser(), this.uri); getUser().getBookmarks().add(this.bookmark); setStatus(Status.SUCCESS_CREATED); } else { setStatus(Status.SUCCESS_NO_CONTENT); } // Update the bookmark this.bookmark.setShortDescription(form .getFirstValue("bookmark[short_description]")); this.bookmark.setLongDescription(form .getFirstValue("bookmark[long_description]")); this.bookmark.setDateTime(new Date()); this.bookmark.setRestricting(new Boolean(form .getFirstValue("bookmark[restrict]"))); // Commit the changes getContainer().store(this.bookmark); getContainer().store(getUser()); getContainer().commit(); } } else { // Intentionally hide the bookmark existence setStatus(Status.CLIENT_ERROR_NOT_FOUND); } return null; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch7/User.java0000664000175000017500000000604711757206350030517 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch7; import java.util.ArrayList; import java.util.List; /** * User account. * * @author Jerome Louvel */ public class User { private String name; private String fullName; private String email; private String password; private List bookmarks; public Bookmark getBookmark(String uri) { for (final Bookmark bookmark : getBookmarks()) { if (bookmark.getUri().equals(uri)) { return bookmark; } } return null; } /** * @return the modifiable list of bookmarks */ public List getBookmarks() { if (this.bookmarks == null) { this.bookmarks = new ArrayList(); } return this.bookmarks; } /** * @return the email */ public String getEmail() { return this.email; } /** * @return the fullName */ public String getFullName() { return this.fullName; } /** * @return the name */ public String getName() { return this.name; } /** * @return the password */ public String getPassword() { return this.password; } /** * @param email * the email to set */ public void setEmail(String email) { this.email = email; } /** * @param fullName * the fullName to set */ public void setFullName(String fullName) { this.fullName = fullName; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch6/0000775000175000017500000000000011757206350026726 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/rest/ch6/Example6_1.java0000664000175000017500000000357511757206350031504 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.rest.ch6; import org.restlet.data.Form; import org.restlet.data.Reference; import org.restlet.resource.ClientResource; /** * Sample map client to create a user account * * @author Jerome Louvel */ public class Example6_1 { public void makeUser(String user, String password) { // Create the input form Form input = new Form(); input.add("password", password); // Create the target URI, encoding the user name String uri = "https://maps.example.com/user/" + Reference.encode(user); // Invoke the web service new ClientResource(uri).put(input.getWebRepresentation()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/0000775000175000017500000000000011757206352026755 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch09/0000775000175000017500000000000012001473213027501 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch01/0000775000175000017500000000000011757206352027510 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch01/HelloServer.java0000664000175000017500000000326611757206352032614 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch01; import org.restlet.Server; import org.restlet.data.Protocol; /** * Creates and launches a HTTP server listening on port 8111, and transmitting * all calls to the HelloServerResource class. */ public class HelloServer { public static void main(String[] args) throws Exception { Server helloServer = new Server(Protocol.HTTP, 8111, HelloServerResource.class); helloServer.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch01/HelloClient.java0000664000175000017500000000330711757206350032556 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch01; import org.restlet.resource.ClientResource; /** * Creates and launches a HTTP client invoking the server listening on port * 8111, and writing the response entity on the console. */ public class HelloClient { public static void main(String[] args) throws Exception { ClientResource helloClientresource = new ClientResource( "http://localhost:8111/"); helloClientresource.get().write(System.out); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch01/HelloServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch01/HelloServerResource.jav0000664000175000017500000000303411757206352034154 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch01; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Simple "hello, world" server resource. */ public class HelloServerResource extends ServerResource { @Get("txt") public String represent() { return "hello, world"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/0000775000175000017500000000000011757206350027510 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/0000775000175000017500000000000011757206350030345 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/client/0000775000175000017500000000000011757206350031623 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/client/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/client/MailClient.0000664000175000017500000000730311757206350033650 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.client; import org.restlet.Client; import org.restlet.Context; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountResource; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountsResource; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.RootResource; import org.restlet.resource.ClientResource; /** * Mail client. */ public class MailClient { /** * Mail client interacting with the RESTful mail server. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { System.out.println("\n1) Set up the service client resource\n"); Client client = new Client(new Context(), Protocol.HTTP); ClientResource service = new ClientResource("http://localhost:8111"); service.setNext(client); System.out.println("\n2) Display the root resource\n"); RootResource mailRoot = service.getChild("/", RootResource.class); System.out.println(mailRoot.represent()); System.out.println("\n3) Display the initial list of accounts\n"); AccountsResource mailAccounts = service.getChild("/accounts/", AccountsResource.class); String list = mailAccounts.represent(); System.out.println(list == null ? "\n" : list); System.out.println("\n4) Adds new accounts\n"); mailAccounts.add("Tim Berners-Lee"); mailAccounts.add("Roy Fielding"); mailAccounts.add("Mark Baker"); System.out.println("Three accounts added !"); System.out.println("\n5) Display the updated list of accounts\n"); System.out.println(mailAccounts.represent()); System.out.println("\n6) Display the second account\n"); AccountResource mailAccount = service.getChild("/accounts/1", AccountResource.class); System.out.println(mailAccount.represent()); System.out .println("\n7) Update the individual account and display it again\n"); mailAccount.store("Roy T. Fielding"); System.out.println(mailAccount.represent()); System.out .println("\n8) Delete the first account and display the list again\n"); mailAccount = service.getChild("/accounts/0", AccountResource.class); mailAccount.remove(); System.out.println(mailAccounts.represent()); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/client/MailClientTestCase.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/client/MailClientT0000664000175000017500000000452211757206350033716 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.client; import junit.framework.TestCase; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.example.book.restlet.ch03.sec3.server.MailServerComponent; /** * Mail client JUnit test case. */ public class MailClientTestCase extends TestCase { /** * Unit test for virtual hosts. * * @throws Exception */ public void testVirtualHost() throws Exception { // Instantiate our Restlet component MailServerComponent component = new MailServerComponent(); // Prepare a mock HTTP call Request request = new Request(); request.setMethod(Method.GET); request.setResourceRef("http://www.rmep.org/accounts/"); request.setHostRef("http://www.rmep.org"); Response response = new Response(request); response.getServerInfo().setAddress("1.2.3.10"); response.getServerInfo().setPort(80); component.handle(request, response); // Test if response was successful assertTrue(response.getStatus().isSuccess()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/common/0000775000175000017500000000000011757206350031635 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/common/AccountResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/common/AccountReso0000664000175000017500000000367311757206350034016 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.common; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * User account resource. */ public interface AccountResource { /** * Represents the account as a simple string with the owner name for now. * * @return The account representation. */ @Get public String represent(); /** * Stores the new value for the identified account. * * @param account * The identified account. */ @Put public void store(String account); /** * Deletes the identified account by setting its value to null. */ @Delete public void remove(); } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/common/AccountsResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/common/AccountsRes0000664000175000017500000000355211757206350034016 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.common; import org.restlet.resource.Get; import org.restlet.resource.Post; /** * Collection resource containing user accounts. */ public interface AccountsResource { /** * Returns the list of accounts, each one on a separate line. * * @return The list of accounts. */ @Get public String represent(); /** * Add the given account to the list and returns its position as an * identifier. * * @param account * The account to add. * @return The account identifier. */ @Post public String add(String account); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/common/RootResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/common/RootResourc0000664000175000017500000000303511757206350034047 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.common; import org.restlet.resource.Get; /** * Root resource. */ public interface RootResource { /** * Represents the application root with a welcome message. * * @return The root representation. */ @Get public String represent(); } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/0000775000175000017500000000000011757206352031655 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/AccountServ0000664000175000017500000000452411757206350034037 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.server; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Implementation of a mail account resource. */ public class AccountServerResource extends ServerResource implements AccountResource { /** The account identifier. */ private int accountId; /** * Retrieve the account identifier based on the URI path variable * "accountId" declared in the URI template attached to the application * router. */ @Override protected void doInit() throws ResourceException { this.accountId = Integer.parseInt((String) getRequestAttributes().get( "accountId")); } public String represent() { return AccountsServerResource.getAccounts().get(this.accountId); } public void store(String account) { AccountsServerResource.getAccounts().set(this.accountId, account); } public void remove() { AccountsServerResource.getAccounts().remove(this.accountId); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/MailServerSpring.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/MailServerS0000664000175000017500000000407511757206350034000 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.server; import org.restlet.Component; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; /** * Creates a Restlet component and application based on a Spring XML * configuration and starts them. */ public class MailServerSpring { public static void main(String[] args) throws Exception { // Load the Spring container ClassPathResource resource = new ClassPathResource( "org/restlet/example/book/restlet/ch03/sec3/server/component-spring.xml"); BeanFactory factory = new XmlBeanFactory(resource); // Start the Restlet component Component component = factory.getBean("component", Component.class); component.start(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/component-spring.xmlrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/component-s0000664000175000017500000000547711757206352034057 0ustar jamespagejamespage true ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/log.propertiesrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/log.propert0000664000175000017500000001142111757206352034052 0ustar jamespagejamespage # ========================== # Restlet logging properties # ========================== # ------------------ # General properties # ------------------ # This defines a whitespace separated list of class names for handler classes to load and register as handlers on # the root Logger (the Logger named ""). Each class name must be for a Handler class which has a default constructor. # Note that these Handlers may be created lazily, when they are first used. handlers=java.util.logging.FileHandler java.util.logging.ConsoleHandler # ------------------ # Loggers properties # ------------------ .level=INFO org.mortbay.level=WARNING org.restlet.level=ALL MailServer.AccessLog.handlers=org.restlet.engine.log.AccessLogFileHandler MailServer.AccessLog.useParentHandlers=false # ------------------------- # ConsoleHandler properties # ------------------------- # Specifies the default level for the Handler (defaults to Level.INFO). # java.util.logging.ConsoleHandler.level=ALL # Specifies the name of a Filter class to use (defaults to no Filter). # java.util.logging.ConsoleHandler.filter= # Specifies the name of a Formatter class to use (defaults to java.util.logging.SimpleFormatter). # java.util.logging.ConsoleHandler.formatter= # The name of the character set encoding to use (defaults to the default platform encoding). # java.util.logging.ConsoleHandler.encoding= # ---------------------- # FileHandler properties # ---------------------- # Specifies the default level for the Handler (defaults to Level.ALL). # java.util.logging.FileHandler.level=ALL # Specifies the name of a Filter class to use (defaults to no Filter). # java.util.logging.FileHandler.filter= # Specifies the name of a Formatter class to use (defaults to java.util.logging.XMLFormatter) java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter # The name of the character set encoding to use (defaults to the default platform encoding). # java.util.logging.FileHandler.encoding= # Specifies an approximate maximum amount to write (in bytes) to any one file. # If this is zero, then there is no limit. (Defaults to no limit). # java.util.logging.FileHandler.limit=1000000 # Specifies how many output files to cycle through (defaults to 1). java.util.logging.FileHandler.count=2 # Specifies a pattern for generating the output file name. (Defaults to "%h/java%u.log"). # A pattern consists of a string that includes the following special components that will be replaced at runtime: # "/" the local pathname separator # "%t" the system temporary directory # "%h" the value of the "user.home" system property # "%g" the generation number to distinguish rotated logs # "%u" a unique number to resolve conflicts # "%%" translates to a single percent sign "%" java.util.logging.FileHandler.pattern=MailServer.DebugLog-%u-%g.log # Specifies whether the FileHandler should append onto any existing files (defaults to false). # java.util.logging.FileHandler.append= # ------------------------------- # AccessLogFileHandler properties # ------------------------------- # Specifies the default level for the Handler (defaults to Level.ALL). # org.restlet.engine.log.AccessLogFileHandler.level=ALL # Specifies the name of a Filter class to use (defaults to no Filter). # org.restlet.engine.log.AccessLogFileHandler.filter= # Specifies the name of a Formatter class to use (defaults to java.util.logging.XMLFormatter) org.restlet.engine.log.AccessLogFileHandler.formatter=org.restlet.engine.log.DefaultAccessLogFormatter # The name of the character set encoding to use (defaults to the default platform encoding). # org.restlet.engine.log.AccessLogFileHandler.encoding= # Specifies an approximate maximum amount to write (in bytes) to any one file. # If this is zero, then there is no limit. (Defaults to no limit). # org.restlet.engine.log.AccessLogFileHandler.limit=1000000 # Specifies how many output files to cycle through (defaults to 1). org.restlet.engine.log.AccessLogFileHandler.count=2 # Specifies a pattern for generating the output file name. (Defaults to "%h/java%u.log"). # A pattern consists of a string that includes the following special components that will be replaced at runtime: # "/" the local pathname separator # "%t" the system temporary directory # "%h" the value of the "user.home" system property # "%g" the generation number to distinguish rotated logs # "%u" a unique number to resolve conflicts # "%%" translates to a single percent sign "%" org.restlet.engine.log.AccessLogFileHandler.pattern=MailServer.AccessLog-%u-%g.log # Specifies whether the AccessLogFileHandler should append onto any existing files (defaults to false). # org.restlet.engine.log.AccessLogFileHandler.append= restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/web.xml0000664000175000017500000000170311757206352033155 0ustar jamespagejamespage Servlet engine as a connector for a Restlet component MailServerComponent org.restlet.ext.servlet.ServerServlet org.restlet.component org.restlet.example.book.restlet.ch03.sec3.server.MailServerComponent MailServerComponent /* ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/MailServerA0000664000175000017500000000423611757206350033755 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.server; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; /** * The reusable mail server application. */ public class MailServerApplication extends Application { /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server application"); setDescription("Example application for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/", RootServerResource.class); router.attach("/accounts/", AccountsServerResource.class); router.attach("/accounts/{accountId}", AccountServerResource.class); return router; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/component-simple.xmlrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/component-s0000664000175000017500000000167111757206352034047 0ustar jamespagejamespage ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/MailServerComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/MailServerC0000664000175000017500000000610711757206352033760 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.server; import org.restlet.Client; import org.restlet.Component; import org.restlet.Context; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.VirtualHost; /** * RESTful component containing the mail server application. */ public class MailServerComponent extends Component { /** * Launches the mail server component. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { new MailServerComponent().start(); } /** * Constructor. * * @throws Exception */ public MailServerComponent() throws Exception { // Set basic properties setName("RESTful Mail Server component"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Add connectors getClients().add(new Client(Protocol.CLAP)); Server server = new Server(new Context(), Protocol.HTTP, 8111); server.getContext().getParameters().set("tracing", "true"); getServers().add(server); // Configure the default virtual host VirtualHost host = getDefaultHost(); // host.setHostDomain("www\\.rmep\\.com|www\\.rmep\\.net|www\\.rmep\\.org"); // host.setServerAddress("1\\.2\\.3\\.10|1\\.2\\.3\\.20"); // host.setServerPort("80"); // Attach the application to the default virtual host host.attachDefault(new MailServerApplication()); // Configure the log service getLogService().setLoggerName("MailServer.AccessLog"); getLogService() .setLogPropertiesRef( "clap://system/org/restlet/example/book/restlet/ch03/sec3/server/log.properties"); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/AccountsSer0000664000175000017500000000460211757206350034031 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.server; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountsResource; import org.restlet.resource.ServerResource; /** * Implementation of the resource containing the list of mail accounts. */ public class AccountsServerResource extends ServerResource implements AccountsResource { /** Static list of accounts stored in memory. */ private static final List accounts = new CopyOnWriteArrayList(); /** * Returns the static list of accounts stored in memory. * * @return The static list of accounts. */ public static List getAccounts() { return accounts; } public String represent() { StringBuilder result = new StringBuilder(); for (String account : getAccounts()) { result.append((account == null) ? "" : account).append('\n'); } return result.toString(); } public String add(String account) { getAccounts().add(account); return Integer.toString(getAccounts().indexOf(account)); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch03/sec3/server/RootServerR0000664000175000017500000000317211757206352034037 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch03.sec3.server; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.RootResource; import org.restlet.resource.ServerResource; /** * Root resource implementation. */ public class RootServerResource extends ServerResource implements RootResource { public String represent() { return "Welcome to the " + getApplication().getName() + " !"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/0000775000175000017500000000000011757206352027510 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec2/0000775000175000017500000000000011757206352030344 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec2/FoafExample.java0000664000175000017500000000630511757206352033402 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec2; import java.io.IOException; import org.restlet.data.Reference; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.Literal; public class FoafExample { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // FOAF ontology String FOAF_BASE = "http://xmlns.com/foaf/0.1/"; Reference firstName = new Reference(FOAF_BASE + "firstName"); Reference lastName = new Reference(FOAF_BASE + "lastName"); Reference mbox = new Reference(FOAF_BASE + "mbox"); Reference knows = new Reference(FOAF_BASE + "knows"); // Linked Simpson resources Reference homerRef = new Reference( "http://www.rmep.org/accounts/chunkylover53/"); Reference margeRef = new Reference( "http://www.rmep.org/accounts/bretzels34/"); Reference bartRef = new Reference( "http://www.rmep.org/accounts/jojo10/"); Reference lisaRef = new Reference( "http://www.rmep.org/accounts/lisa1984/"); // Example RDF graph Graph example = new Graph(); example.add(homerRef, firstName, new Literal("Homer")); example.add(homerRef, lastName, new Literal("Simpson")); example.add(homerRef, mbox, new Literal("mailto:homer@simpson.org")); example.add(homerRef, knows, margeRef); example.add(homerRef, knows, bartRef); example.add(homerRef, knows, lisaRef); // Serialization System.out.println("\nRDF/XML format:\n"); example.getRdfXmlRepresentation().write(System.out); System.out.println("\nRDF/n3 format:\n"); example.getRdfN3Representation().write(System.out); System.out.println("\nRDF/Turtle format:\n"); example.getRdfTurtleRepresentation().write(System.out); System.out.println("\nRDF/NTriples format:\n"); example.getRdfNTriplesRepresentation().write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/0000775000175000017500000000000011757206352030345 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/FoafConstants.java0000664000175000017500000000353611757206350033765 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3; import org.restlet.data.Reference; public class FoafConstants { public static final String BASE = "http://xmlns.com/foaf/0.1/"; public static final Reference KNOWS = new Reference(BASE + "knows"); public static final Reference NAME = new Reference(BASE + "name"); public static final Reference FIRST_NAME = new Reference(BASE + "firstName"); public static final Reference LAST_NAME = new Reference(BASE + "lastName"); public static final Reference MBOX = new Reference(BASE + "mbox"); public static final Reference NICK = new Reference(BASE + "nick"); } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/client/0000775000175000017500000000000011757206352031623 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/client/FoafBrowser.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/client/FoafBrowser0000664000175000017500000000514411757206352033771 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.client; import java.util.Set; import org.restlet.data.Reference; import org.restlet.example.book.restlet.ch10.sec3.FoafConstants; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.RdfClientResource; import org.restlet.util.Couple; public class FoafBrowser { public static void main(String[] args) { displayFoafProfile("http://localhost:8111/accounts/chunkylover53/"); } public static void displayFoafProfile(String uri) { displayFoafProfile(new RdfClientResource(uri), 1); } public static void displayFoafProfile(RdfClientResource foafProfile, int maxDepth) { Set> literals = foafProfile.getLiterals(); if (literals != null) { for (Couple literal : literals) { System.out.println(literal.getFirst().getLastSegment() + ": " + literal.getSecond()); } } System.out.println("--------------------------------------------"); if (maxDepth > 0) { Set knows = foafProfile .getLinked(FoafConstants.KNOWS); if (knows != null) { for (RdfClientResource know : knows) { displayFoafProfile(know, maxDepth - 1); } } } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/model/0000775000175000017500000000000011757206352031445 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/model/Contact.java0000664000175000017500000000315711757206350033707 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.model; public class Contact { private String profileRef; public Contact() { } public Contact(String profileRef) { super(); this.profileRef = profileRef; } public String getProfileRef() { return profileRef; } public void setProfileRef(String login) { this.profileRef = login; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/model/Account.java0000664000175000017500000000541311757206352033707 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.model; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Account { private String login; private String firstName; private String lastName; private String nickName; private String senderName; private String emailAddress; private List contacts; public Account() { this.contacts = new CopyOnWriteArrayList(); } public List getContacts() { return contacts; } public String getEmailAddress() { return emailAddress; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getLogin() { return login; } public String getNickName() { return nickName; } public String getSenderName() { return senderName; } public void setContacts(List contact) { this.contacts = contact; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setLogin(String login) { this.login = login; } public void setNickName(String nickName) { this.nickName = nickName; } public void setSenderName(String senderName) { this.senderName = senderName; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/server/0000775000175000017500000000000011757206350031651 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/server/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/server/AccountServ0000664000175000017500000001061211757206350034030 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.server; import java.util.Map; import org.restlet.data.Reference; import org.restlet.example.book.restlet.ch10.sec3.FoafConstants; import org.restlet.example.book.restlet.ch10.sec3.api.AccountRepresentation; import org.restlet.example.book.restlet.ch10.sec3.api.AccountResource; import org.restlet.example.book.restlet.ch10.sec3.model.Account; import org.restlet.example.book.restlet.ch10.sec3.model.Contact; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.Literal; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Implementation of a mail account resource. */ public class AccountServerResource extends ServerResource implements AccountResource { /** The account identifier. */ private Account account; public Map getAccounts() { return ((MailServerApplication) getApplication()).getAccounts(); } /** * Retrieve the account identifier based on the URI path variable * "accountId" declared in the URI template attached to the application * router. */ @Override protected void doInit() throws ResourceException { String accountId = (String) getRequestAttributes().get("accountId"); this.account = getAccounts().get(accountId); } public void remove() { getAccounts().remove(this.account); } /** * Builds the RDF graph. */ public Graph getFoafProfile() { Graph result = null; if (account != null) { result = new Graph(); result.add(getReference(), FoafConstants.MBOX, new Literal( "mailto:" + account.getEmailAddress())); result.add(getReference(), FoafConstants.FIRST_NAME, new Literal( account.getFirstName())); result.add(getReference(), FoafConstants.LAST_NAME, new Literal( account.getLastName())); result.add(getReference(), FoafConstants.NICK, new Literal(account.getNickName())); result.add(getReference(), FoafConstants.NAME, new Literal(account.getSenderName())); for (Contact contact : account.getContacts()) { result.add(getReference(), FoafConstants.KNOWS, new Reference( getReference(), contact.getProfileRef()).getTargetRef()); } } return result; } /** * Builds the representation bean. */ public AccountRepresentation represent() { AccountRepresentation result = null; if (account != null) { result = new AccountRepresentation(); result.setEmailAddress(account.getEmailAddress()); result.setFirstName(account.getFirstName()); result.setLastName(account.getLastName()); result.setLogin(account.getLogin()); result.setNickName(account.getNickName()); result.setSenderName(account.getSenderName()); for (Contact contact : account.getContacts()) { result.getContactRefs().add(contact.getProfileRef()); } } return result; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/server/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/server/MailServerA0000664000175000017500000001130711757206350033750 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.server; import java.util.HashMap; import java.util.Map; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.example.book.restlet.ch10.sec3.model.Account; import org.restlet.example.book.restlet.ch10.sec3.model.Contact; import org.restlet.routing.Router; /** * The reusable mail server application. */ public class MailServerApplication extends Application { /** Static list of accounts stored in memory. */ private final Map accounts = new HashMap(); /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail API application"); setDescription("Example API for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); Account homer = new Account(); homer.setFirstName("Homer"); homer.setLastName("Simpson"); homer.setLogin("chunkylover53"); homer.setNickName("Personal mailbox of Homer"); homer.setSenderName("Homer"); homer.setEmailAddress("homer@simpson.org"); homer.getContacts().add(new Contact("/accounts/bretzels34/")); homer.getContacts().add(new Contact("/accounts/jojo10/")); homer.getContacts().add(new Contact("/accounts/lisa1984/")); getAccounts().put("chunkylover53", homer); Account marge = new Account(); marge.setFirstName("Marjorie"); marge.setLastName("Simpson"); marge.setLogin("bretzels34"); marge.setNickName("Personal mailbox of Marge"); marge.setSenderName("Marge"); marge.setEmailAddress("homer@simpson.org"); marge.getContacts().add(new Contact("/accounts/chunkylover53/")); marge.getContacts().add(new Contact("/accounts/jojo10/")); marge.getContacts().add(new Contact("/accounts/lisa1984/")); getAccounts().put("bretzels34", marge); Account bart = new Account(); bart.setFirstName("Bartholomew"); bart.setLastName("Simpson"); bart.setLogin("jojo10"); bart.setNickName("Personal mailbox of Bart"); bart.setSenderName("Bart"); bart.setEmailAddress("bart@simpson.org"); bart.getContacts().add(new Contact("/accounts/chunkylover53/")); bart.getContacts().add(new Contact("/accounts/bretzels34/")); bart.getContacts().add(new Contact("/accounts/lisa1984/")); getAccounts().put("jojo10", bart); Account lisa = new Account(); lisa.setFirstName("Lisa"); lisa.setLastName("Simpson"); lisa.setLogin("lisa1984"); lisa.setNickName("Personal mailbox of Lisa"); lisa.setSenderName("Lisa"); lisa.setEmailAddress("lisa@simpson.org"); lisa.getContacts().add(new Contact("/accounts/chunkylover53/")); lisa.getContacts().add(new Contact("/accounts/bretzels34/")); lisa.getContacts().add(new Contact("/accounts/jojo10/")); getAccounts().put("lisa1984", lisa); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/", AccountServerResource.class); return router; } /** * Returns the list of accounts stored in memory. * * @return The list of accounts stored in memory. */ public Map getAccounts() { return accounts; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/server/MailServerComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/server/MailServerC0000664000175000017500000000457411757206350033762 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.server; import org.restlet.Component; import org.restlet.Server; import org.restlet.data.Protocol; /** * RESTful component containing the mail server application. */ public class MailServerComponent extends Component { /** * Launches the mail server component. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { new MailServerComponent().start(); } /** * Constructor. * * @throws Exception */ public MailServerComponent() throws Exception { // Set basic properties setName("RESTful Mail Server component"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Adds a HTTP server connector Server server = getServers().add(Protocol.HTTP, 8111); server.getContext().getParameters().set("tracing", "false"); // Attach the application to the default virtual host getDefaultHost().attachDefault(new MailServerApplication()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/api/0000775000175000017500000000000011757206352031116 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/api/AccountResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/api/AccountResourc0000664000175000017500000000343711757206350034005 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.api; import org.restlet.ext.rdf.Graph; import org.restlet.resource.Get; /** * User account resource. */ public interface AccountResource { /** * Represents the account as a FOAF profile using RDF. * * @return The FOAF profile as a RDF graph. */ @Get("rdf") public Graph getFoafProfile(); /** * Represents the account as a simple string with the owner name for now. * * @return The account representation. */ @Get public AccountRepresentation represent(); } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/api/AccountRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch10/sec3/api/AccountReprese0000664000175000017500000000604011757206352033763 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch10.sec3.api; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias("account") public class AccountRepresentation { private volatile String login; private volatile String firstName; private volatile String lastName; private volatile String nickName; private volatile String senderName; private volatile String emailAddress; @XStreamImplicit private volatile List contactRefs; public AccountRepresentation() { this.contactRefs = new CopyOnWriteArrayList(); } public List getContactRefs() { return contactRefs; } public String getEmailAddress() { return emailAddress; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getLogin() { return login; } public String getNickName() { return nickName; } public String getSenderName() { return senderName; } public void setContactRefs(List contactRefs) { this.contactRefs = contactRefs; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setLogin(String login) { this.login = login; } public void setNickName(String nickName) { this.nickName = nickName; } public void setSenderName(String senderName) { this.senderName = senderName; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/0000775000175000017500000000000011757206350027514 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/0000775000175000017500000000000011757206352030354 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub3/0000775000175000017500000000000011757206352031230 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub3/RangeClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub3/RangeClient.j0000664000175000017500000000332511757206350033577 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub3; import org.restlet.data.Range; import org.restlet.resource.ClientResource; public class RangeClient { public static void main(String[] args) throws Exception { ClientResource resource = new ClientResource("http://localhost:8111/"); // Requesting the first five characters. resource.getRanges().add(new Range(0, 5)); // Get the representation of the resource resource.get().write(System.out); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub3/RangeServer.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub3/RangeServer.j0000664000175000017500000000354111757206352033631 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub3; import org.restlet.Application; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch01.HelloServerResource; public class RangeServer { public static void main(String[] args) throws Exception { // Instantiating the Application providing the Range Service Application app = new Application(); // Plug the server resource. app.setInboundRoot(HelloServerResource.class); // Instantiating the HTTP server and listening on port 8111 new Server(Protocol.HTTP, 8111, app).start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub5/0000775000175000017500000000000011757206352031232 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub5/CachingServer.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub5/CachingServer0000664000175000017500000000323511757206350033701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub5; import org.restlet.Component; import org.restlet.data.Protocol; public class CachingServer { public static void main(String[] args) throws Exception { Component component = new Component(); component.getDefaultHost().attachDefault( CachingServerResource.class); component.getServers().add(Protocol.HTTP, 8111); component.start(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub5/CachingClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub5/CachingClient0000664000175000017500000000346411757206352033657 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub5; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; public class CachingClient { public static void main(String[] args) throws Exception { ClientResource resource = new ClientResource("http://localhost:8111/"); // Get a representation Representation rep = resource.get(); System.out.println("Modified: " + rep.getModificationDate()); System.out.println("Expires: " + rep.getExpirationDate()); System.out.println("E-Tag: " + rep.getTag()); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub5/CachingServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub5/CachingServer0000664000175000017500000000521311757206352033701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub5; import java.util.Calendar; import java.util.GregorianCalendar; import org.restlet.data.CacheDirective; import org.restlet.data.MediaType; import org.restlet.data.Tag; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; public class CachingServerResource extends ServerResource { @Get public Representation represent() { // Modification date (Fri, 17 Apr 2009 10:10:10 GMT) unchanged. Calendar cal = new GregorianCalendar(2009, 3, 17, 10, 10, 10); Representation result = new StringRepresentation("" + System.currentTimeMillis() + ""); result.setMediaType(MediaType.TEXT_HTML); result.setModificationDate(cal.getTime()); // Expiration date (Fri, 17 Apr 2019 10:10:10 GMT) unchanged. cal = new GregorianCalendar(2019, 3, 17, 10, 10, 10); result.setExpirationDate(cal.getTime()); // Setting E-Tag result.setTag(new Tag("xyz123")); // Setting a cache directive getResponse().getCacheDirectives().add(CacheDirective.publicInfo()); return result; } @Put public void store(Representation entity) { System.out.println("Storing a new entity."); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub1/0000775000175000017500000000000011757206352031226 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub1/DynamicContentServer.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub1/DynamicConten0000664000175000017500000000315011757206352033703 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub1; import org.restlet.Server; import org.restlet.data.Protocol; public class DynamicContentServer { public static void main(String[] args) throws Exception { // Instantiating the HTTP server and listening on port 8111 new Server(Protocol.HTTP, 8111, DynamicContentServerResource.class) .start(); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub1/DynamicContentServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub1/DynamicConten0000664000175000017500000000422511757206352033707 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub1; import java.io.IOException; import java.io.Writer; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Resource that generates content dynamically. */ public class DynamicContentServerResource extends ServerResource { @Get public Representation getDynamicContent() { // Inline sub class of WriterRepresentation that writes // its dynamic content. Representation result = new WriterRepresentation(MediaType.TEXT_PLAIN) { @Override public void write(Writer writer) throws IOException { for (int i = 0; i < 10; i++) { writer.append(Integer.toString(i)); } } }; return result; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub1/DynamicContentClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub1/DynamicConten0000664000175000017500000000304711757206352033710 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub1; import org.restlet.resource.ClientResource; public class DynamicContentClient { public static void main(String[] args) throws Exception { ClientResource resource = new ClientResource("http://localhost:8111/"); resource.get().write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub6/0000775000175000017500000000000011757206350031231 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub6/ConditionalClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec4/sub6/ConditionalCl0000664000175000017500000000525311757206350033703 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec4.sub6; import org.restlet.data.Tag; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; public class ConditionalClient { public static void main(String[] args) throws Exception { ClientResource resource = new ClientResource("http://localhost:8111/"); // Get a representation Representation rep = resource.get(); System.out.println(resource.getStatus()); // Get an updated representation, if modified resource.getConditions().setModifiedSince(rep.getModificationDate()); rep = resource.get(); System.out.println(resource.getStatus()); // Get an updated representation, if tag changed resource.getConditions().setModifiedSince(null); resource.getConditions().getNoneMatch().add(new Tag("xyz123")); rep = resource.get(); System.out.println(resource.getStatus()); // Put a new representation if tag has not changed resource.getConditions().getNoneMatch().clear(); resource.getConditions().getMatch().add(rep.getTag()); resource.put(rep); System.out.println(resource.getStatus()); // Put a new representation when a different tag resource.getConditions().getMatch().clear(); resource.getConditions().getMatch().add(new Tag("abcd7890")); resource.put(rep); System.out.println(resource.getStatus()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/0000775000175000017500000000000011757206352030352 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub1/0000775000175000017500000000000011757206352031224 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub1/FeedServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub1/FeedServerRes0000664000175000017500000000630011757206350033650 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec2.sub1; import java.util.ArrayList; import java.util.List; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Text; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; /** * Resource corresponding to an account feed associated to tags. */ public class FeedServerResource extends ServerResource { @Get("atom") public Feed toAtom() throws ResourceException { Feed result = new Feed(); result.setTitle(new Text("Homer's feed")); Entry entry; for (int i = 1; i < 11; i++) { entry = new Entry(); entry.setTitle(new Text("Mail n�" + i)); entry.setSummary("Doh! This is the content of mail n�" + i); result.getEntries().add(entry); } return result; } @Get("rss") public SyndFeed toRss() throws ResourceException { SyndFeed result = new SyndFeedImpl(); result.setTitle("Homer's feed"); result.setDescription("Homer's feed"); result.setLink(getReference().toString()); List entries = new ArrayList(); result.setEntries(entries); SyndEntry entry; SyndContent description; for (int i = 1; i < 11; i++) { entry = new SyndEntryImpl(); entry.setTitle("Mail n�" + i); description = new SyndContentImpl(); description.setValue("Doh! This is the content of mail n�" + i); entry.setDescription(description); entries.add(entry); } return result; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub1/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub1/MailServerApp0000664000175000017500000000437011757206352033665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec2.sub1; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Routing to annotated server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach( "http://localhost:8111/accounts/{accountId}/feeds/{feedId}", FeedServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub2/0000775000175000017500000000000011757206352031225 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub2/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec2/sub2/MailClient.ja0000664000175000017500000000517611757206352033573 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec2.sub2; import java.util.List; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.resource.ClientResource; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; /** * Mail client updating a mail by submitting a form. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/123/feeds/xyz"); // Display the retrieved Atom feed and entries Feed atomFeed = mailClient.get(Feed.class); System.out.println("\nAtom feed: " + atomFeed.getTitle() + "\n"); for (Entry entry : atomFeed.getEntries()) { System.out.println("Title : " + entry.getTitle()); System.out.println("Summary: " + entry.getSummary()); } // Display the retrieved RSS feed and entries SyndFeed rssFeed = mailClient.get(SyndFeed.class); System.out.println("\nRSS feed: " + rssFeed.getTitle() + "\n"); @SuppressWarnings("unchecked") List entries = (List) rssFeed.getEntries(); for (SyndEntry entry : entries) { System.out.println("Title : " + entry.getTitle()); System.out.println("Summary: " + entry.getDescription().getValue()); } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/0000775000175000017500000000000011757206352030353 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub1/0000775000175000017500000000000011757206352031225 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub1/RedirectedClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub1/RedirectedCli0000664000175000017500000000304311757206350033650 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec3.sub1; import org.restlet.resource.ClientResource; public class RedirectedClient { public static void main(String[] args) throws Exception { ClientResource resource = new ClientResource("http://localhost:8113/"); resource.get().write(System.out); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub1/OldServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub1/OldServerReso0000664000175000017500000000342411757206352033711 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec3.sub1; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Resource that simply redirects to the port 8111. */ public class OldServerResource extends ServerResource { @Get public String redirect() { // Sets the response status to 301 (Moved Permanently) redirectPermanent("http://localhost:8111/"); System.out.println("Redirecting client to new location..."); // Add explanation message entity return "Resource moved... \n"; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub1/RedirectingServer.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub1/RedirectingSe0000664000175000017500000000341011757206350033673 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec3.sub1; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch01.HelloServerResource; public class RedirectingServer { public static void main(String[] args) throws Exception { // Launching the HelloServerResource on port 8111 new Server(Protocol.HTTP, 8111, HelloServerResource.class).start(); // Launching the RedirectionResource on port 8113 new Server(Protocol.HTTP, 8113, OldServerResource.class).start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub2/0000775000175000017500000000000011757206352031226 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub2/SearchRedirector.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec3/sub2/SearchRedirec0000664000175000017500000000605311757206352033660 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec3.sub2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Extractor; import org.restlet.routing.Redirector; import org.restlet.routing.Router; /** * URI rewriting, attribute extraction and redirection. * * @author Jerome Louvel */ public class SearchRedirector extends Application { public static void main(String[] args) throws Exception { // Create a component Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); // Create an application Application application = new SearchRedirector(); // Attach the application to the component and start it component.getDefaultHost().attachDefault(application); component.start(); } @Override public Restlet createInboundRoot() { // Create a root router Router router = new Router(getContext()); // Create a Redirector to Google search service String target = "http://www.google.com/search?q=site:mysite.org+{keywords}"; Redirector redirector = new Redirector(getContext(), target, Redirector.MODE_CLIENT_TEMPORARY); // While routing requests to the redirector, extract the "kwd" query // parameter. For instance : // http://localhost:8111/search?kwd=myKeyword1+myKeyword2 // will be routed to // http://www.google.com/search?q=site:mysite.org+myKeyword1%20myKeyword2 Extractor extractor = new Extractor(getContext(), redirector); extractor.extractFromQuery("keywords", "kwd", true); // Attach the extractor to the router router.attach("/search", extractor); // Return the root router return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/0000775000175000017500000000000011757206350030347 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub3/0000775000175000017500000000000011757206352031225 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub3/MergeSitesServicesServer.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub3/MergeSitesSer0000664000175000017500000000474511757206350033701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub3; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.resource.Directory; import org.restlet.routing.Router; public class MergeSitesServicesServer { public static void main(String[] args) throws Exception { Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getClients().add(Protocol.FILE); Application app = new Application() { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); // Serve static files (images, etc.) String rootUri = "file:///" + System.getProperty("java.io.tmpdir"); Directory directory = new Directory(getContext(), rootUri); directory.setListingAllowed(true); router.attach("/static", directory); // Attach the hello web service router.attach("/hello", HelloServerResource.class); return router; } }; component.getDefaultHost().attach(app); component.start(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub3/HelloServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub3/HelloServerRe0000664000175000017500000000331011757206352033666 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub3; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class HelloServerResource extends ServerResource { @Get("html") public String toHtml() { return "hello, world"; } @Get("xml") public String toXml() { return "hello, world"; } @Get("json") public String toJson() { return "{txt: \"hello, world\"}"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/0000775000175000017500000000000011757206352031227 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailServerRes0000664000175000017500000000736111757206352033704 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub5; import java.util.List; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.fileupload.RestletFileUpload; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages FreeMarker template engine. */ public class MailServerResource extends ServerResource { @Override protected Representation get() throws ResourceException { // Create the mail bean MailRepresentation mail = new MailRepresentation(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, mail, MediaType.TEXT_HTML); } @Override protected Representation put(Representation input) { try { // Create a factory for disk-based file items RestletFileUpload fileUpload = new RestletFileUpload( new DiskFileItemFactory()); List fileItems = fileUpload.parseRepresentation(input); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { System.out.println(fileItem.getFieldName() + "=" + fileItem.getString()); } else { Representation attachment = new InputRepresentation( fileItem.getInputStream()); attachment.write(System.out); } } } catch (Exception e) { e.printStackTrace(); } return new StringRepresentation("Mail updated!"); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailClient.ja0000664000175000017500000000345111757206350033565 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub5; import org.restlet.data.Form; import org.restlet.resource.ClientResource; /** * Mail client updating a mail by submitting a form. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/123/mails/abc"); Form form = new Form(); form.add("subject", "Message to Jérôme"); form.add("content", "Doh!\n\nAllo?"); mailClient.put(form).write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/Mail.ftl0000664000175000017500000000144311757206352032622 0ustar jamespagejamespage Example mail
    Status ${status}
    Subject
    Content
    Attachment
    ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailServerApp0000664000175000017500000000437011757206350033666 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub5; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Routing to annotated server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach( "http://localhost:8111/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub5/MailRepresent0000664000175000017500000000406411757206350033726 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub5; /** * The mail representation bean. */ public class MailRepresentation { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/0000775000175000017500000000000011757206352031223 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailServerRes0000664000175000017500000000623611757206350033676 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub1; import org.restlet.data.Form; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages FreeMarker template engine. */ public class MailServerResource extends ServerResource { @Override protected Representation get() throws ResourceException { // Create the mail representation bean MailRepresentation mail = new MailRepresentation(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, mail, MediaType.TEXT_HTML); } @Override protected Representation put(Representation input) { try { String inputText = input.getText(); System.out.println(inputText); Form form = new Form(inputText); for (Parameter entry : form) { System.out.println(entry.getName() + "=" + entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } return new StringRepresentation("Mail updated!"); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailClient.ja0000664000175000017500000000345311757206350033563 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub1; import org.restlet.data.Form; import org.restlet.resource.ClientResource; /** * Mail client updating a mail by submitting a form. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/123/mails/abc"); Form form = new Form(); form.add("subject", "Message to J�r�me"); form.add("content", "Doh!\n\nAllo?"); mailClient.put(form).write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/Mail.ftl0000664000175000017500000000123211757206352032612 0ustar jamespagejamespage Example mail
    Status ${status}
    Subject
    Content
    ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailServerApp0000664000175000017500000000437011757206350033662 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub1; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Routing to annotated server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach( "http://localhost:8111/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub1/MailRepresent0000664000175000017500000000406411757206352033724 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub1; /** * The mail representation bean. */ public class MailRepresentation { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/0000775000175000017500000000000011757206352031226 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailServerApp0000664000175000017500000000404311757206352033664 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub4; import org.restlet.Restlet; import org.restlet.ext.wadl.WadlApplication; import org.restlet.routing.Router; /** * The reusable mail server application. */ public class MailServerApplication extends WadlApplication { /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server application"); setDescription("Example application for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Configure the status service setStatusService(new MailStatusService()); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { return new Router(getContext()); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailStatus.ftlrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailStatus.ft0000664000175000017500000000055311757206352033652 0ustar jamespagejamespage Mail status page

    An error was detected in the ${applicationName} application.

    ${statusName} : ${statusDescription}

    ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailServerComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailServerCom0000664000175000017500000000453311757206350033664 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub4; import org.restlet.Component; import org.restlet.data.Protocol; /** * RESTful component containing the mail server application. */ public class MailServerComponent extends Component { /** * Launches the mail server component. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { new MailServerComponent().start(); } /** * Constructor. * * @throws Exception */ public MailServerComponent() throws Exception { // Set basic properties setName("RESTful Mail Server component"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Add a CLAP client connector getClients().add(Protocol.CLAP); // Adds a HTTP server connector getServers().add(Protocol.HTTP, 8111); // Attach the application to the default virtual host getDefaultHost().attachDefault(new MailServerApplication()); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailStatusService.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub4/MailStatusSer0000664000175000017500000000520511757206350033711 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub4; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.service.StatusService; public class MailStatusService extends StatusService { @Override public Representation getRepresentation(Status status, Request request, Response response) { // Create the data model Map dataModel = new ConcurrentHashMap(); dataModel.put("applicationName", Application.getCurrent().getName()); dataModel.put("statusName", response.getStatus().getName()); dataModel.put("statusDescription", response.getStatus() .getDescription()); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/MailStatus.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, dataModel, MediaType.TEXT_HTML); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/0000775000175000017500000000000011757206352031224 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailServerRes0000664000175000017500000000623711757206350033700 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub2; import org.restlet.data.Form; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages FreeMarker template engine. */ public class MailServerResource extends ServerResource { @Override protected Representation get() throws ResourceException { // Create the mail bean MailRepresentation mail = new MailRepresentation(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, mail, MediaType.TEXT_HTML); } @Override protected Representation put(Representation input) { try { String inputText = input.getText(); System.out.println(inputText); Form form = new Form(inputText); for (Parameter entry : form) { System.out.println(entry.getName() + "=" + entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } return new StringRepresentation("Mail updated!"); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailClient.ja0000664000175000017500000000367111757206352033570 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub2; import org.restlet.data.Cookie; import org.restlet.data.Form; import org.restlet.resource.ClientResource; /** * Mail client updating a mail by submitting a form. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/123/mails/abc"); mailClient.getRequest().getCookies() .add(new Cookie("Credentials", "scott=tiger")); Form form = new Form(); form.add("subject", "Message to J�r�me"); form.add("content", "Doh!\n\nAllo?"); mailClient.put(form).write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/Login.ftl0000664000175000017500000000105411757206352033003 0ustar jamespagejamespage Mail login
    Login
    Password
    restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/Mail.ftl0000664000175000017500000000123211757206352032613 0ustar jamespagejamespage Example mail
    Status ${status}
    Subject
    Content
    ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailServerApp0000664000175000017500000000515311757206352033665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub2; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.Router; import org.restlet.security.MapVerifier; /** * Routing to annotated server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach( "http://localhost:8111/accounts/{accountId}/mails/{mailId}", MailServerResource.class); MapVerifier verifier = new MapVerifier(); verifier.getLocalSecrets().put("scott", "tiger".toCharArray()); CookieAuthenticator authenticator = new CookieAuthenticator( getContext(), "Cookie Test"); authenticator.setVerifier(verifier); authenticator.setNext(router); return authenticator; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/MailRepresent0000664000175000017500000000406411757206350033723 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub2; /** * The mail representation bean. */ public class MailRepresentation { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/CookieAuthenticator.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec1/sub2/CookieAuthent0000664000175000017500000001233311757206350033711 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec1.sub2; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Cookie; import org.restlet.data.CookieSetting; import org.restlet.data.Form; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.Verifier; public class CookieAuthenticator extends ChallengeAuthenticator { public CookieAuthenticator(Context context, boolean optional, String realm) { super(context, optional, ChallengeScheme.HTTP_COOKIE, realm); } public CookieAuthenticator(Context context, boolean optional, String realm, Verifier verifier) { super(context, optional, ChallengeScheme.HTTP_COOKIE, realm, verifier); } public CookieAuthenticator(Context context, String realm) { super(context, ChallengeScheme.HTTP_COOKIE, realm); } @Override protected int beforeHandle(Request request, Response response) { Cookie cookie = request.getCookies().getFirst("Credentials"); if (cookie != null) { // Extract the challenge response from the cookie String[] credentials = cookie.getValue().split("="); if (credentials.length == 2) { String identifier = credentials[0]; String secret = credentials[1]; request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_COOKIE, identifier, secret)); } } else if (Method.POST.equals(request.getMethod()) && request.getResourceRef().getQueryAsForm().getFirst("login") != null) { // Intercepting a login form Form credentials = new Form(request.getEntity()); String identifier = credentials.getFirstValue("identifier"); String secret = credentials.getFirstValue("secret"); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_COOKIE, identifier, secret)); // Continue call processing to return the target representation if // authentication is successful or a new login page request.setMethod(Method.GET); } return super.beforeHandle(request, response); } @Override public void challenge(Response response, boolean stale) { // Load the FreeMarker template Representation ftl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Login.ftl").get(); // Wraps the bean with a FreeMarker representation response.setEntity(new TemplateRepresentation(ftl, response .getRequest().getResourceRef(), MediaType.TEXT_HTML)); response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); } @Override protected void afterHandle(Request request, Response response) { super.afterHandle(request, response); Cookie cookie = request.getCookies().getFirst("Credentials"); if (request.getClientInfo().isAuthenticated() && (cookie == null)) { String identifier = request.getChallengeResponse().getIdentifier(); String secret = new String(request.getChallengeResponse() .getSecret()); CookieSetting cookieSetting = new CookieSetting("Credentials", identifier + "=" + secret); cookieSetting.setAccessRestricted(true); cookieSetting.setPath("/"); cookieSetting.setComment("Unsecured cookie based authentication"); cookieSetting.setMaxAge(30); response.getCookieSettings().add(cookieSetting); } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/0000775000175000017500000000000011757206352030355 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/0000775000175000017500000000000011757206352032017 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailSiteApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailSiteAp0000664000175000017500000000771011757206350033735 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.resource.Directory; import org.restlet.routing.Extractor; import org.restlet.routing.Redirector; import org.restlet.routing.Router; import org.restlet.security.MapVerifier; /** * The reusable mail server application. */ public class MailSiteApplication extends Application { /** * Constructor. */ public MailSiteApplication() { setName("RESTful Mail Site application"); setDescription("Example Site for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Configure the status service setStatusService(new MailStatusService()); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/", RootServerResource.class); router.attach("/accounts/", AccountsServerResource.class); router.attach("/accounts/{accountId}", AccountServerResource.class); router.attach("/accounts/{accountId}/feeds/{feedId}", FeedServerResource.class); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); // Serve static files (images, etc.) String rootUri = "file:///" + System.getProperty("java.io.tmpdir"); Directory directory = new Directory(getContext(), rootUri); directory.setListingAllowed(true); router.attach("/static", directory); // Create a Redirector to Google search service String target = "http://www.google.com/search?q=site:mysite.org+{keywords}"; Redirector redirector = new Redirector(getContext(), target, Redirector.MODE_CLIENT_TEMPORARY); // While routing requests to the redirector, extract the "kwd" query // parameter. For instance : // http://localhost:8111/search?kwd=myKeyword1+myKeyword2 // will be routed to // http://www.google.com/search?q=site:mysite.org+myKeyword1%20myKeyword2 Extractor extractor = new Extractor(getContext(), redirector); extractor.extractFromQuery("keywords", "kwd", true); // Attach the extractor to the router router.attach("/search", extractor); MapVerifier verifier = new MapVerifier(); verifier.getLocalSecrets().put("scott", "tiger".toCharArray()); CookieAuthenticator authenticator = new CookieAuthenticator( getContext(), "Cookie Test"); authenticator.setVerifier(verifier); authenticator.setNext(router); return authenticator; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/AccountSer0000664000175000017500000000267011757206350034013 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import org.restlet.resource.ServerResource; /** * Implementation of a mail account resource. */ public class AccountServerResource extends ServerResource { } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailServer0000664000175000017500000000774711757206350034030 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import java.util.List; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.MailRepresentation; import org.restlet.ext.fileupload.RestletFileUpload; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages FreeMarker template engine. */ public class MailServerResource extends ServerResource { @Override protected Representation get() throws ResourceException { // Create the mail URI inside the API application String accountId = (String) getRequestAttributes().get("accountId"); String mailId = (String) getRequestAttributes().get("mailId"); String mailApiUri = "riap://component/api/accounts/" + accountId + "/mails/" + mailId; // Optimal internal call using the server dispatcher ClientResource cr = new ClientResource(mailApiUri); MailRepresentation mail = cr.get(MailRepresentation.class); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, mail, MediaType.TEXT_HTML); } @Override protected Representation put(Representation input) { try { // Create a factory for disk-based file items RestletFileUpload fileUpload = new RestletFileUpload( new DiskFileItemFactory()); List fileItems = fileUpload.parseRepresentation(input); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { System.out.println(fileItem.getFieldName() + "=" + fileItem.getString()); } else { Representation attachment = new InputRepresentation( fileItem.getInputStream()); attachment.write(System.out); } } } catch (Exception e) { e.printStackTrace(); } return new StringRepresentation("Mail updated!"); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/FeedServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/FeedServer0000664000175000017500000000630311757206350033774 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import java.util.ArrayList; import java.util.List; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.ext.atom.Text; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; /** * Resource corresponding to an account feed associated to tags. */ public class FeedServerResource extends ServerResource { @Get("atom") public Feed toAtom() throws ResourceException { Feed result = new Feed(); result.setTitle(new Text("Homer's feed")); Entry entry; for (int i = 1; i < 11; i++) { entry = new Entry(); entry.setTitle(new Text("Mail n�" + i)); entry.setSummary("Doh! This is the content of mail n�" + i); result.getEntries().add(entry); } return result; } @Get("rss") public SyndFeed toRss() throws ResourceException { SyndFeed result = new SyndFeedImpl(); result.setTitle("Homer's feed"); result.setDescription("Homer's feed"); result.setLink(getReference().toString()); List entries = new ArrayList(); result.setEntries(entries); SyndEntry entry; SyndContent description; for (int i = 1; i < 11; i++) { entry = new SyndEntryImpl(); entry.setTitle("Mail n�" + i); description = new SyndContentImpl(); description.setValue("Doh! This is the content of mail n�" + i); entry.setDescription(description); entries.add(entry); } return result; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/Login.ftl0000664000175000017500000000105411757206352033576 0ustar jamespagejamespage Mail login
    Login
    Password
    restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/Root.ftl0000664000175000017500000000055311757206352033454 0ustar jamespagejamespage Mail status page

    An error was detected in the ${applicationName} application.

    ${statusName} : ${statusDescription}

    restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/Mail.ftl0000664000175000017500000000144311757206352033412 0ustar jamespagejamespage Example mail
    Status ${status}
    Subject
    Content
    Attachment
    ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailStatus.ftlrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailStatus0000664000175000017500000000055311757206352034033 0ustar jamespagejamespage Mail status page

    An error was detected in the ${applicationName} application.

    ${statusName} : ${statusDescription}

    ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/AccountsSe0000664000175000017500000000272311757206352034015 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import org.restlet.resource.ServerResource; /** * Implementation of the resource containing the list of mail accounts. */ public class AccountsServerResource extends ServerResource{ } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailStatusService.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/MailStatus0000664000175000017500000000515111757206350034030 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import java.util.Map; import java.util.TreeMap; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.service.StatusService; public class MailStatusService extends StatusService { @Override public Representation getRepresentation(Status status, Request request, Response response) { // Create the data model Map dataModel = new TreeMap(); dataModel.put("applicationName", Application.getCurrent().getName()); dataModel.put("statusName", response.getStatus().getName()); dataModel.put("statusDescription", response.getStatus() .getDescription()); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/MailStatus.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, dataModel, MediaType.TEXT_HTML); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/RootServer0000664000175000017500000000521611757206350034056 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.MailRepresentation; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Root resource implementation. */ public class RootServerResource extends ServerResource { @Override protected Representation get() throws ResourceException { // Create the mail bean MailRepresentation mail = new MailRepresentation(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, mail, MediaType.TEXT_HTML); } public String represent() { return "Welcome to the " + getApplication().getName() + " !"; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/CookieAuthenticator.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/website/CookieAuth0000664000175000017500000001233611757206350034000 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.website; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Cookie; import org.restlet.data.CookieSetting; import org.restlet.data.Form; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.Verifier; public class CookieAuthenticator extends ChallengeAuthenticator { public CookieAuthenticator(Context context, boolean optional, String realm) { super(context, optional, ChallengeScheme.HTTP_COOKIE, realm); } public CookieAuthenticator(Context context, boolean optional, String realm, Verifier verifier) { super(context, optional, ChallengeScheme.HTTP_COOKIE, realm, verifier); } public CookieAuthenticator(Context context, String realm) { super(context, ChallengeScheme.HTTP_COOKIE, realm); } @Override protected int beforeHandle(Request request, Response response) { Cookie cookie = request.getCookies().getFirst("Credentials"); if (cookie != null) { // Extract the challenge response from the cookie String[] credentials = cookie.getValue().split("="); if (credentials.length == 2) { String identifier = credentials[0]; String secret = credentials[1]; request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_COOKIE, identifier, secret)); } } else if (Method.POST.equals(request.getMethod()) && request.getResourceRef().getQueryAsForm().getFirst("login") != null) { // Intercepting a login form Form credentials = new Form(request.getEntity()); String identifier = credentials.getFirstValue("identifier"); String secret = credentials.getFirstValue("secret"); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_COOKIE, identifier, secret)); // Continue call processing to return the target representation if // authentication is successful or a new login page request.setMethod(Method.GET); } return super.beforeHandle(request, response); } @Override public void challenge(Response response, boolean stale) { // Load the FreeMarker template Representation ftl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Login.ftl").get(); // Wraps the bean with a FreeMarker representation response.setEntity(new TemplateRepresentation(ftl, response .getRequest().getResourceRef(), MediaType.TEXT_HTML)); response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); } @Override protected void afterHandle(Request request, Response response) { super.afterHandle(request, response); Cookie cookie = request.getCookies().getFirst("Credentials"); if (request.getClientInfo().isAuthenticated() && (cookie == null)) { String identifier = request.getChallengeResponse().getIdentifier(); String secret = new String(request.getChallengeResponse() .getSecret()); CookieSetting cookieSetting = new CookieSetting("Credentials", identifier + "=" + secret); cookieSetting.setAccessRestricted(true); cookieSetting.setPath("/"); cookieSetting.setComment("Unsecured cookie based authentication"); cookieSetting.setMaxAge(30); response.getCookieSettings().add(cookieSetting); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/MailServerComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/MailServerComponen0000664000175000017500000000504411757206352034053 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5; import org.restlet.Component; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch07.sec5.webapi.server.MailApiApplication; import org.restlet.example.book.restlet.ch07.sec5.website.MailSiteApplication; /** * RESTful component containing the mail API and mail site applications. */ public class MailServerComponent extends Component { /** * Launches the mail server component. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { new MailServerComponent().start(); } /** * Constructor. * * @throws Exception */ public MailServerComponent() throws Exception { // Set basic properties setName("RESTful Mail Server component"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Add client connectors getClients().add(Protocol.CLAP); // Adds server connectors getServers().add(Protocol.HTTP, 8111); // Attach the applications getDefaultHost().attach("/site", new MailSiteApplication()); getInternalRouter().attach("/api", new MailApiApplication()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/0000775000175000017500000000000011757206352031624 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/client/0000775000175000017500000000000011757206352033102 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/client/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/client/Mail0000664000175000017500000000725311757206352033716 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.client; import java.util.List; import org.restlet.data.Cookie; import org.restlet.data.Form; import org.restlet.ext.atom.Entry; import org.restlet.ext.atom.Feed; import org.restlet.resource.ClientResource; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; /** * Mail client. */ public class MailClient { /** * Mail client interacting with the RESTful mail server. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { System.out.println("\n1) Set-up the service client resource\n"); ClientResource service = new ClientResource("http://localhost:8111/"); System.out.println("\n2) Describe the application\n"); System.out.println(service.options().getText()); System.out.println("\n3) Describe the accounts resource\n"); System.out.println(service.getChild("/accounts/").options().getText()); // FORM SUBMIT ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/123/mails/abc"); mailClient.getRequest().getCookies() .add(new Cookie("Credentials", "scott=tiger")); Form form = new Form(); form.add("subject", "Message to Jérôme"); form.add("content", "Doh!\n\nAllo?"); mailClient.put(form).write(System.out); // WEB FEEDS mailClient = new ClientResource( "http://localhost:8111/accounts/123/feeds/xyz"); // Display the retrieved Atom feed and entries Feed atomFeed = mailClient.get(Feed.class); System.out.println("\nAtom feed: " + atomFeed.getTitle() + "\n"); for (Entry entry : atomFeed.getEntries()) { System.out.println("Title : " + entry.getTitle()); System.out.println("Summary: " + entry.getSummary()); } // Display the retrieved RSS feed and entries SyndFeed rssFeed = mailClient.get(SyndFeed.class); System.out.println("\nRSS feed: " + rssFeed.getTitle() + "\n"); @SuppressWarnings("unchecked") List entries = (List) rssFeed.getEntries(); for (SyndEntry entry : entries) { System.out.println("Title : " + entry.getTitle()); System.out.println("Summary: " + entry.getDescription().getValue()); } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/0000775000175000017500000000000011757206352033114 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/AccountResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Acco0000664000175000017500000000374011757206352033710 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * User account resource. */ public interface AccountResource { /** * Represents the account as a simple string with the owner name for now. * * @return The account representation. */ @Get public AccountRepresentation represent(); /** * Stores the new value for the identified account. * * @param account * The identified account. */ @Put public void store(AccountRepresentation account); /** * Deletes the identified account by setting its value to null. */ @Delete public void remove(); } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/ContactRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Cont0000664000175000017500000000433511757206352033747 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; public class ContactRepresentation { private String firstName; private String lastName; private String login; private String nickName; private String senderName; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getLogin() { return login; } public String getNickName() { return nickName; } public String getSenderName() { return senderName; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setLogin(String login) { this.login = login; } public void setNickName(String nickName) { this.nickName = nickName; } public void setSenderName(String senderName) { this.senderName = senderName; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/TagRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/TagR0000664000175000017500000000250111757206350033670 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; public class TagRepresentation { } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/AccountsResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Acco0000664000175000017500000000360011757206350033701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; import org.restlet.resource.Get; import org.restlet.resource.Post; /** * Collection resource containing user accounts. */ public interface AccountsResource { /** * Returns the list of accounts, each one on a separate line. * * @return The list of accounts. */ @Get public String represent(); /** * Add the given account to the list and returns its position as an * identifier. * * @param account * The account to add. * @return The account identifier. */ @Post public String add(AccountRepresentation account); } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/RootResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Root0000664000175000017500000000304411757206352033763 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; import org.restlet.resource.Get; /** * Root resource. */ public interface RootResource { /** * Represents the application root with a welcome message. * * @return The root representation. */ @Get public String represent(); } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/MailRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Mail0000664000175000017500000000407511757206350033725 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; /** * The mail representation bean. */ public class MailRepresentation { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/MailResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Mail0000664000175000017500000000303611757206350033721 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * Annotated mail resource interface */ public interface MailResource { @Get public MailRepresentation retrieve(); @Put public void store(MailRepresentation mail); } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/AccountRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Acco0000664000175000017500000000377411757206350033715 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; import java.util.List; public class AccountRepresentation { private List contactRefs; private List mailRefs; private List feedRefs; public AccountRepresentation() { } public List getContactRefs() { return contactRefs; } public List getFeedRefs() { return feedRefs; } public List getMailRefs() { return mailRefs; } public void setContactRefs(List contactRefs) { this.contactRefs = contactRefs; } public void setFeedRefs(List feedRefs) { this.feedRefs = feedRefs; } public void setMailRefs(List mailRefs) { this.mailRefs = mailRefs; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/FeedRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/common/Feed0000664000175000017500000000250211757206350033677 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.common; public class FeedRepresentation { } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/0000775000175000017500000000000011757206352033132 5ustar jamespagejamespage././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/Acco0000664000175000017500000000646411757206352033734 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.server; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.AccountRepresentation; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.AccountResource; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.WadlServerResource; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Implementation of a mail account resource. */ public class AccountServerResource extends WadlServerResource implements AccountResource { /** The account identifier. */ private int accountId; @Override protected RepresentationInfo describe(MethodInfo methodInfo, Class representationClass, Variant variant) { RepresentationInfo result = new RepresentationInfo(variant); result.setReference("account"); return result; } /** * Retrieve the account identifier based on the URI path variable * "accountId" declared in the URI template attached to the application * router. */ @Override protected void doInit() throws ResourceException { String accountIdAttribute = (String) getRequestAttributes().get( "accountId"); if (accountIdAttribute != null) { this.accountId = Integer.parseInt(accountIdAttribute); setName("Resource for mail account \"" + this.accountId + "\""); setDescription("The resource describing the mail account number \"" + this.accountId + "\""); } else { setName("Mail account resource"); setDescription("The resource describing a mail account"); } } public void remove() { AccountsServerResource.getAccounts().remove(this.accountId); } public AccountRepresentation represent() { return AccountsServerResource.getAccounts().get(this.accountId); } public void store(AccountRepresentation account) { AccountsServerResource.getAccounts().set(this.accountId, account); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/Mail0000664000175000017500000000455311757206350033744 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.server; import org.restlet.data.Reference; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.MailRepresentation; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.MailResource; import org.restlet.ext.wadl.WadlServerResource; /** * Mail server resource implementing the {@link MailResource} interface. */ public class MailServerResource extends WadlServerResource implements MailResource { public MailRepresentation retrieve() { MailRepresentation mail = new MailRepresentation(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); return mail; } public void store(MailRepresentation mail) { System.out.println("Status: " + mail.getStatus()); System.out.println("Subject: " + mail.getSubject()); System.out.println("Content: " + mail.getContent()); System.out.println("Account URI: " + mail.getAccountRef()); System.out.println(); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/MailApiApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/Mail0000664000175000017500000000441611757206352033744 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.server; import org.restlet.Restlet; import org.restlet.ext.wadl.WadlApplication; import org.restlet.routing.Router; /** * The reusable mail server application. */ public class MailApiApplication extends WadlApplication { /** * Constructor. */ public MailApiApplication() { setName("RESTful Mail API application"); setDescription("Example API for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/", RootServerResource.class); router.attach("/accounts/", AccountsServerResource.class); router.attach("/accounts/{accountId}", AccountServerResource.class); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/Acco0000664000175000017500000000741411757206350033726 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.server; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.MediaType; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.AccountRepresentation; import org.restlet.example.book.restlet.ch07.sec5.webapi.common.AccountsResource; import org.restlet.ext.wadl.ApplicationInfo; import org.restlet.ext.wadl.DocumentationInfo; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.WadlServerResource; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Implementation of the resource containing the list of mail accounts. */ public class AccountsServerResource extends WadlServerResource implements AccountsResource { /** Static list of accounts stored in memory. */ private static final List accounts = new CopyOnWriteArrayList(); @Override protected void describe(ApplicationInfo applicationInfo) { RepresentationInfo rep = new RepresentationInfo(MediaType.TEXT_PLAIN); rep.setIdentifier("account"); applicationInfo.getRepresentations().add(rep); DocumentationInfo doc = new DocumentationInfo(); doc.setTitle("Account"); doc.setTextContent("Simple string containing the account ID"); rep.getDocumentations().add(doc); } @Override protected RepresentationInfo describe(MethodInfo methodInfo, Class representationClass, Variant variant) { RepresentationInfo result = new RepresentationInfo(variant); result.setReference("account"); return result; } @Override protected void doInit() throws ResourceException { setName("Mail accounts resource"); setDescription("The resource containing the list of mail accounts"); } /** * Returns the static list of accounts stored in memory. * * @return The static list of accounts. */ public static List getAccounts() { return accounts; } public String represent() { StringBuilder result = new StringBuilder(); for (AccountRepresentation account : getAccounts()) { result.append((account == null) ? "" : account).append('\n'); } return result.toString(); } public String add(AccountRepresentation account) { getAccounts().add(account); return Integer.toString(getAccounts().indexOf(account)); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch07/sec5/webapi/server/Root0000664000175000017500000000521511757206352034003 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch07.sec5.webapi.server; import org.restlet.data.MediaType; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.RootResource; import org.restlet.ext.wadl.DocumentationInfo; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.WadlServerResource; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Root resource implementation. */ public class RootServerResource extends WadlServerResource implements RootResource { @Override protected RepresentationInfo describe(MethodInfo methodInfo, Class representationClass, Variant variant) { RepresentationInfo result = new RepresentationInfo(MediaType.TEXT_PLAIN); result.setIdentifier("root"); DocumentationInfo doc = new DocumentationInfo(); doc.setTitle("Mail application"); doc .setTextContent("Simple string welcoming the user to the mail application"); result.getDocumentations().add(doc); return result; } @Override protected void doInit() throws ResourceException { setAutoDescribing(false); setName("Root resource"); setDescription("The root resource of the mail server application"); } public String represent() { return "Welcome to the " + getApplication().getName() + " !"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/0000775000175000017500000000000011757206350027507 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect3/0000775000175000017500000000000011757206352030532 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect3/sub1/0000775000175000017500000000000011757206352031404 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect3/sub1/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect3/sub1/MailServerAp0000664000175000017500000000541511757206352033666 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect3.sub1; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.MediaType; import org.restlet.data.Protocol; /** * Providing the inbound root Restlet for the application */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Creates a root Restlet to trace requests. */ @Override public Restlet createInboundRoot() { return new Restlet() { @Override public void handle(Request request, Response response) { String entity = "Method : " + request.getMethod() + "\nResource URI : " + request.getResourceRef() + "\nIP address : " + request.getClientInfo().getAddress() + "\nAgent name : " + request.getClientInfo().getAgentName() + "\nAgent version: " + request.getClientInfo().getAgentVersion(); response.setEntity(entity, MediaType.TEXT_PLAIN); } }; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect3/sub2/0000775000175000017500000000000011757206350031403 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect3/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect3/sub2/MailServerAp0000664000175000017500000000577711757206350033700 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect3.sub2; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.MediaType; import org.restlet.data.Protocol; /** * Setting basic application properties. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Restlet to trace requests. */ @Override public Restlet createInboundRoot() { return new Restlet() { @Override public void handle(Request request, Response response) { String entity = "Method : " + request.getMethod() + "\nResource URI : " + request.getResourceRef() + "\nIP address : " + request.getClientInfo().getAddress() + "\nAgent name : " + request.getClientInfo().getAgentName() + "\nAgent version: " + request.getClientInfo().getAgentVersion(); response.setEntity(entity, MediaType.TEXT_PLAIN); } }; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/0000775000175000017500000000000011757206352030534 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub3/0000775000175000017500000000000011757206352031410 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub3/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub3/MailClient.j0000664000175000017500000000326411757206352033611 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub3; import org.restlet.resource.ClientResource; /** * Illustrating features of client resources. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailRoot = new ClientResource("http://localhost:8111/"); mailRoot.get().write(System.out); String result = mailRoot.get(String.class); System.out.println("\n" + result); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/0000775000175000017500000000000011757206350031410 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/common/0000775000175000017500000000000011757206352032702 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/common/AccountResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/common/Accou0000664000175000017500000000371711757206350033665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub5.common; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * User account resource. */ public interface AccountResource { /** * Represents the account as a simple string with the owner name for now. * * @return The account representation. */ @Get("txt") public String represent(); /** * Stores the new value for the identified account. * * @param account * The identified account. */ @Put("txt") public void store(String account); /** * Deletes the identified account by setting its value to null. */ @Delete public void remove(); } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/common/AccountsResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/common/Accou0000664000175000017500000000357611757206350033670 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub5.common; import org.restlet.resource.Get; import org.restlet.resource.Post; /** * Collection resource containing user accounts. */ public interface AccountsResource { /** * Returns the list of accounts, each one on a separate line. * * @return The list of accounts. */ @Get("txt") public String represent(); /** * Add the given account to the list and returns its position as an * identifier. * * @param account * The account to add. * @return The account identifier. */ @Post("txt") public String add(String account); } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/common/RootResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/common/RootR0000664000175000017500000000305211757206352033672 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub5.common; import org.restlet.resource.Get; /** * Root resource. */ public interface RootResource { /** * Represents the application root with a welcome message. * * @return The root representation. */ @Get("txt") public String represent(); } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/0000775000175000017500000000000011757206352032720 5ustar jamespagejamespage././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/Accou0000664000175000017500000000453211757206352033701 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub5.server; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Implementation of a mail account resource. */ public class AccountServerResource extends ServerResource implements AccountResource { /** The account identifier. */ private int accountId; /** * Retrieve the account identifier based on the URI path variable * "accountId" declared in the URI template attached to the application * router. */ @Override protected void doInit() throws ResourceException { this.accountId = Integer.parseInt((String) getRequestAttributes().get( "accountId")); } public String represent() { return AccountsServerResource.getAccounts().get(this.accountId); } public void store(String account) { AccountsServerResource.getAccounts().set(this.accountId, account); } public void remove() { AccountsServerResource.getAccounts().remove(this.accountId); } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/MailS0000664000175000017500000000424411757206350033652 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub5.server; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; /** * The reusable mail server application. */ public class MailServerApplication extends Application { /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server application"); setDescription("Example application for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/", RootServerResource.class); router.attach("/accounts/", AccountsServerResource.class); router.attach("/accounts/{accountId}", AccountServerResource.class); return router; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/Accou0000664000175000017500000000461011757206350033674 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub5.server; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountsResource; import org.restlet.resource.ServerResource; /** * Implementation of the resource containing the list of mail accounts. */ public class AccountsServerResource extends ServerResource implements AccountsResource { /** Static list of accounts stored in memory. */ private static final List accounts = new CopyOnWriteArrayList(); /** * Returns the static list of accounts stored in memory. * * @return The static list of accounts. */ public static List getAccounts() { return accounts; } public String represent() { StringBuilder result = new StringBuilder(); for (String account : getAccounts()) { result.append((account == null) ? "" : account).append('\n'); } return result.toString(); } public String add(String account) { getAccounts().add(account); return Integer.toString(getAccounts().indexOf(account)); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub5/server/RootS0000664000175000017500000000320011757206350033702 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub5.server; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.RootResource; import org.restlet.resource.ServerResource; /** * Root resource implementation. */ public class RootServerResource extends ServerResource implements RootResource { public String represent() { return "Welcome to the " + getApplication().getName() + " !"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/0000775000175000017500000000000011757206352031411 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/AccountServe0000664000175000017500000000266611757206350033745 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub4; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail account. */ public class AccountServerResource extends ServerResource { } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/MailClient.j0000664000175000017500000000326411757206350033610 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub4; import org.restlet.resource.ClientResource; /** * Creating dynamic proxies based on annotated Java interfaces. */ public class MailClient { public static void main(String[] args) throws Exception { RootResource mailRoot = ClientResource.create( "http://localhost:8111/", RootResource.class); String result = mailRoot.represent(); System.out.println(result); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/RootResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/RootResource0000664000175000017500000000303511757206350033766 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub4; import org.restlet.resource.Get; import org.restlet.resource.Options; /** * Annotated Java interface for the root resource. */ public interface RootResource { @Get("txt") public String represent(); @Options("txt") public String describe(); } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/MailServerAp0000664000175000017500000000524311757206350033670 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub4; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Routing to annotated server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("http://localhost:8111/", RootServerResource.class); router.attach("http://localhost:8111/accounts/", AccountsServerResource.class); router.attach("http://localhost:8111/accounts/{accountId}", AccountServerResource.class); return router; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/AccountsServ0000664000175000017500000000270211757206352033754 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub4; import org.restlet.resource.ServerResource; /** * Resource corresponding to the list of mail accounts. */ public class AccountsServerResource extends ServerResource { } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub4/RootServerRe0000664000175000017500000000321611757206350033735 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub4; import org.restlet.resource.ServerResource; /** * Implementing the Java annotated resource interface. */ public class RootServerResource extends ServerResource implements RootResource { public String represent() { return "This is the root resource"; } public String describe() { throw new RuntimeException("Not yet implemented"); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/0000775000175000017500000000000011757206352031407 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/AccountServe0000664000175000017500000000266611757206350033743 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub2; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail account. */ public class AccountServerResource extends ServerResource { } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/MailServerAp0000664000175000017500000000523111757206350033663 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub2; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Routing to server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("http://localhost:8111/", RootServerResource.class); router.attach("http://localhost:8111/accounts/", AccountsServerResource.class); router.attach("http://localhost:8111/accounts/{accountId}", AccountServerResource.class); return router; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/AccountsServ0000664000175000017500000000270211757206352033752 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub2; import org.restlet.resource.ServerResource; /** * Resource corresponding to the list of mail accounts. */ public class AccountsServerResource extends ServerResource { } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect5/sub2/RootServerRe0000664000175000017500000000557511757206352033747 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect5.sub2; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Illustrating server resource life cycle. */ public class RootServerResource extends ServerResource { /** * Constructor disabling content negotiation and indicating if the * identified resource already exists. */ public RootServerResource() { setNegotiated(false); // setExisting(false); } @Override protected void doInit() throws ResourceException { System.out.println("The root resource was initialized."); } @Override protected void doCatch(Throwable throwable) { System.out.println("An exception was thrown in the root resource."); } @Override protected void doRelease() throws ResourceException { System.out.println("The root resource was released.\n"); } /** * Handle the HTTP GET method by returning a simple textual representation. */ @Override protected Representation get() throws ResourceException { System.out.println("The GET method of root resource was invoked."); return new StringRepresentation("This is the root resource"); } /** * Handle the HTTP OPTIONS method by illustrating the impact of throwing an * exception. */ @Override protected Representation options() throws ResourceException { System.out.println("The OPTIONS method of root resource was invoked."); throw new RuntimeException("Not yet implemented"); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/0000775000175000017500000000000011757206350030531 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub1/0000775000175000017500000000000011757206352031405 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub1/Blocker.java0000664000175000017500000000521711757206350033634 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect4.sub1; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Status; /** * Filter that blocks specific IP addresses. */ public class Blocker extends org.restlet.routing.Filter { /** The set of blocked IP addresses. */ private final Set blockedAddresses; /** * Constructor. * * @param context * The parent context. */ public Blocker(Context context) { super(context); this.blockedAddresses = new CopyOnWriteArraySet(); } /** * Pre-processing method testing if the client IP address is in the set of * blocked addresses. */ @Override protected int beforeHandle(Request request, Response response) { int result = STOP; if (getBlockedAddresses() .contains(request.getClientInfo().getAddress())) { response.setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Your IP address was blocked"); } else { result = CONTINUE; } return result; } /** * Returns the modifiable set of blocked IP addresses. * * @return The modifiable set of blocked IP addresses. */ public Set getBlockedAddresses() { return blockedAddresses; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub1/Tracer.java0000664000175000017500000000423711757206352033476 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect4.sub1; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; /** * Restlet that returns common request properties to the client. */ public class Tracer extends Restlet { public Tracer(Context context) { super(context); } @Override public void handle(Request request, Response response) { String entity = "Method : " + request.getMethod() + "\nResource URI : " + request.getResourceRef() + "\nIP address : " + request.getClientInfo().getAddress() + "\nAgent name : " + request.getClientInfo().getAgentName() + "\nAgent version: " + request.getClientInfo().getAgentVersion(); response.setEntity(entity, MediaType.TEXT_PLAIN); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub1/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub1/MailServerAp0000664000175000017500000000464611757206350033672 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect4.sub1; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; /** * Setting basic application properties */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Restlet to trace requests. */ @Override public Restlet createInboundRoot() { Blocker blocker = new Blocker(getContext()); blocker.getBlockedAddresses().add("127.0.0.1"); blocker.setNext(new Tracer(getContext())); return blocker; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub2/0000775000175000017500000000000011757206352031406 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub2/Blocker.java0000664000175000017500000000521711757206352033637 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect4.sub2; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Status; /** * Filter that blocks specific IP addresses. */ public class Blocker extends org.restlet.routing.Filter { /** The set of blocked IP addresses. */ private final Set blockedAddresses; /** * Constructor. * * @param context * The parent context. */ public Blocker(Context context) { super(context); this.blockedAddresses = new CopyOnWriteArraySet(); } /** * Pre-processing method testing if the client IP address is in the set of * blocked addresses. */ @Override protected int beforeHandle(Request request, Response response) { int result = STOP; if (getBlockedAddresses() .contains(request.getClientInfo().getAddress())) { response.setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Your IP address was blocked"); } else { result = CONTINUE; } return result; } /** * Returns the modifiable set of blocked IP addresses. * * @return The modifiable set of blocked IP addresses. */ public Set getBlockedAddresses() { return blockedAddresses; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub2/Tracer.java0000664000175000017500000000423711757206350033475 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect4.sub2; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; /** * Restlet that returns common request properties to the client. */ public class Tracer extends Restlet { public Tracer(Context context) { super(context); } @Override public void handle(Request request, Response response) { String entity = "Method : " + request.getMethod() + "\nResource URI : " + request.getResourceRef() + "\nIP address : " + request.getClientInfo().getAddress() + "\nAgent name : " + request.getClientInfo().getAgentName() + "\nAgent version: " + request.getClientInfo().getAgentVersion(); response.setEntity(entity, MediaType.TEXT_PLAIN); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch02/sect4/sub2/MailServerAp0000664000175000017500000000534111757206352033666 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch02.sect4.sub2; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Illustrating URI based routing. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Server mailServer = new Server(Protocol.HTTP, 8111); mailServer.setNext(new MailServerApplication()); mailServer.start(); } /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Restlet to trace requests. */ @Override public Restlet createInboundRoot() { Tracer tracer = new Tracer(getContext()); Blocker blocker = new Blocker(getContext()); blocker.getBlockedAddresses().add("127.0.0.1"); blocker.setNext(tracer); Router router = new Router(getContext()); router.attach("http://localhost:8111/", tracer); router.attach("http://localhost:8111/accounts/", tracer); router.attach("http://localhost:8111/accounts/{accountId}", blocker); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/0000775000175000017500000000000011757206350027513 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/0000775000175000017500000000000011757206352030351 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/client/0000775000175000017500000000000011757206352031627 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/client/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/client/MailClient.0000664000175000017500000000401611757206352033652 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.client; import org.restlet.resource.ClientResource; /** * Mail client. */ public class MailClient { /** * Mail client interacting with the RESTful mail server. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { System.out.println("\n1) Set-up the service client resource\n"); ClientResource service = new ClientResource("http://localhost:8111"); System.out.println("\n2) Describe the application\n"); System.out.println(service.options().getText()); System.out.println("\n3) Describe the accounts resource\n"); System.out.println(service.getChild("/accounts/").options().getText()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/0000775000175000017500000000000011757206352031641 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/AccountResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/AccountReso0000664000175000017500000000367311757206350034020 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * User account resource. */ public interface AccountResource { /** * Represents the account as a simple string with the owner name for now. * * @return The account representation. */ @Get public String represent(); /** * Stores the new value for the identified account. * * @param account * The identified account. */ @Put public void store(String account); /** * Deletes the identified account by setting its value to null. */ @Delete public void remove(); } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/ContactRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/ContactRepr0000664000175000017500000000432611757206350034013 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; public class ContactRepresentation { private String firstName; private String lastName; private String login; private String nickName; private String senderName; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getLogin() { return login; } public String getNickName() { return nickName; } public String getSenderName() { return senderName; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setLogin(String login) { this.login = login; } public void setNickName(String nickName) { this.nickName = nickName; } public void setSenderName(String senderName) { this.senderName = senderName; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/TagRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/TagRepresen0000664000175000017500000000247211757206350034006 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; public class TagRepresentation { } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/AccountsResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/AccountsRes0000664000175000017500000000355211757206352034022 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; import org.restlet.resource.Get; import org.restlet.resource.Post; /** * Collection resource containing user accounts. */ public interface AccountsResource { /** * Returns the list of accounts, each one on a separate line. * * @return The list of accounts. */ @Get public String represent(); /** * Add the given account to the list and returns its position as an * identifier. * * @param account * The account to add. * @return The account identifier. */ @Post public String add(String account); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/RootResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/RootResourc0000664000175000017500000000303511757206350034051 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; import org.restlet.resource.Get; /** * Root resource. */ public interface RootResource { /** * Represents the application root with a welcome message. * * @return The root representation. */ @Get public String represent(); } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/MailRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/MailReprese0000664000175000017500000000401511757206350033772 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; public class MailRepresentation { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/AccountRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/AccountRepr0000664000175000017500000000376511757206352034024 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; import java.util.List; public class AccountRepresentation { private List contactRefs; private List mailRefs; private List feedRefs; public AccountRepresentation() { } public List getContactRefs() { return contactRefs; } public List getFeedRefs() { return feedRefs; } public List getMailRefs() { return mailRefs; } public void setContactRefs(List contactRefs) { this.contactRefs = contactRefs; } public void setFeedRefs(List feedRefs) { this.feedRefs = feedRefs; } public void setMailRefs(List mailRefs) { this.mailRefs = mailRefs; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/FeedRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/common/FeedReprese0000664000175000017500000000247311757206352033763 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.common; public class FeedRepresentation { } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/0000775000175000017500000000000011757206352031657 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/AccountServ0000664000175000017500000000634011757206350034037 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.server; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountResource; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.WadlServerResource; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Implementation of a mail account resource. */ public class AccountServerResource extends WadlServerResource implements AccountResource { /** The account identifier. */ private int accountId; @Override protected RepresentationInfo describe(MethodInfo methodInfo, Class representationClass, Variant variant) { RepresentationInfo result = super.describe(methodInfo, representationClass, variant); result.setReference("account"); return result; } /** * Retrieve the account identifier based on the URI path variable * "accountId" declared in the URI template attached to the application * router. */ @Override protected void doInit() throws ResourceException { String accountIdAttribute = (String) getRequestAttributes().get( "accountId"); if (accountIdAttribute != null) { this.accountId = Integer.parseInt(accountIdAttribute); setName("Resource for mail account \"" + this.accountId + "\""); setDescription("The resource describing the mail account number \"" + this.accountId + "\""); } else { setName("Mail account resource"); setDescription("The resource describing a mail account"); } } public void remove() { AccountsServerResource.getAccounts().remove(this.accountId); } public String represent() { return AccountsServerResource.getAccounts().get(this.accountId); } public void store(String account) { AccountsServerResource.getAccounts().set(this.accountId, account); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/MailServerA0000664000175000017500000000425711757206350033762 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.server; import org.restlet.Restlet; import org.restlet.ext.wadl.WadlApplication; import org.restlet.routing.Router; /** * The reusable mail server application. */ public class MailServerApplication extends WadlApplication { /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server application"); setDescription("Example application for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/", RootServerResource.class); router.attach("/accounts/", AccountsServerResource.class); router.attach("/accounts/{accountId}", AccountServerResource.class); return router; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/MailServerComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/MailServerC0000664000175000017500000000572211757206352033764 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.server; import org.restlet.Component; import org.restlet.Server; import org.restlet.data.Protocol; /** * RESTful component containing the mail server application. */ public class MailServerComponent extends Component { /** * Launches the mail server component. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { new MailServerComponent().start(); } /** * Constructor. * * @throws Exception */ public MailServerComponent() throws Exception { // Set basic properties setName("RESTful Mail Server component"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Add a CLAP client connector getClients().add(Protocol.CLAP); // Adds a HTTP server connector Server server = getServers().add(Protocol.HTTP, 8111); server.getContext().getParameters().set("tracing", "true"); // Configure the default virtual host // getDefaultHost().setHostDomain("www.rmep.com|www.rmep.net|www.rmep.org"); // getDefaultHost().setServerAddress("1.2.3.10|1.2.3.20"); // getDefaultHost().setServerPort("80"); // Attach the application to the default virtual host getDefaultHost().attachDefault(new MailServerApplication()); // Configure the log service getLogService().setLoggerName("MailServer.AccessLog"); getLogService() .setLogPropertiesRef( "clap://system/org/restlet/example/book/restlet/ch04/sec3/server/log.properties"); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/AccountsSer0000664000175000017500000000726411757206350034042 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.server; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.data.MediaType; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountsResource; import org.restlet.ext.wadl.ApplicationInfo; import org.restlet.ext.wadl.DocumentationInfo; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.WadlServerResource; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Implementation of the resource containing the list of mail accounts. */ public class AccountsServerResource extends WadlServerResource implements AccountsResource { /** Static list of accounts stored in memory. */ private static final List accounts = new CopyOnWriteArrayList(); @Override protected void describe(ApplicationInfo applicationInfo) { super.describe(applicationInfo); RepresentationInfo rep = new RepresentationInfo(MediaType.TEXT_PLAIN); rep.setIdentifier("account"); applicationInfo.getRepresentations().add(rep); DocumentationInfo doc = new DocumentationInfo(); doc.setTitle("Account"); doc.setTextContent("Simple string containing the account ID"); rep.getDocumentations().add(doc); } @Override protected RepresentationInfo describe(MethodInfo methodInfo, Class representationClass, Variant variant) { RepresentationInfo result = super.describe(methodInfo, representationClass, variant); result.setReference("account"); return result; } @Override protected void doInit() throws ResourceException { setName("Mail accounts resource"); setDescription("The resource containing the list of mail accounts"); } /** * Returns the static list of accounts stored in memory. * * @return The static list of accounts. */ public static List getAccounts() { return accounts; } public String represent() { StringBuilder result = new StringBuilder(); for (String account : getAccounts()) { result.append((account == null) ? "" : account).append('\n'); } return result.toString(); } public String add(String account) { getAccounts().add(account); return Integer.toString(getAccounts().indexOf(account)); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch06/sec2/server/RootServerR0000664000175000017500000000530411757206350034036 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch06.sec2.server; import org.restlet.data.MediaType; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.RootResource; import org.restlet.ext.wadl.DocumentationInfo; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.WadlServerResource; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; /** * Root resource implementation. */ public class RootServerResource extends WadlServerResource implements RootResource { @Override protected RepresentationInfo describe(MethodInfo methodInfo, Class representationClass, Variant variant) { RepresentationInfo result = super.describe(methodInfo, representationClass, variant); result.setMediaType(MediaType.TEXT_PLAIN); result.setIdentifier("root"); DocumentationInfo doc = new DocumentationInfo(); doc.setTitle("Mail application"); doc.setTextContent("Simple string welcoming the user to the mail application"); result.getDocumentations().add(doc); return result; } @Override protected void doInit() throws ResourceException { setAutoDescribing(false); setName("Root resource"); setDescription("The root resource of the mail server application"); } public String represent() { return "Welcome to the " + getApplication().getName() + " !"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/0000775000175000017500000000000011757206350027511 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/0000775000175000017500000000000011757206352030351 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/mail123.html0000664000175000017500000000064011757206352032407 0ustar jamespagejamespage Example mail
    Status received
    Subject Message to self
    Content Doh!
    Account Link
    restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/0000775000175000017500000000000011757206352031223 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/MailServerRes0000664000175000017500000000526111757206350033673 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub1; import java.util.HashMap; import java.util.Map; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages FreeMarker template engine. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() { // Create the mail bean Mail mail = new Mail(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Prepare the data model Map dataModel = new HashMap(); dataModel.put("mail", mail); // Load the FreeMarker template Representation mailFtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.ftl").get(); // Wraps the bean with a FreeMarker representation return new TemplateRepresentation(mailFtl, dataModel, MediaType.TEXT_HTML); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/MailClient.ja0000664000175000017500000000324711757206352033566 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub1; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); mailClient.get().write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/Mail.ftl0000664000175000017500000000063011757206352032613 0ustar jamespagejamespage Example mail
    Status ${mail.status}
    Subject ${mail.subject}
    Content ${mail.content}
    Account Link
    ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/MailServerApp0000664000175000017500000000455211757206350033664 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub1; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using FreeMarker extension. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getClients().add(Protocol.CLAP); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub1/Mail.java0000664000175000017500000000404611757206350032752 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub1; /** * The mail representation bean. */ public class Mail { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/0000775000175000017500000000000011757206352031224 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/MailServerRes0000664000175000017500000000527211757206350033676 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub2; import java.util.HashMap; import java.util.Map; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.velocity.TemplateRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages Velocity template engine. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() throws Exception { // Create the mail bean Mail mail = new Mail(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Prepare the data model Map dataModel = new HashMap(); dataModel.put("mail", mail); // Load the Velocity template Representation mailVtl = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.vtl").get(); // Wraps the bean with a Velocity representation return new TemplateRepresentation(mailVtl, dataModel, MediaType.TEXT_HTML); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/MailClient.ja0000664000175000017500000000324711757206350033565 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub2; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); mailClient.get().write(System.out); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/MailServerApp0000664000175000017500000000455011757206352033665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using Velocity extension. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getClients().add(Protocol.CLAP); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/Mail.vtl0000664000175000017500000000062011757206352032633 0ustar jamespagejamespage Example mail
    Status $mail.status
    Subject $mail.subject
    Content $mail.content
    Account Link
    restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/Mail.java0000664000175000017500000000404611757206350032753 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec4.sub2; /** * The mail representation bean. */ public class Mail { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/0000775000175000017500000000000011757206352030347 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/mail123.xml0000664000175000017500000000027511757206352032245 0ustar jamespagejamespage received Message to self Doh! http://www.rmep.org/accounts/chunkylover53/ restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub3/0000775000175000017500000000000011757206352031223 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub3/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub3/MailServerRes0000664000175000017500000001127511757206352033677 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub3; import java.io.IOException; import org.restlet.data.Reference; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages the SAX API. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() { // Create a new SAX representation SaxRepresentation result = new SaxRepresentation() { public void write(org.restlet.ext.xml.XmlWriter writer) throws IOException { try { // Start document writer.startDocument(); // Append the root node writer.startElement("mail"); // Append the child nodes and set their text content writer.startElement("status"); writer.characters("received"); writer.endElement("status"); writer.startElement("subject"); writer.characters("Message to self"); writer.endElement("subject"); writer.startElement("content"); writer.characters("Doh!"); writer.endElement("content"); writer.startElement("accountRef"); writer.characters(new Reference(getReference(), "..") .getTargetRef().toString()); writer.endElement("accountRef"); // End the root node writer.endElement("mail"); // End the document writer.endDocument(); } catch (SAXException e) { throw new IOException(e.getMessage()); } }; }; result.setNamespaceAware(true); return result; } @Put public void store(SaxRepresentation mailRep) throws IOException { mailRep.parse(new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // Output the XML element names if ("status".equals(localName)) { System.out.print("Status: "); } else if ("subject".equals(localName)) { System.out.print("Subject: "); } else if ("content".equals(localName)) { System.out.print("Content: "); } else if ("accountRef".equals(localName)) { System.out.print("Account URI: "); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { // Output the XML element values System.out.print(new String(ch, start, length)); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // Output a new line System.out.println(); } }); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub3/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub3/MailClient.ja0000664000175000017500000000342711757206352033566 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub3; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub3/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub3/MailServerApp0000664000175000017500000000445511757206350033666 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub3; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using the SAX API. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub5/0000775000175000017500000000000011757206350031223 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub5/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub5/MailServerRes0000664000175000017500000000745711757206350033706 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub5; import java.io.IOException; import org.restlet.data.Reference; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages XML namespaces. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() throws IOException { // Create a new DOM representation DomRepresentation result = new DomRepresentation(); result.setIndenting(true); // XML namespace configuration result.setNamespaceAware(true); // Populate the DOM document Document doc = result.getDocument(); Node mailElt = doc.createElementNS( "http://www.rmep.org/namespaces/1.0", "mail"); doc.appendChild(mailElt); Node statusElt = doc.createElement("status"); statusElt.setTextContent("received"); mailElt.appendChild(statusElt); Node subjectElt = doc.createElement("subject"); subjectElt.setTextContent("Message to self"); mailElt.appendChild(subjectElt); Node contentElt = doc.createElement("content"); contentElt.setTextContent("Doh!"); mailElt.appendChild(contentElt); Node accountRefElt = doc.createElement("accountRef"); accountRefElt.setTextContent(new Reference(getReference(), "..") .getTargetRef().toString()); mailElt.appendChild(accountRefElt); return result; } @Put public void store(DomRepresentation mailRep) { // XML namespace configuration String rmepNs = "http://www.rmep.org/namespaces/1.0"; mailRep.setNamespaceAware(true); mailRep.getNamespaces().put("", rmepNs); mailRep.getNamespaces().put("rmep", rmepNs); // Retrieve the XML element using XPath expressions String status = mailRep.getText("/:mail/:status"); String subject = mailRep.getText("/rmep:mail/:subject"); String content = mailRep.getText("/rmep:mail/rmep:content"); String accountRef = mailRep.getText("/:mail/rmep:accountRef"); // Output the XML element values System.out.println("Status: " + status); System.out.println("Subject: " + subject); System.out.println("Content: " + content); System.out.println("Account URI: " + accountRef); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub5/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub5/MailClient.ja0000664000175000017500000000342711757206350033566 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub5; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub5/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub5/MailServerApp0000664000175000017500000000450111757206350033660 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub5; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using XML namespaces. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach( "/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/0000775000175000017500000000000011757206352031227 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/MailServerRes0000664000175000017500000000742611757206350033704 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub7; import java.io.IOException; import javax.xml.transform.OutputKeys; import org.restlet.data.LocalReference; import org.restlet.data.Reference; import org.restlet.ext.xml.DomRepresentation; import org.restlet.ext.xml.TransformRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages XSLT transformation. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() throws IOException { // Create a new DOM representation DomRepresentation rmepMail = new DomRepresentation(); rmepMail.setIndenting(true); // Populate the DOM document Document doc = rmepMail.getDocument(); Node mailElt = doc.createElement("mail"); doc.appendChild(mailElt); Node statusElt = doc.createElement("status"); statusElt.setTextContent("received"); mailElt.appendChild(statusElt); Node subjectElt = doc.createElement("subject"); subjectElt.setTextContent("Message to self"); mailElt.appendChild(subjectElt); Node contentElt = doc.createElement("content"); contentElt.setTextContent("Doh!"); mailElt.appendChild(contentElt); Node accountRefElt = doc.createElement("accountRef"); accountRefElt.setTextContent(new Reference(getReference(), "..") .getTargetRef().toString()); mailElt.appendChild(accountRefElt); // Transform to another XML format using XSLT Representation transformSheet = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.xslt").get(); TransformRepresentation result = new TransformRepresentation(rmepMail, transformSheet); result.getOutputProperties().put(OutputKeys.INDENT, "yes"); return result; } @Put public void store(DomRepresentation mailRep) { // Retrieve the XML element using XPath expressions String subject = mailRep.getText("/email/head/subject"); String content = mailRep.getText("/email/body"); // Output the XML element values System.out.println("Subject: " + subject); System.out.println("Content: " + content); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/MailClient.ja0000664000175000017500000000342711757206352033572 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub7; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/MailServerApp0000664000175000017500000000455111757206350033667 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub7; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using XSLT transformation. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getClients().add(Protocol.CLAP); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub7/Mail.xslt0000664000175000017500000000075711757206352033036 0ustar jamespagejamespage chunkylover53@rmep.org test@domain.com restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/0000775000175000017500000000000011757206352031230 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/MailServerRes0000664000175000017500000000545311757206350033703 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub8; import java.io.IOException; import org.restlet.data.Reference; import org.restlet.ext.jaxb.JaxbRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages JAXB extension. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() { // Create the mail bean Mail mail = new Mail(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Wraps the bean with a JAXB representation JaxbRepresentation result = new JaxbRepresentation(mail); result.setFormattedOutput(true); return result; } @Put public void store(Representation rep) throws IOException { // Parse XML representation to get the mail bean JaxbRepresentation mailRep = new JaxbRepresentation(rep, Mail.class); Mail mail = mailRep.getObject(); // Output the XML element values System.out.println("Status: " + mail.getStatus()); System.out.println("Subject: " + mail.getSubject()); System.out.println("Content: " + mail.getContent()); System.out.println("Account URI: " + mail.getAccountRef()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/MailClient.ja0000664000175000017500000000342711757206350033571 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub8; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/MailServerApp0000664000175000017500000000450111757206352033665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub8; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using JAXB extension. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach( "/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/ObjectFactory.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/ObjectFactory0000664000175000017500000000444211757206350033713 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub8; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.restlet.example.book.restlet.ch05.sec2.sub8 package. *

    An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.restlet.example.book.restlet.ch05.sec2.sub8 * */ public ObjectFactory() { } /** * Create an instance of {@link Mail } * */ public Mail createMail() { return new Mail(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/Mail.xsd0000664000175000017500000000107211757206352032632 0ustar jamespagejamespage restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub8/Mail.java0000664000175000017500000001136211757206350032756 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub8; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** *

    Java class for anonymous complex type. * *

    The following schema fragment specifies the expected content contained within this class. * *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *         <element name="subject" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *         <element name="content" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *         <element name="accountRef" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     * 
    * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "status", "subject", "content", "accountRef" }) @XmlRootElement(name = "mail", namespace = "http://www.rmep.org/namespaces/1.0") public class Mail { @XmlElement(namespace = "http://www.rmep.org/namespaces/1.0", required = true) protected String status; @XmlElement(namespace = "http://www.rmep.org/namespaces/1.0", required = true) protected String subject; @XmlElement(namespace = "http://www.rmep.org/namespaces/1.0", required = true) protected String content; @XmlElement(namespace = "http://www.rmep.org/namespaces/1.0", required = true) protected String accountRef; /** * Gets the value of the status property. * * @return * possible object is * {@link String } * */ public String getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link String } * */ public void setStatus(String value) { this.status = value; } /** * Gets the value of the subject property. * * @return * possible object is * {@link String } * */ public String getSubject() { return subject; } /** * Sets the value of the subject property. * * @param value * allowed object is * {@link String } * */ public void setSubject(String value) { this.subject = value; } /** * Gets the value of the content property. * * @return * possible object is * {@link String } * */ public String getContent() { return content; } /** * Sets the value of the content property. * * @param value * allowed object is * {@link String } * */ public void setContent(String value) { this.content = value; } /** * Gets the value of the accountRef property. * * @return * possible object is * {@link String } * */ public String getAccountRef() { return accountRef; } /** * Sets the value of the accountRef property. * * @param value * allowed object is * {@link String } * */ public void setAccountRef(String value) { this.accountRef = value; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub4/0000775000175000017500000000000011757206352031224 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub4/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub4/MailServerRes0000664000175000017500000000705111757206352033675 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub4; import java.io.IOException; import org.restlet.data.Reference; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages the XPath language. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() throws IOException { // Create a new DOM representation DomRepresentation result = new DomRepresentation(); // Ensure pretty printing result.setIndenting(true); // Retrieve the DOM document to populate Document doc = result.getDocument(); // Append the root node Node mailElt = doc.createElement("mail"); doc.appendChild(mailElt); // Append the child nodes and set their text content Node statusElt = doc.createElement("status"); statusElt.setTextContent("received"); mailElt.appendChild(statusElt); Node subjectElt = doc.createElement("subject"); subjectElt.setTextContent("Message to self"); mailElt.appendChild(subjectElt); Node contentElt = doc.createElement("content"); contentElt.setTextContent("Doh!"); mailElt.appendChild(contentElt); Node accountRefElt = doc.createElement("accountRef"); accountRefElt.setTextContent(new Reference(getReference(), "..") .getTargetRef().toString()); mailElt.appendChild(accountRefElt); return result; } @Put public void store(DomRepresentation mailRep) { // Retrieve the XML element using XPath expressions String status = mailRep.getText("/mail/status"); String subject = mailRep.getText("/mail/subject"); String content = mailRep.getText("/mail/content"); String accountRef = mailRep.getText("/mail/accountRef"); // Output the XML element values System.out.println("Status: " + status); System.out.println("Subject: " + subject); System.out.println("Content: " + content); System.out.println("Account URI: " + accountRef); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub4/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub4/MailClient.ja0000664000175000017500000000342711757206350033565 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub4; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub4/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub4/MailServerApp0000664000175000017500000000446311757206352033670 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub4; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using XPath expressions. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/0000775000175000017500000000000011757206352031226 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/MailServerRes0000664000175000017500000001156711757206350033704 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub6; import java.io.IOException; import org.restlet.data.LocalReference; import org.restlet.data.Reference; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages XML Schema validation. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() throws IOException { // Create a new DOM representation DomRepresentation result = new DomRepresentation(); result.setIndenting(true); // XML namespace configuration result.setNamespaceAware(true); // Populate the DOM document Document doc = result.getDocument(); Node mailElt = doc.createElementNS( "http://www.rmep.org/namespaces/1.0", "mail"); doc.appendChild(mailElt); Node statusElt = doc.createElement("status"); statusElt.setTextContent("received"); mailElt.appendChild(statusElt); Node subjectElt = doc.createElement("subject"); subjectElt.setTextContent("Message to self"); mailElt.appendChild(subjectElt); Node contentElt = doc.createElement("content"); contentElt.setTextContent("Doh!"); mailElt.appendChild(contentElt); Node accountRefElt = doc.createElement("accountRef"); accountRefElt.setTextContent(new Reference(getReference(), "..") .getTargetRef().toString()); mailElt.appendChild(accountRefElt); return result; } @Put public void store(DomRepresentation mailRep) throws IOException { // Configure the XML Schema used for validation Representation mailXsd = new ClientResource( LocalReference.createClapReference(getClass().getPackage()) + "/Mail.xsd").get(); mailRep.setSchema(mailXsd); mailRep.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXException { throw new ResourceException(exception); } public void fatalError(SAXParseException exception) throws SAXException { throw new ResourceException(exception); } public void warning(SAXParseException exception) throws SAXException { throw new ResourceException(exception); } }); // XML namespace configuration String rmepNs = "http://www.rmep.org/namespaces/1.0"; mailRep.setNamespaceAware(true); mailRep.getNamespaces().put("", rmepNs); mailRep.getNamespaces().put("rmep", rmepNs); // Retrieve the XML element using XPath expressions String status = mailRep.getText("/:mail/:status"); String subject = mailRep.getText("/rmep:mail/:subject"); String content = mailRep.getText("/rmep:mail/rmep:content"); String accountRef = mailRep.getText("/:mail/rmep:accountRef"); // Output the XML element values System.out.println("Status: " + status); System.out.println("Subject: " + subject); System.out.println("Content: " + content); System.out.println("Account URI: " + accountRef); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/MailClient.ja0000664000175000017500000000342711757206350033567 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub6; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/MailServerApp0000664000175000017500000000455311757206352033672 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub6; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using XML schema validation. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getClients().add(Protocol.CLAP); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub6/Mail.xsd0000664000175000017500000000101311757206352032623 0ustar jamespagejamespage restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub2/0000775000175000017500000000000011757206352031222 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub2/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub2/MailServerRes0000664000175000017500000000775111757206350033700 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub2; import java.io.IOException; import org.restlet.data.Reference; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages the DOM API. */ public class MailServerResource extends ServerResource { @Get public Representation toXml() throws IOException { // Create an empty DOM representation DomRepresentation result = new DomRepresentation(); // Ensure pretty printing result.setIndenting(true); // Retrieve the DOM document to populate Document doc = result.getDocument(); // Append the root node Node mailElt = doc.createElement("mail"); doc.appendChild(mailElt); // Append the child nodes and set their text content Node statusElt = doc.createElement("status"); statusElt.setTextContent("received"); mailElt.appendChild(statusElt); Node subjectElt = doc.createElement("subject"); subjectElt.setTextContent("Message to self"); mailElt.appendChild(subjectElt); Node contentElt = doc.createElement("content"); contentElt.setTextContent("Doh!"); mailElt.appendChild(contentElt); Node accountRefElt = doc.createElement("accountRef"); // Computes the parent URI including slash accountRefElt.setTextContent(new Reference(getReference(), "..") .getTargetRef().toString()); mailElt.appendChild(accountRefElt); return result; } @Put public void store(DomRepresentation mailRep) throws IOException { // Parses and normalizes the DOM document Document doc = mailRep.getDocument(); Element mailElt = doc.getDocumentElement(); Element statusElt = (Element) mailElt.getElementsByTagName("status") .item(0); Element subjectElt = (Element) mailElt.getElementsByTagName("subject") .item(0); Element contentElt = (Element) mailElt.getElementsByTagName("content") .item(0); Element accountRefElt = (Element) mailElt.getElementsByTagName( "accountRef").item(0); // Output the XML element values System.out.println("Status: " + statusElt.getTextContent()); System.out.println("Subject: " + subjectElt.getTextContent()); System.out.println("Content: " + contentElt.getTextContent()); System.out.println("Account URI: " + accountRefElt.getTextContent()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub2/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub2/MailClient.ja0000664000175000017500000000342711757206350033563 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub2; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec2/sub2/MailServerApp0000664000175000017500000000445511757206352033667 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec2.sub2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using the DOM API. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/0000775000175000017500000000000011757206352030350 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub1/0000775000175000017500000000000011757206352031222 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub1/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub1/MailServerRes0000664000175000017500000000537211757206350033675 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec3.sub1; import org.json.JSONException; import org.json.JSONObject; import org.restlet.data.Reference; import org.restlet.ext.json.JsonRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages JSON.org extension. */ public class MailServerResource extends ServerResource { @Get public Representation toJson() throws JSONException { // Create a JSON object structure similar to a map JSONObject mailElt = new JSONObject(); mailElt.put("status", "received"); mailElt.put("subject", "Message to self"); mailElt.put("content", "Doh!"); mailElt.put("accountRef", new Reference(getReference(), "..") .getTargetRef().toString()); return new JsonRepresentation(mailElt); } @Put public void store(JsonRepresentation mailRep) throws JSONException { // Parse the JSON representation to get the mail properties JSONObject mailElt = mailRep.getJsonObject(); // Output the JSON element values System.out.println("Status: " + mailElt.getString("status")); System.out.println("Subject: " + mailElt.getString("subject")); System.out.println("Content: " + mailElt.getString("content")); System.out.println("Account URI: " + mailElt.getString("accountRef")); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub1/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub1/MailClient.ja0000664000175000017500000000342711757206350033563 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec3.sub1; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub1/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub1/MailServerApp0000664000175000017500000000446411757206352033667 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec3.sub1; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using JSON.org extension. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/mail123.json0000664000175000017500000000027511757206352032417 0ustar jamespagejamespage received Message to self Doh! http://www.rmep.org/accounts/chunkylover53/ restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/0000775000175000017500000000000011757206350031221 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/MailServerRes0000664000175000017500000000535511757206350033677 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec3.sub2; import java.io.IOException; import org.restlet.data.Reference; import org.restlet.ext.jackson.JacksonRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages Jackson extension. */ public class MailServerResource extends ServerResource { @Get public Representation toJson() { // Create the mail bean Mail mail = new Mail(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); // Wraps the bean with a Jackson representation return new JacksonRepresentation(mail); } @Put public void store(Representation rep) throws IOException { // Parse the JSON representation to get the mail bean JacksonRepresentation mailRep = new JacksonRepresentation( rep, Mail.class); Mail mail = mailRep.getObject(); // Output the JSON element values System.out.println("Status: " + mail.getStatus()); System.out.println("Subject: " + mail.getSubject()); System.out.println("Content: " + mail.getContent()); System.out.println("Account URI: " + mail.getAccountRef()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/MailClient.ja0000664000175000017500000000342711757206350033564 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec3.sub2; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient.get(); mailClient.put(mailRepresentation); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/MailServerApp0000664000175000017500000000446311757206350033665 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec3.sub2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Simple test application serving mail resources using Jackson extension. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec3/sub2/Mail.java0000664000175000017500000000404611757206350032752 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec3.sub2; /** * The mail representation bean. */ public class Mail { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/0000775000175000017500000000000011757206350030351 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/client/0000775000175000017500000000000011757206350031627 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/client/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/client/MailClient.0000664000175000017500000000727711757206350033666 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.client; import org.restlet.Client; import org.restlet.Context; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountResource; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountsResource; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.RootResource; import org.restlet.resource.ClientResource; /** * Mail client. */ public class MailClient { /** * Mail client interacting with the RESTful mail server. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { System.out.println("\n1) Set-up the service client resource\n"); Client client = new Client(new Context(), Protocol.HTTP); ClientResource service = new ClientResource("http://localhost:8111"); service.setNext(client); System.out.println("\n2) Display the root resource\n"); RootResource mailRoot = service.getChild("/", RootResource.class); System.out.println(mailRoot.represent()); System.out.println("\n3) Display the initial list of accounts\n"); AccountsResource mailAccounts = service.getChild("/accounts/", AccountsResource.class); String list = mailAccounts.represent(); System.out.println(list == null ? "\n" : list); System.out.println("4) Adds new accounts\n"); mailAccounts.add("Tim Berners-Lee"); mailAccounts.add("Roy Fielding"); mailAccounts.add("Mark Baker"); System.out.println("Three accounts added !"); System.out.println("\n5) Display the updated list of accounts\n"); System.out.println(mailAccounts.represent()); System.out.println("6) Display the second account\n"); AccountResource mailAccount = service.getChild("/accounts/2", AccountResource.class); System.out.println(mailAccount.represent()); System.out .println("\n7) Update the individual account and display it again\n"); mailAccount.store("Roy T. Fielding"); System.out.println(mailAccount.represent()); System.out .println("\n8) Delete the first account and display the list again\n"); mailAccount = service.getChild("/accounts/1", AccountResource.class); mailAccount.remove(); System.out.println(mailAccounts.represent()); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/client/MailClientTestCase.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/client/MailClientT0000664000175000017500000000452211757206350033722 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.client; import junit.framework.TestCase; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.example.book.restlet.ch03.sec3.server.MailServerComponent; /** * Mail client JUnit test case. */ public class MailClientTestCase extends TestCase { /** * Unit test for virtual hosts. * * @throws Exception */ public void testVirtualHost() throws Exception { // Instantiate our Restlet component MailServerComponent component = new MailServerComponent(); // Prepare a mock HTTP call Request request = new Request(); request.setMethod(Method.GET); request.setResourceRef("http://www.rmep.org/accounts/"); request.setHostRef("http://www.rmep.org"); Response response = new Response(request); response.getServerInfo().setAddress("1.2.3.10"); response.getServerInfo().setPort(80); component.handle(request, response); // Test if response was successful assertTrue(response.getStatus().isSuccess()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/0000775000175000017500000000000011757206352031643 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/AccountResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/AccountReso0000664000175000017500000000367311757206350034022 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * User account resource. */ public interface AccountResource { /** * Represents the account as a simple string with the owner name for now. * * @return The account representation. */ @Get public String represent(); /** * Stores the new value for the identified account. * * @param account * The identified account. */ @Put public void store(String account); /** * Deletes the identified account by setting its value to null. */ @Delete public void remove(); } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/ContactRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/ContactRepr0000664000175000017500000000432611757206350034015 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; public class ContactRepresentation { private String firstName; private String lastName; private String login; private String nickName; private String senderName; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getLogin() { return login; } public String getNickName() { return nickName; } public String getSenderName() { return senderName; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setLogin(String login) { this.login = login; } public void setNickName(String nickName) { this.nickName = nickName; } public void setSenderName(String senderName) { this.senderName = senderName; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/TagRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/TagRepresen0000664000175000017500000000247211757206350034010 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; public class TagRepresentation { } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/AccountsResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/AccountsRes0000664000175000017500000000355211757206352034024 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; import org.restlet.resource.Get; import org.restlet.resource.Post; /** * Collection resource containing user accounts. */ public interface AccountsResource { /** * Returns the list of accounts, each one on a separate line. * * @return The list of accounts. */ @Get public String represent(); /** * Add the given account to the list and returns its position as an * identifier. * * @param account * The account to add. * @return The account identifier. */ @Post public String add(String account); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/RootResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/RootResourc0000664000175000017500000000303511757206350034053 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; import org.restlet.resource.Get; /** * Root resource. */ public interface RootResource { /** * Represents the application root with a welcome message. * * @return The root representation. */ @Get public String represent(); } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/MailRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/MailReprese0000664000175000017500000000401511757206352033776 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; public class MailRepresentation { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/AccountRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/AccountRepr0000664000175000017500000000376511757206352034026 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; import java.util.List; public class AccountRepresentation { private List contactRefs; private List mailRefs; private List feedRefs; public AccountRepresentation() { } public List getContactRefs() { return contactRefs; } public List getFeedRefs() { return feedRefs; } public List getMailRefs() { return mailRefs; } public void setContactRefs(List contactRefs) { this.contactRefs = contactRefs; } public void setFeedRefs(List feedRefs) { this.feedRefs = feedRefs; } public void setMailRefs(List mailRefs) { this.mailRefs = mailRefs; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/FeedRepresentation.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/common/FeedReprese0000664000175000017500000000247311757206350033763 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.common; public class FeedRepresentation { } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/0000775000175000017500000000000011757206352031661 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/AccountServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/AccountServ0000664000175000017500000000477011757206350034046 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.server; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountResource; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Implementation of a mail account resource. */ public class AccountServerResource extends ServerResource implements AccountResource { /** The account identifier. */ private int accountId; /** * Retrieve the account identifier based on the URI path variable * "accountId" declared in the URI template attached to the application * router. */ @Override protected void doInit() throws ResourceException { String accountIdAttribute = (String) getRequestAttributes().get( "accountId"); if (accountIdAttribute != null) { this.accountId = Integer.parseInt((String) getRequestAttributes() .get("accountId")); } } public String represent() { return AccountsServerResource.getAccounts().get(this.accountId); } public void store(String account) { AccountsServerResource.getAccounts().set(this.accountId, account); } public void remove() { AccountsServerResource.getAccounts().remove(this.accountId); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/log.propertiesrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/log.propert0000664000175000017500000001142111757206352034056 0ustar jamespagejamespage # ========================== # Restlet logging properties # ========================== # ------------------ # General properties # ------------------ # This defines a whitespace separated list of class names for handler classes to load and register as handlers on # the root Logger (the Logger named ""). Each class name must be for a Handler class which has a default constructor. # Note that these Handlers may be created lazily, when they are first used. handlers=java.util.logging.FileHandler java.util.logging.ConsoleHandler # ------------------ # Loggers properties # ------------------ .level=INFO org.mortbay.level=WARNING org.restlet.level=ALL MailServer.AccessLog.handlers=org.restlet.engine.log.AccessLogFileHandler MailServer.AccessLog.useParentHandlers=false # ------------------------- # ConsoleHandler properties # ------------------------- # Specifies the default level for the Handler (defaults to Level.INFO). # java.util.logging.ConsoleHandler.level=ALL # Specifies the name of a Filter class to use (defaults to no Filter). # java.util.logging.ConsoleHandler.filter= # Specifies the name of a Formatter class to use (defaults to java.util.logging.SimpleFormatter). # java.util.logging.ConsoleHandler.formatter= # The name of the character set encoding to use (defaults to the default platform encoding). # java.util.logging.ConsoleHandler.encoding= # ---------------------- # FileHandler properties # ---------------------- # Specifies the default level for the Handler (defaults to Level.ALL). # java.util.logging.FileHandler.level=ALL # Specifies the name of a Filter class to use (defaults to no Filter). # java.util.logging.FileHandler.filter= # Specifies the name of a Formatter class to use (defaults to java.util.logging.XMLFormatter) java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter # The name of the character set encoding to use (defaults to the default platform encoding). # java.util.logging.FileHandler.encoding= # Specifies an approximate maximum amount to write (in bytes) to any one file. # If this is zero, then there is no limit. (Defaults to no limit). # java.util.logging.FileHandler.limit=1000000 # Specifies how many output files to cycle through (defaults to 1). java.util.logging.FileHandler.count=2 # Specifies a pattern for generating the output file name. (Defaults to "%h/java%u.log"). # A pattern consists of a string that includes the following special components that will be replaced at runtime: # "/" the local pathname separator # "%t" the system temporary directory # "%h" the value of the "user.home" system property # "%g" the generation number to distinguish rotated logs # "%u" a unique number to resolve conflicts # "%%" translates to a single percent sign "%" java.util.logging.FileHandler.pattern=MailServer.DebugLog-%u-%g.log # Specifies whether the FileHandler should append onto any existing files (defaults to false). # java.util.logging.FileHandler.append= # ------------------------------- # AccessLogFileHandler properties # ------------------------------- # Specifies the default level for the Handler (defaults to Level.ALL). # org.restlet.engine.log.AccessLogFileHandler.level=ALL # Specifies the name of a Filter class to use (defaults to no Filter). # org.restlet.engine.log.AccessLogFileHandler.filter= # Specifies the name of a Formatter class to use (defaults to java.util.logging.XMLFormatter) org.restlet.engine.log.AccessLogFileHandler.formatter=org.restlet.engine.log.DefaultAccessLogFormatter # The name of the character set encoding to use (defaults to the default platform encoding). # org.restlet.engine.log.AccessLogFileHandler.encoding= # Specifies an approximate maximum amount to write (in bytes) to any one file. # If this is zero, then there is no limit. (Defaults to no limit). # org.restlet.engine.log.AccessLogFileHandler.limit=1000000 # Specifies how many output files to cycle through (defaults to 1). org.restlet.engine.log.AccessLogFileHandler.count=2 # Specifies a pattern for generating the output file name. (Defaults to "%h/java%u.log"). # A pattern consists of a string that includes the following special components that will be replaced at runtime: # "/" the local pathname separator # "%t" the system temporary directory # "%h" the value of the "user.home" system property # "%g" the generation number to distinguish rotated logs # "%u" a unique number to resolve conflicts # "%%" translates to a single percent sign "%" org.restlet.engine.log.AccessLogFileHandler.pattern=MailServer.AccessLog-%u-%g.log # Specifies whether the AccessLogFileHandler should append onto any existing files (defaults to false). # org.restlet.engine.log.AccessLogFileHandler.append= ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/MailServerA0000664000175000017500000000423611757206350033761 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.server; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; /** * The reusable mail server application. */ public class MailServerApplication extends Application { /** * Constructor. */ public MailServerApplication() { setName("RESTful Mail Server application"); setDescription("Example application for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/", RootServerResource.class); router.attach("/accounts/", AccountsServerResource.class); router.attach("/accounts/{accountId}", AccountServerResource.class); return router; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/MailServerComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/MailServerC0000664000175000017500000000572211757206350033764 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.server; import org.restlet.Component; import org.restlet.Server; import org.restlet.data.Protocol; /** * RESTful component containing the mail server application. */ public class MailServerComponent extends Component { /** * Launches the mail server component. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { new MailServerComponent().start(); } /** * Constructor. * * @throws Exception */ public MailServerComponent() throws Exception { // Set basic properties setName("RESTful Mail Server component"); setDescription("Example for 'Restlet in Action' book"); setOwner("Restlet S.A.S."); setAuthor("The Restlet Team"); // Add a CLAP client connector getClients().add(Protocol.CLAP); // Adds a HTTP server connector Server server = getServers().add(Protocol.HTTP, 8111); server.getContext().getParameters().set("tracing", "true"); // Configure the default virtual host // getDefaultHost().setHostDomain("www.rmep.com|www.rmep.net|www.rmep.org"); // getDefaultHost().setServerAddress("1.2.3.10|1.2.3.20"); // getDefaultHost().setServerPort("80"); // Attach the application to the default virtual host getDefaultHost().attachDefault(new MailServerApplication()); // Configure the log service getLogService().setLoggerName("MailServer.AccessLog"); getLogService() .setLogPropertiesRef( "clap://system/org/restlet/example/book/restlet/ch04/sec3/server/log.properties"); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/AccountsServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/AccountsSer0000664000175000017500000000460211757206350034035 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.server; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.AccountsResource; import org.restlet.resource.ServerResource; /** * Implementation of the resource containing the list of mail accounts. */ public class AccountsServerResource extends ServerResource implements AccountsResource { /** Static list of accounts stored in memory. */ private static final List accounts = new CopyOnWriteArrayList(); /** * Returns the static list of accounts stored in memory. * * @return The static list of accounts. */ public static List getAccounts() { return accounts; } public String represent() { StringBuilder result = new StringBuilder(); for (String account : getAccounts()) { result.append((account == null) ? "" : account).append('\n'); } return result.toString(); } public String add(String account) { getAccounts().add(account); return Integer.toString(getAccounts().indexOf(account)); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/RootServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec6/server/RootServerR0000664000175000017500000000317211757206350034041 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec6.server; import org.restlet.example.book.restlet.ch02.sect5.sub5.common.RootResource; import org.restlet.resource.ServerResource; /** * Root resource implementation. */ public class RootServerResource extends ServerResource implements RootResource { public String represent() { return "Welcome to the " + getApplication().getName() + " !"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec1/0000775000175000017500000000000011757206350030344 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec1/AppendableTestCase.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec1/AppendableTestCase0000664000175000017500000000460411757206350033762 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec1; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import junit.framework.TestCase; import org.restlet.engine.io.BioUtils; import org.restlet.representation.AppendableRepresentation; /** * Test the appendable representation. */ public class AppendableTestCase extends TestCase { public void testAppendable() throws IOException { // Create the representation AppendableRepresentation ar = new AppendableRepresentation(); ar.append("abcd"); ar.append("1234"); // Get its content as text assertEquals("abcd1234", ar.getText()); // Append a new line character ar.append('\n'); // Write its content to the console's output stream ar.write(System.out); // Copy its content as an input stream to the console BioUtils.copy(ar.getStream(), System.out); // Write its content to the console's writer Writer writer = new OutputStreamWriter(System.out); ar.write(writer); // Copy its content as a reader to the console BioUtils.copy(ar.getReader(), writer); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/0000775000175000017500000000000011757206350030350 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub3/0000775000175000017500000000000011757206350031224 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub3/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub3/MailClient.ja0000664000175000017500000000373311757206350033567 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub3; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { ClientResource mailClient = new ClientResource( "http://localhost:8111/accounts/chunkylover53/mails/123"); Representation mailRepresentation = mailClient .get(MediaType.APPLICATION_XML); mailClient.put(mailRepresentation); mailRepresentation = mailClient.get(MediaType.APPLICATION_JSON); mailClient.put(mailRepresentation); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/0000775000175000017500000000000011757206352031227 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailServerRes0000664000175000017500000000420011757206352033671 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub4; import org.restlet.data.Reference; import org.restlet.resource.ServerResource; /** * Mail server resource implementing the {@link MailResource} interface. */ public class MailServerResource extends ServerResource implements MailResource { public Mail retrieve() { Mail mail = new Mail(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); return mail; } public void store(Mail mail) { System.out.println("Status: " + mail.getStatus()); System.out.println("Subject: " + mail.getSubject()); System.out.println("Content: " + mail.getContent()); System.out.println("Account URI: " + mail.getAccountRef()); System.out.println(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailClient.ja0000664000175000017500000000333511757206352033570 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub4; import org.restlet.resource.ClientResource; /** * Mail client retrieving a mail then storing it again on the same resource. */ public class MailClient { public static void main(String[] args) throws Exception { MailResource clientResource = ClientResource.create( "http://localhost:8111/accounts/chunkylover53/mails/123", MailResource.class); clientResource.store(clientResource.retrieve()); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailServerApp0000664000175000017500000000442211757206350033664 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub4; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Routing to annotated server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/MailResource.0000664000175000017500000000277111757206352033631 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub4; import org.restlet.resource.Get; import org.restlet.resource.Put; /** * Annotated mail resource interface */ public interface MailResource { @Get public Mail retrieve(); @Put public void store(Mail mail); } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub4/Mail.java0000664000175000017500000000404611757206350032756 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub4; /** * The mail representation bean. */ public class Mail { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub2/0000775000175000017500000000000011757206350031223 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub2/MailServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub2/MailServerRes0000664000175000017500000001017311757206350033673 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub2; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.ext.jackson.JacksonRepresentation; import org.restlet.ext.xstream.XstreamRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * Resource corresponding to a mail received or sent with the parent mail * account. Leverages Jackson extension. */ public class MailServerResource extends ServerResource { @Override protected void doInit() throws ResourceException { // Declares the two variants supported getVariants().add(new Variant(MediaType.APPLICATION_XML)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); } @Override protected Representation get(Variant variant) throws ResourceException { Representation result = null; // Create the mail bean Mail mail = new Mail(); mail.setStatus("received"); mail.setSubject("Message to self"); mail.setContent("Doh!"); mail.setAccountRef(new Reference(getReference(), "..").getTargetRef() .toString()); if (MediaType.APPLICATION_XML.isCompatible(variant.getMediaType())) { // Wraps the bean with an XStream representation result = new XstreamRepresentation(mail); } else if (MediaType.APPLICATION_JSON.isCompatible(variant .getMediaType())) { // Wraps the bean with a Jackson representation result = new JacksonRepresentation(mail); } return result; } @Override protected Representation put(Representation representation, Variant variant) throws ResourceException { Mail mail = null; if (MediaType.APPLICATION_XML.isCompatible(representation .getMediaType())) { // Parse the XML representation to get the mail bean mail = new XstreamRepresentation(representation).getObject(); System.out.println("XML representation received"); } else if (MediaType.APPLICATION_JSON.isCompatible(representation .getMediaType())) { // Parse the JSON representation to get the mail bean mail = new JacksonRepresentation(representation, Mail.class) .getObject(); System.out.println("JSON representation received"); } if (mail != null) { // Output the mail bean System.out.println("Status: " + mail.getStatus()); System.out.println("Subject: " + mail.getSubject()); System.out.println("Content: " + mail.getContent()); System.out.println("Account URI: " + mail.getAccountRef()); System.out.println(); } return null; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub2/MailServerApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub2/MailServerApp0000664000175000017500000000442211757206350033662 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Routing to annotated server resources. */ public class MailServerApplication extends Application { /** * Launches the application with an HTTP server. * * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Component mailServer = new Component(); mailServer.getServers().add(Protocol.HTTP, 8111); mailServer.getDefaultHost().attach(new MailServerApplication()); mailServer.start(); } /** * Creates a root Router to dispatch call to server resources. */ @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/accounts/{accountId}/mails/{mailId}", MailServerResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec5/sub2/Mail.java0000664000175000017500000000404611757206350032754 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch04.sec5.sub2; /** * The mail representation bean. */ public class Mail { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch08/0000775000175000017500000000000012001473213027500 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/0000775000175000017500000000000011757206352027514 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec4/0000775000175000017500000000000011757206352030352 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec4/ListHomeDirResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec4/ListHomeDirResourc0000664000175000017500000000566311757206350034033 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec4; import java.io.File; import java.io.FilenameFilter; import java.security.PrivilegedAction; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.ext.jaas.JaasUtils; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * */ public class ListHomeDirResource extends ServerResource { @Get("txt") public Representation echoPrincipals() throws ResourceException { PrivilegedAction action = new PrivilegedAction() { public StringBuilder run() { File dir = new File(System.getProperty("user.home")); String[] filenames = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith("."); } }); StringBuilder sb = new StringBuilder( "Files in the home directory: \n\n"); for (String filename : filenames) { sb.append(filename); sb.append("\n"); } return sb; } }; StringBuilder sb = JaasUtils.doAsPriviledged(getRequest() .getClientInfo(), action); Representation rep = new StringRepresentation(sb, MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8); return rep; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec4/SecurityManagerDemoApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec4/SecurityManagerDem0000664000175000017500000000424211757206352034027 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec4; import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.routing.Router; import org.restlet.security.ChallengeAuthenticator; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * */ public class SecurityManagerDemoApplication extends Application { public SecurityManagerDemoApplication(Context context) { super(context); } @Override public synchronized Restlet createInboundRoot() { ChallengeAuthenticator authenticator = new ChallengeAuthenticator( getContext(), ChallengeScheme.HTTP_BASIC, "Basic Test"); authenticator.setVerifier(getContext().getDefaultVerifier()); Router router = new Router(getContext()); router.attachDefault(ListHomeDirResource.class); authenticator.setNext(router); return authenticator; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec4/SecurityManagerDemoComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec4/SecurityManagerDem0000664000175000017500000000733011757206350034026 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec4; import org.restlet.Application; import org.restlet.Component; import org.restlet.Context; import org.restlet.data.Protocol; import org.restlet.security.Group; import org.restlet.security.MemoryRealm; import org.restlet.security.Role; import org.restlet.security.User; /** * Sample SAAS component with declared organizations. * * @author Jerome Louvel */ public class SecurityManagerDemoComponent extends Component { public SecurityManagerDemoComponent() { MemoryRealm realm = new MemoryRealm(); // Add users User stiger = new User("stiger", "pwd", "Scott", "Tiger", "scott.tiger@foobar.com"); realm.getUsers().add(stiger); User larmstrong = new User("larmstrong", "pwd", "Louis", "Armstrong", "la@foobar.com"); realm.getUsers().add(larmstrong); // Add groups Group employees = new Group("employees", "All FooBar employees"); employees.getMemberUsers().add(larmstrong); realm.getRootGroups().add(employees); Group contractors = new Group("contractors", "All FooBar contractors"); contractors.getMemberUsers().add(stiger); realm.getRootGroups().add(contractors); Group managers = new Group("managers", "All FooBar managers"); realm.getRootGroups().add(managers); Group directors = new Group("directors", "Top-level directors"); directors.getMemberUsers().add(larmstrong); managers.getMemberGroups().add(directors); Group developers = new Group("developers", "All FooBar developers"); realm.getRootGroups().add(developers); Group engineers = new Group("engineers", "All FooBar engineers"); engineers.getMemberUsers().add(stiger); developers.getMemberGroups().add(engineers); Context appContext = getContext().createChildContext(); Application app = new SecurityManagerDemoApplication(appContext); appContext.setDefaultEnroler(realm.getEnroler()); appContext.setDefaultVerifier(realm.getVerifier()); Role adminRole = new Role("admin", "Administrator"); realm.map(managers, adminRole); app.getRoles().add(adminRole); getDefaultHost().attachDefault(app); } public static void main(String[] args) throws Exception { SecurityManagerDemoComponent component = new SecurityManagerDemoComponent(); component.getServers().add(Protocol.HTTP, 8111); component.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/0000775000175000017500000000000011757206352030350 5ustar jamespagejamespage././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/BasicJaasAuthenticationApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/BasicJaasAuthentic0000664000175000017500000000656311757206352033772 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch05.EchoPrincipalsResource; import org.restlet.ext.jaas.JaasVerifier; import org.restlet.routing.Router; import org.restlet.security.ChallengeAuthenticator; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * * This is an example application that uses the JaasVerifier. A sample * JAAS configuration (using the LdapLoginModule) could be as follow: * *
     * BasicJaasAuthenticationApplication {
     *     com.sun.security.auth.module.LdapLoginModule REQUIRED
     *         userProvider="ldap://ldap.example.net/"
     *         authIdentity="uid={USERNAME},ou=people,dc=example,dc=net"
     *         useSSL="false"
     *         debug="true"
     *   };
     * 
    * * This configuration should be put in a text file (e.g. jaas.conf) and * passed to the JVM using this parameter: * *
     * -Djava.security.auth.login.config=jaas.conf
     * 
    */ public class BasicJaasAuthenticationApplication extends Application { @Override public synchronized Restlet createInboundRoot() { Router router = new Router(getContext()); router.attachDefault(EchoPrincipalsResource.class); ChallengeAuthenticator authenticator = new ChallengeAuthenticator( getContext(), ChallengeScheme.HTTP_BASIC, "Basic Test"); JaasVerifier verifier = new JaasVerifier( "BasicJaasAuthenticationApplication"); verifier .setUserPrincipalClassName("com.sun.security.auth.UserPrincipal"); authenticator.setVerifier(verifier); authenticator.setNext(router); return authenticator; } public static void main(String[] args) throws Exception { Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getDefaultHost().attachDefault( new BasicJaasAuthenticationApplication()); component.start(); } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/CertificateAuthenticationApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/CertificateAuthent0000664000175000017500000000473711757206350034057 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch05.EchoPrincipalsResource; import org.restlet.routing.Router; import org.restlet.security.Authenticator; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * */ public class CertificateAuthenticationApplication extends Application { @Override public synchronized Restlet createInboundRoot() { Router router = new Router(getContext()); router.attachDefault(EchoPrincipalsResource.class); Authenticator authenticator = new ClientCertificateAuthenticator( getContext()); authenticator.setNext(router); return authenticator; } public static void main(String[] args) throws Exception { Component component = new Component(); Server server = component.getServers().add(Protocol.HTTPS, 8183); server.getContext().getParameters().add("wantClientAuthentication", "true"); component.getDefaultHost().attachDefault( new CertificateAuthenticationApplication()); component.start(); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/ClientCertificateAuthenticator.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/ClientCertificateA0000664000175000017500000001161611757206352033762 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec2; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import javax.security.auth.x500.X500Principal; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.security.Authenticator; import org.restlet.security.User; /** * Authenticator based on the SSL client certificate. If a client certificate is * presented, it adds the Principal of its subject to the list of principals in * the request's ClientInfo. It also sets the user to be a new User based on * this Principal. * * {@link #getPrincipal(List)} and {@link #getUser(Principal)} can be overridden * to change the default behaviour. * * @author Bruno Harbulot (Bruno.Harbulot@manchester.ac.uk) */ public class ClientCertificateAuthenticator extends Authenticator { public ClientCertificateAuthenticator(Context context) { super(context); } /** * Extracts the Principal of the subject to use from a chain of certificate. * By default, this is the X500Principal of the subject subject of the first * certificate in the chain. * * @see X509Certificate * @see X500Principal * @param certificateChain * chain of client certificates. * @return Principal of the client certificate or null if the chain is * empty. */ protected List getPrincipals( List certificateChain) { if ((certificateChain != null) && (certificateChain.size() > 0)) { ArrayList principals = new ArrayList(); X509Certificate userCert = certificateChain.get(0); principals.add(userCert.getSubjectX500Principal()); return principals; } else { return null; } } /** * Creates a new User based on the subject's X500Principal. By default, the * user name is the subject distinguished name, formatted accorded to RFC * 2253. Some may choose to extract the Common Name only, for example. * * @param principal * subject's Principal (most likely X500Principal). * @return User instance corresponding to this principal or null. */ protected User getUser(Principal principal) { if (principal != null) { return new User(principal.getName()); } else { return null; } } /** * Authenticates the call using the X.509 client certificate. The * verification of the credentials is normally done by the SSL layer, via * the TrustManagers. * * It uses the certificate chain in the request's * "org.restlet.https.clientCertificates" attribute, adds the principal * returned from this chain by {@link #getPrincipal(List)} to the request's * ClientInfo and set the user to the result of {@link #getUser(Principal)} * if that user is non-null. */ @Override protected boolean authenticate(Request request, Response response) { @SuppressWarnings("unchecked") List certchain = (List) request .getAttributes().get("org.restlet.https.clientCertificates"); List principals = getPrincipals(certchain); if ((principals != null) && (principals.size() > 0)) { request.getClientInfo().getPrincipals().addAll(principals); User user = getUser(principals.get(0)); if (user != null) { request.getClientInfo().setUser(user); } return true; } else { return false; } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/BasicAuthenticationApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/BasicAuthenticatio0000664000175000017500000000543311757206352034043 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch05.EchoPrincipalsResource; import org.restlet.routing.Router; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.LocalVerifier; import org.restlet.security.MapVerifier; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * */ public class BasicAuthenticationApplication extends Application { private final LocalVerifier verifier; public BasicAuthenticationApplication() { MapVerifier verifier = new MapVerifier(); verifier.getLocalSecrets().put("scott", "tiger".toCharArray()); this.verifier = verifier; } @Override public synchronized Restlet createInboundRoot() { Router router = new Router(getContext()); router.attachDefault(EchoPrincipalsResource.class); ChallengeAuthenticator authenticator = new ChallengeAuthenticator( getContext(), ChallengeScheme.HTTP_BASIC, "Basic Test"); authenticator.setVerifier(verifier); authenticator.setNext(router); return authenticator; } public static void main(String[] args) throws Exception { Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getDefaultHost().attachDefault( new BasicAuthenticationApplication()); component.start(); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/DigestAuthenticationApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec2/DigestAuthenticati0000664000175000017500000000516111757206350034056 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec2; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.ext.crypto.DigestAuthenticator; import org.restlet.routing.Router; import org.restlet.security.LocalVerifier; import org.restlet.security.MapVerifier; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * */ public class DigestAuthenticationApplication extends Application { private final LocalVerifier verifier; public DigestAuthenticationApplication() { MapVerifier verifier = new MapVerifier(); verifier.getLocalSecrets().put("scott", "tiger".toCharArray()); this.verifier = verifier; } @Override public synchronized Restlet createInboundRoot() { Router router = new Router(getContext()); DigestAuthenticator authenticator = new DigestAuthenticator( getContext(), "Digest Test", "1234567890ABCDEF"); authenticator.setWrappedVerifier(this.verifier); authenticator.setNext(router); return authenticator; } public static void main(String[] args) throws Exception { Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getDefaultHost().attachDefault( new DigestAuthenticationApplication()); component.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec3/0000775000175000017500000000000011757206350030347 5ustar jamespagejamespage././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec3/RoleAuthorizationComponent.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec3/RoleAuthorizationC0000664000175000017500000000743111757206350034064 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec3; import org.restlet.Application; import org.restlet.Component; import org.restlet.Context; import org.restlet.data.Protocol; import org.restlet.example.book.restlet.ch05.sec4.SecurityManagerDemoComponent; import org.restlet.security.Group; import org.restlet.security.MemoryRealm; import org.restlet.security.Role; import org.restlet.security.User; /** * Sample SAAS component with declared organizations. * * @author Jerome Louvel */ public class RoleAuthorizationComponent extends Component { public RoleAuthorizationComponent() { MemoryRealm realm = new MemoryRealm(); // Add users User stiger = new User("stiger", "pwd", "Scott", "Tiger", "scott.tiger@foobar.com"); realm.getUsers().add(stiger); User larmstrong = new User("larmstrong", "pwd", "Louis", "Armstrong", "la@foobar.com"); realm.getUsers().add(larmstrong); // Add groups Group employees = new Group("employees", "All FooBar employees"); employees.getMemberUsers().add(larmstrong); realm.getRootGroups().add(employees); Group contractors = new Group("contractors", "All FooBar contractors"); contractors.getMemberUsers().add(stiger); realm.getRootGroups().add(contractors); Group managers = new Group("managers", "All FooBar managers"); realm.getRootGroups().add(managers); Group directors = new Group("directors", "Top-level directors"); directors.getMemberUsers().add(larmstrong); managers.getMemberGroups().add(directors); Group developers = new Group("developers", "All FooBar developers"); realm.getRootGroups().add(developers); Group engineers = new Group("engineers", "All FooBar engineers"); engineers.getMemberUsers().add(stiger); developers.getMemberGroups().add(engineers); Context appContext = getContext().createChildContext(); Application app = new RoleAuthorizationApplication(appContext); appContext.setDefaultEnroler(realm.getEnroler()); appContext.setDefaultVerifier(realm.getVerifier()); Role adminRole = new Role("admin", "Administrator"); realm.map(managers, adminRole); app.getRoles().add(adminRole); getDefaultHost().attachDefault(app); } public static void main(String[] args) throws Exception { SecurityManagerDemoComponent component = new SecurityManagerDemoComponent(); component.getServers().add(Protocol.HTTP, 8111); component.start(); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec3/RoleAuthorizationApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec3/RoleAuthorizationA0000664000175000017500000000476311757206350034067 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec3; import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.example.book.restlet.ch05.EchoPrincipalsResource; import org.restlet.routing.Router; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.RoleAuthorizer; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * */ public class RoleAuthorizationApplication extends Application { public RoleAuthorizationApplication(Context context) { super(context); } @Override public synchronized Restlet createInboundRoot() { ChallengeAuthenticator authenticator = new ChallengeAuthenticator( getContext(), ChallengeScheme.HTTP_BASIC, "Basic Test"); authenticator.setVerifier(getContext().getDefaultVerifier()); RoleAuthorizer authorizer = new RoleAuthorizer(); authorizer.getAuthorizedRoles().add(getRole("admin")); authorizer.setNext(EchoPrincipalsResource.class); Router router = new Router(getContext()); router.attach("/admin", authorizer); router.attachDefault(EchoPrincipalsResource.class); authenticator.setNext(router); return authenticator; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec5/0000775000175000017500000000000011757206350030351 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec5/VerificationServer.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec5/VerificationServer0000664000175000017500000000313111757206350034103 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec5; import org.restlet.Server; import org.restlet.data.Protocol; public class VerificationServer { public static void main(String[] args) throws Exception { // Instantiating the HTTP server and listening on port 8111 new Server(Protocol.HTTP, 8111, VerifiedServerResource.class) .start(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec5/VerifiedServerResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec5/VerifiedServerReso0000664000175000017500000000375111757206350034057 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec5; import java.security.NoSuchAlgorithmException; import org.restlet.representation.DigesterRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class VerifiedServerResource extends ServerResource { @Get public Representation represent() throws NoSuchAlgorithmException { // Wraps the StringRepresentation DigesterRepresentation result = new DigesterRepresentation( new StringRepresentation("hello, world")); // Compute's representation's digest. result.setDigest(result.computeDigest()); return result; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec5/VerificationClient.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/sec5/VerificationClient0000664000175000017500000000372011757206350034057 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05.sec5; import org.restlet.representation.DigesterRepresentation; import org.restlet.resource.ClientResource; public class VerificationClient { public static void main(String[] args) throws Exception { ClientResource resource = new ClientResource( "http://localhost:8111/"); // The Digester helps computing the digest while reading or writing the // representation's content. DigesterRepresentation rep = new DigesterRepresentation(resource.get()); rep.write(System.out); if (rep.checkDigest()) { System.out.println("\nContent checked."); } else { System.out.println("\nContent not checked."); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/EchoPrincipalsResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/book/restlet/ch05/EchoPrincipalsResource.0000664000175000017500000000521111757206352034127 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.book.restlet.ch05; import java.security.Principal; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import org.restlet.security.Role; /** * @author Bruno Harbulot (bruno/distributedmatter.net) * */ public class EchoPrincipalsResource extends ServerResource { @Get("txt") public Representation echoPrincipals() throws ResourceException { StringBuilder sb = new StringBuilder("* User: "); sb.append(getClientInfo().getUser()); sb.append("\n"); sb.append("* Roles: \n"); for (Role role : getClientInfo().getRoles()) { sb.append(" - "); sb.append(role.getName()); sb.append("\n"); } sb.append("* Principals: \n"); for (Principal principal : getClientInfo().getPrincipals()) { sb.append(" - "); sb.append(principal.getName()); sb.append(" ("); sb.append(principal.getClass()); sb.append(")\n"); } Representation rep = new StringRepresentation(sb, MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8); return rep; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/0000775000175000017500000000000011757206352026204 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part02b.java0000664000175000017500000000344011757206350030260 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.resource.ClientResource; /** * Retrieving the content of a Web page (detailed). * * @author Jerome Louvel */ public class Part02b { public static void main(String[] args) throws Exception { // Create the client resource ClientResource resource = new ClientResource("http://www.restlet.org"); // Customize the referrer property resource.setReferrerRef("http://www.mysite.org"); // Write the response entity on the console resource.get().write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/OrderResource.java0000664000175000017500000000346311757206352031640 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.resource.Get; /** * Related to the part 12 of the tutorial. * * @author Jerome Louvel */ public class OrderResource extends UserResource { String orderId; Object order; @Override public void doInit() { super.doInit(); this.orderId = (String) getRequestAttributes().get("order"); this.order = null; // Could be a lookup to a domain object. } @Get public String toString() { return "Order \"" + this.orderId + "\" for user \"" + this.userName + "\""; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part10.java0000664000175000017500000000624411757206350030122 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Extractor; import org.restlet.routing.Redirector; import org.restlet.routing.Router; /** * URI rewriting, attribute extraction and redirection. * * @author Jerome Louvel */ public class Part10 extends Application { /** * Run the example as a standalone component. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { // Create a component Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); // Create an application Application application = new Part10(); // Attach the application to the component and start it component.getDefaultHost().attachDefault(application); component.start(); } @Override public Restlet createInboundRoot() { // Create a root router Router router = new Router(getContext()); // Create a Redirector to Google search service String target = "http://www.google.com/search?q=site:mysite.org+{keywords}"; Redirector redirector = new Redirector(getContext(), target, Redirector.MODE_CLIENT_TEMPORARY); // While routing requests to the redirector, extract the "kwd" query // parameter. For instance : // http://localhost:8111/search?kwd=myKeyword1+myKeyword2 // will be routed to // http://www.google.com/search?q=site:mysite.org+myKeyword1%20myKeyword2 Extractor extractor = new Extractor(getContext(), redirector); extractor.extractFromQuery("keywords", "kwd", true); // Attach the extractor to the router router.attach("/search", extractor); // Return the root router return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part06.java0000664000175000017500000000432711757206350030127 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import static org.restlet.example.tutorial.Constants.ROOT_URI; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.resource.Directory; /** * Server static files using an application. * * @author Jerome Louvel */ public class Part06 { public static void main(String[] args) throws Exception { // Create a component Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getClients().add(Protocol.FILE); // Create an application Application application = new Application() { @Override public Restlet createInboundRoot() { return new Directory(getContext(), ROOT_URI); } }; // Attach the application to the component and start it component.getDefaultHost().attach(application); component.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part09b.java0000664000175000017500000000513511757206350030272 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Status; import org.restlet.resource.ClientResource; /** * Authenticating to an HTTP server. * * @author Jerome Louvel */ public class Part09b { public static void main(String[] args) throws Exception { // Prepare the request ClientResource resource = new ClientResource("http://localhost:8111/"); // Add the client authentication to the call ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC; ChallengeResponse authentication = new ChallengeResponse(scheme, "scott", "tiger"); resource.setChallengeResponse(authentication); // Send the HTTP GET request resource.get(); if (resource.getStatus().isSuccess()) { // Output the response entity on the JVM console resource.getResponseEntity().write(System.out); } else if (resource.getStatus() .equals(Status.CLIENT_ERROR_UNAUTHORIZED)) { // Unauthorized access System.out .println("Access authorized by the server, check your credentials"); } else { // Unexpected status System.out.println("An unexpected status was returned: " + resource.getStatus()); } } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Constants.java0000664000175000017500000000264211757206350031025 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; /** * Constants for the tutorial examples. * * @author Jerome Louvel */ public class Constants { public static final String ROOT_URI = "file:///c:/"; } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/OrdersResource.java0000664000175000017500000000302311757206352032013 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.resource.Get; /** * Related to the part 12 of the tutorial. * * @author Jerome Louvel */ public class OrdersResource extends UserResource { @Get public String toString() { return "Orders of user \"" + this.userName + "\""; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part11.java0000664000175000017500000001201711757206352030120 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import static org.restlet.example.tutorial.Constants.ROOT_URI; import org.restlet.Application; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.resource.Directory; import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.MapVerifier; /** * Routers and hierarchical URIs * * @author Jerome Louvel */ public class Part11 extends Application { /** * Run the example as a standalone component. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { // Create a component Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getClients().add(Protocol.FILE); // Create an application Application application = new Part11(); // Attach the application to the component and start it component.getDefaultHost().attach(application); component.start(); } @Override public Restlet createInboundRoot() { // Create a root router Router router = new Router(getContext()); // Create a simple password verifier MapVerifier verifier = new MapVerifier(); verifier.getLocalSecrets().put("scott", "tiger".toCharArray()); // Create a Guard // Attach a guard to secure access to the directory ChallengeAuthenticator guard = new ChallengeAuthenticator(getContext(), ChallengeScheme.HTTP_BASIC, "Tutorial"); guard.setVerifier(verifier); router.attach("/docs/", guard).setMatchingMode( Template.MODE_STARTS_WITH); // Create a directory able to expose a hierarchy of files Directory directory = new Directory(getContext(), ROOT_URI); guard.setNext(directory); // Create the account handler Restlet account = new Restlet() { @Override public void handle(Request request, Response response) { // Print the requested URI path String message = "Account of user \"" + request.getAttributes().get("user") + "\""; response.setEntity(message, MediaType.TEXT_PLAIN); } }; // Create the orders handler Restlet orders = new Restlet(getContext()) { @Override public void handle(Request request, Response response) { // Print the user name of the requested orders String message = "Orders of user \"" + request.getAttributes().get("user") + "\""; response.setEntity(message, MediaType.TEXT_PLAIN); } }; // Create the order handler Restlet order = new Restlet(getContext()) { @Override public void handle(Request request, Response response) { // Print the user name of the requested orders String message = "Order \"" + request.getAttributes().get("order") + "\" for user \"" + request.getAttributes().get("user") + "\""; response.setEntity(message, MediaType.TEXT_PLAIN); } }; // Attach the handlers to the root router router.attach("/users/{user}", account); router.attach("/users/{user}/orders", orders); router.attach("/users/{user}/orders/{order}", order); // Return the root router return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part09a.java0000664000175000017500000000604711757206352030276 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import static org.restlet.example.tutorial.Constants.ROOT_URI; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.data.Protocol; import org.restlet.resource.Directory; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.MapVerifier; /** * Guard access to a Restlet. * * @author Jerome Louvel */ public class Part09a extends Application { /** * Run the example as a standalone component. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { // Create a component Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getClients().add(Protocol.FILE); // Create an application Application application = new Part09a(); // Attach the application to the component and start it component.getDefaultHost().attachDefault(application); component.start(); } @Override public Restlet createInboundRoot() { // Create a simple password verifier MapVerifier verifier = new MapVerifier(); verifier.getLocalSecrets().put("scott", "tiger".toCharArray()); // Create a Guard ChallengeAuthenticator authenticator = new ChallengeAuthenticator( getContext(), ChallengeScheme.HTTP_BASIC, "Tutorial"); authenticator.setVerifier(verifier); // Create a Directory able to return a deep hierarchy of files Directory directory = new Directory(getContext(), ROOT_URI); directory.setListingAllowed(true); authenticator.setNext(directory); return authenticator; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/package.html0000664000175000017500000000010011757206352030454 0ustar jamespagejamespage Tutorial examples. @since 1.0 restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part05.java0000664000175000017500000000453611757206352030132 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.Component; import org.restlet.data.Protocol; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Restlets components. * * @author Jerome Louvel */ public class Part05 extends ServerResource { public static void main(String[] args) throws Exception { // Create a new Restlet component and add a HTTP server connector to it Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); // Then attach it to the local host component.getDefaultHost().attach("/trace", Part05.class); // Now, let's start the component! // Note that the HTTP server connector is also automatically started. component.start(); } @Get public String toString() { // Print the requested URI path return "Resource URI : " + getReference() + '\n' + "Root URI : " + getRootRef() + '\n' + "Routed part : " + getReference().getBaseRef() + '\n' + "Remaining part: " + getReference().getRemainingPart(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/UserResource.java0000664000175000017500000000343611757206352031503 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Related to the part 12 of the tutorial. * * @author Jerome Louvel */ public class UserResource extends ServerResource { String userName; Object user; @Override public void doInit() { this.userName = (String) getRequestAttributes().get("user"); this.user = null; // Could be a lookup to a domain object. } @Get public String toString() { return "Account of user \"" + this.userName + "\""; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part12.java0000664000175000017500000000505111757206352030121 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.routing.Router; /** * Reaching target Resources * * @author Jerome Louvel */ public class Part12 extends Application { /** * Run the example as a standalone component. * * @param args * The optional arguments. * @throws Exception */ public static void main(String[] args) throws Exception { // Create a component Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); // Create an application Application application = new Part12(); // Attach the application to the component and start it component.getDefaultHost().attachDefault(application); component.start(); } @Override public Restlet createInboundRoot() { // Create a router Router router = new Router(getContext()); // Attach the resources to the router router.attach("/users/{user}", UserResource.class); router.attach("/users/{user}/orders", OrdersResource.class); router.attach("/users/{user}/orders/{order}", OrderResource.class); // Return the root router return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part03.java0000664000175000017500000000341311757206350030117 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Listening to Web browsers. * * @author Jerome Louvel */ public class Part03 extends ServerResource { public static void main(String[] args) throws Exception { // Create the HTTP server and listen on port 8111 new Server(Protocol.HTTP, 8111, Part03.class).start(); } @Get public String toString() { return "hello, world"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/tutorial/Part02a.java0000664000175000017500000000313011757206352030255 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.tutorial; import org.restlet.resource.ClientResource; /** * Retrieving the content of a Web page. * * @author Jerome Louvel */ public class Part02a { public static void main(String[] args) throws Exception { // Outputting the content of a Web page new ClientResource("http://www.restlet.org").get().write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/dist/0000775000175000017500000000000012001473213025265 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/package.html0000664000175000017500000000012111757206352026614 0ustar jamespagejamespage Various Restlet examples. @since Restlet 1.0 restlet-2.0.14/org.restlet.example/src/org/restlet/example/misc/0000775000175000017500000000000011757206352025274 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/misc/HeadersTest.java0000664000175000017500000000674411757206350030363 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.misc; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.util.Series; /** * Display the HTTP accept header sent by the Web browsers. * * @author Jerome Louvel */ public class HeadersTest { public static void main(String[] args) throws Exception { final Restlet restlet = new Restlet() { @SuppressWarnings("unchecked") @Override public void handle(Request request, Response response) { // ------------------------------ // Getting an HTTP request header // ------------------------------ Series headers = (Series) request.getAttributes() .get("org.restlet.http.headers"); // The headers list contains all received HTTP headers, in raw // format. // Below, we simply display the standard "Accept" HTTP header. response.setEntity("Accept header: " + headers.getFirstValue("accept", true), MediaType.TEXT_PLAIN); // ----------------------- // Adding response headers // ----------------------- headers = new Form(); // Non-standard headers are allowed headers.add("X-Test", "Test value"); // Standard HTTP headers are forbidden. If you happen to add one // like the "Location" // header below, it will be ignored and a warning message will // be displayed in the logs. headers.add("Location", "http://www.restlet.org"); // Setting the additional headers into the shared call's // attribute response.getAttributes().put("org.restlet.http.headers", headers); } }; // Create the HTTP server and listen on port 8111 final Server server = new Server(Protocol.HTTP, 8111, restlet); server.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/misc/package.html0000664000175000017500000000007411757206352027556 0ustar jamespagejamespage Misc examples. @since 1.0 restlet-2.0.14/org.restlet.example/src/org/restlet/example/misc/ClapTest.java0000664000175000017500000000470311757206352027662 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.misc; import org.restlet.Application; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.resource.Directory; /** * HTTP server exposing a Directory of resources based on a local CLAP client * (ClassLoader Access Protocol). * * @author Jerome Louvel */ public class ClapTest { public static void main(String[] args) throws Exception { final Component component = new Component(); component.getServers().add(Protocol.HTTP, 8111); component.getClients().add(Protocol.CLAP); final Application application = new Application() { @Override public Restlet createInboundRoot() { getConnectorService().getClientProtocols().add(Protocol.CLAP); getConnectorService().getServerProtocols().add(Protocol.HTTP); final Directory directory = new Directory(getContext(), "clap://class"); directory.setListingAllowed(true); directory.setDeeplyAccessible(true); return directory; } }; component.getDefaultHost().attach(application); component.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/misc/AwsTest.java0000664000175000017500000000603511757206350027533 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.misc; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Form; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * Test the Amazon Web Service authentication. * * @author Jerome Louvel */ public class AwsTest { public static void main(String[] args) throws Exception { // Prepare the request final Request request = new Request(Method.GET, "http://s3.amazonaws.com/quotes/nelson"); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_AWS_S3, "44CF9590006BF252F707", "OtxrzxIsfpFjA7SwPzILwy8Bw21TLhquhboDYROV")); // Add some extra headers final Series extraHeaders = new Form(); extraHeaders.add("X-Amz-Meta-Author", "foo@bar.com"); extraHeaders.add("X-Amz-Magic", "abracadabra"); // For the test we hard coded a special date header. Normally you don't // need this as the // HTTP client connector will automatically provide an accurate Date // header and use it // for authentication. // extraHeaders.add("X-Amz-Date", "Thu, 17 Nov 2005 18:49:58 GMT"); request.getAttributes().put("org.restlet.http.headers", extraHeaders); // Handle it using an HTTP client connector final Client client = new Client(Protocol.HTTP); final Response response = client.handle(request); // Write the response entity on the console final Representation output = response.getEntity(); output.write(System.out); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/0000775000175000017500000000000011757206352027200 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/ItemResource.java0000664000175000017500000001030311757206350032444 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstResource; import java.io.IOException; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; import org.w3c.dom.Document; import org.w3c.dom.Element; public class ItemResource extends BaseResource { /** The underlying Item object. */ Item item; /** The sequence of characters that identifies the resource. */ String itemName; @Override protected void doInit() throws ResourceException { // Get the "itemName" attribute value taken from the URI template // /items/{itemName}. this.itemName = (String) getRequest().getAttributes().get("itemName"); // Get the item directly from the "persistence layer". this.item = getItems().get(itemName); setExisting(this.item != null); } /** * Handle DELETE requests. */ @Delete public void removeItem() { if (item != null) { // Remove the item from the list. getItems().remove(item.getName()); } // Tells the client that the request has been successfully fulfilled. setStatus(Status.SUCCESS_NO_CONTENT); } /** * Handle PUT requests. * * @throws IOException */ @Put public void storeItem(Representation entity) throws IOException { // The PUT request updates or creates the resource. if (item == null) { item = new Item(itemName); } // Update the description. Form form = new Form(entity); item.setDescription(form.getFirstValue("description")); if (getItems().putIfAbsent(item.getName(), item) == null) { setStatus(Status.SUCCESS_CREATED); } else { setStatus(Status.SUCCESS_OK); } } @Get("xml") public Representation toXml() { try { DomRepresentation representation = new DomRepresentation( MediaType.TEXT_XML); // Generate a DOM document representing the item. Document d = representation.getDocument(); Element eltItem = d.createElement("item"); d.appendChild(eltItem); Element eltName = d.createElement("name"); eltName.appendChild(d.createTextNode(item.getName())); eltItem.appendChild(eltName); Element eltDescription = d.createElement("description"); eltDescription.appendChild(d.createTextNode(item.getDescription())); eltItem.appendChild(eltDescription); d.normalizeDocument(); // Returns the XML representation of this document. return representation; } catch (IOException e) { e.printStackTrace(); } return null; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/BaseResource.java0000664000175000017500000000344411757206352032432 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstResource; import java.util.concurrent.ConcurrentMap; import org.restlet.resource.ServerResource; /** * Base resource class that supports common behaviours or attributes shared by * all resources. * */ public abstract class BaseResource extends ServerResource { /** * Returns the map of items managed by this application. * * @return the map of items managed by this application. */ protected ConcurrentMap getItems() { return ((FirstResourceApplication) getApplication()).getItems(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/FirstResourceClientMain.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/FirstResourceClientMain.jav0000664000175000017500000001014411757206352034445 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstResource; import java.io.IOException; import org.restlet.data.Form; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; public class FirstResourceClientMain { public static void main(String[] args) throws IOException, ResourceException { // Define our Restlet client resources. ClientResource itemsResource = new ClientResource( "http://localhost:8111/firstResource/items"); ClientResource itemResource = null; // Create a new item Item item = new Item("item1", "this is an item."); try { Representation r = itemsResource.post(getRepresentation(item)); itemResource = new ClientResource(r.getLocationRef()); } catch (ResourceException e) { System.out.println("Error status: " + e.getStatus()); System.out.println("Error message: " + e.getMessage()); } // Consume the response's entity which releases the connection itemsResource.getResponseEntity().exhaust(); if (itemResource != null) { // Prints the representation of the newly created resource. get(itemResource); // Prints the list of registered items. get(itemsResource); // Update the item item.setDescription("This is an other description"); itemResource.put(getRepresentation(item)); // Prints the list of registered items. get(itemsResource); // delete the item itemResource.delete(); // Print the list of registered items. get(itemsResource); } } /** * Prints the resource's representation. * * @param clientResource * The Restlet client resource. * @throws IOException * @throws ResourceException */ public static void get(ClientResource clientResource) throws IOException, ResourceException { try { clientResource.get().write(System.out); } catch (ResourceException e) { System.out.println("Error status: " + e.getStatus()); System.out.println("Error message: " + e.getMessage()); // Consume the response's entity which releases the connection clientResource.getResponseEntity().exhaust(); } } /** * Returns the Representation of an item. * * @param item * the item. * * @return The Representation of the item. */ public static Representation getRepresentation(Item item) { // Gathering informations into a Web form. Form form = new Form(); form.add("name", item.getName()); form.add("description", item.getDescription()); return form.getWebRepresentation(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/Item.java0000664000175000017500000000363511757206352030750 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstResource; public class Item { /** A description of the item. */ private String description; /** Name of the item. */ private String name; public Item(String name) { super(); setName(name); } public Item(String name, String description) { super(); setName(name); setDescription(description); } public String getDescription() { return description; } public String getName() { return name; } public void setDescription(String description) { this.description = description; } public void setName(String name) { this.name = name; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/ItemsResource.java0000664000175000017500000001301411757206350032631 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstResource; import java.io.IOException; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Resource that manages a list of items. * */ public class ItemsResource extends BaseResource { /** * Handle POST requests: create a new item. */ @Post public Representation acceptItem(Representation entity) { Representation result = null; // Parse the given representation and retrieve pairs of // "name=value" tokens. Form form = new Form(entity); String itemName = form.getFirstValue("name"); String itemDescription = form.getFirstValue("description"); // Register the new item if one is not already registered. if (!getItems().containsKey(itemName) && getItems().putIfAbsent(itemName, new Item(itemName, itemDescription)) == null) { // Set the response's status and entity setStatus(Status.SUCCESS_CREATED); Representation rep = new StringRepresentation("Item created", MediaType.TEXT_PLAIN); // Indicates where is located the new resource. rep.setLocationRef(getRequest().getResourceRef().getIdentifier() + "/" + itemName); result = rep; } else { // Item is already registered. setStatus(Status.CLIENT_ERROR_NOT_FOUND); result = generateErrorRepresentation("Item " + itemName + " already exists.", "1"); } return result; } /** * Generate an XML representation of an error response. * * @param errorMessage * the error message. * @param errorCode * the error code. */ private Representation generateErrorRepresentation(String errorMessage, String errorCode) { DomRepresentation result = null; // This is an error // Generate the output representation try { result = new DomRepresentation(MediaType.TEXT_XML); // Generate a DOM document representing the list of // items. Document d = result.getDocument(); Element eltError = d.createElement("error"); Element eltCode = d.createElement("code"); eltCode.appendChild(d.createTextNode(errorCode)); eltError.appendChild(eltCode); Element eltMessage = d.createElement("message"); eltMessage.appendChild(d.createTextNode(errorMessage)); eltError.appendChild(eltMessage); } catch (IOException e) { e.printStackTrace(); } return result; } /** * Returns a listing of all registered items. */ @Get("xml") public Representation toXml() { // Generate the right representation according to its media type. try { DomRepresentation representation = new DomRepresentation( MediaType.TEXT_XML); // Generate a DOM document representing the list of // items. Document d = representation.getDocument(); Element r = d.createElement("items"); d.appendChild(r); for (Item item : getItems().values()) { Element eltItem = d.createElement("item"); Element eltName = d.createElement("name"); eltName.appendChild(d.createTextNode(item.getName())); eltItem.appendChild(eltName); Element eltDescription = d.createElement("description"); eltDescription.appendChild(d.createTextNode(item .getDescription())); eltItem.appendChild(eltDescription); r.appendChild(eltItem); } d.normalizeDocument(); // Returns the XML representation of this document. return representation; } catch (IOException e) { e.printStackTrace(); } return null; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/FirstResourceServerMain.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/FirstResourceServerMain.jav0000664000175000017500000000344511757206352034503 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstResource; import org.restlet.Component; import org.restlet.data.Protocol; public class FirstResourceServerMain { public static void main(String[] args) throws Exception { // Create a new Component. Component component = new Component(); // Add a new HTTP server listening on port 8111. component.getServers().add(Protocol.HTTP, 8111); component.getDefaultHost().attach("/firstResource", new FirstResourceApplication()); // Start the component. component.start(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/FirstResourceApplication.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstResource/FirstResourceApplication.ja0000664000175000017500000000451711757206350034504 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstResource; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; public class FirstResourceApplication extends Application { /** The list of items is persisted in memory. */ private final ConcurrentMap items = new ConcurrentHashMap(); /** * Creates a root Restlet that will receive all incoming calls. */ @Override public Restlet createInboundRoot() { // Create a router Restlet that defines routes. Router router = new Router(getContext()); // Defines a route for the resource "list of items" router.attach("/items", ItemsResource.class); // Defines a route for the resource "item" router.attach("/items/{itemName}", ItemResource.class); return router; } /** * Returns the list of registered items. * * @return the list of registered items. */ public ConcurrentMap getItems() { return items; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/firstSteps/0000775000175000017500000000000011757206352026507 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/firstSteps/FirstStepsApplication.java0000664000175000017500000000350311757206350033643 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstSteps; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; public class FirstStepsApplication extends Application { /** * Creates a root Restlet that will receive all incoming calls. */ @Override public Restlet createInboundRoot() { // Create a router Restlet that routes each call to a // new instance of HelloWorldResource. Router router = new Router(getContext()); // Defines only one route router.attachDefault(HelloWorldResource.class); return router; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/firstSteps/HelloWorldResource.java0000664000175000017500000000302311757206350033131 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstSteps; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Resource which has only one representation. */ public class HelloWorldResource extends ServerResource { @Get public String represent() { return "hello, world"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/firstSteps/FirstStepsMain.java0000664000175000017500000000347411757206352032275 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.firstSteps; import org.restlet.Component; import org.restlet.data.Protocol; public class FirstStepsMain { public static void main(String[] args) throws Exception { // Create a new Component. Component component = new Component(); // Add a new HTTP server listening on port 8111. component.getServers().add(Protocol.HTTP, 8111); // Attach the sample application. component.getDefaultHost().attach("/firstSteps", new FirstStepsApplication()); // Start the component. component.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/0000775000175000017500000000000011757206350025137 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/0000775000175000017500000000000011757206352026270 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/ExampleApplication.java0000664000175000017500000000462311757206350032715 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import org.restlet.example.ext.jaxrs.employees.EmployeesResource; /** * An {@link ApplicationConfig} contains the root resource classes and the * providers for an JAX-RS application.
    * This example application configuration contains two root resource classes ( * {@link EasyRootResource} and {@link EmployeesResource}, see * {@link #getResourceClasses()}) and no provider (default, would be returned by * {@link ApplicationConfig#getProviderClasses()}. * * @author Stephan Koops * @see EasyRootResource * @see EmployeesResource * @see ExampleServer * @see GuardedExample */ public class ExampleApplication extends Application { /** * creates a new Application configuration for this example. */ public ExampleApplication() { } /** * @see javax.ws.rs.core.ApplicationConfig#getResourceClasses() */ @Override public Set> getClasses() { final Set> rrcs = new HashSet>(); rrcs.add(EasyRootResource.class); rrcs.add(EmployeesResource.class); return rrcs; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/GuardedExample.java0000664000175000017500000001165411757206350032027 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs; import java.security.Principal; import javax.ws.rs.core.SecurityContext; import org.restlet.Component; import org.restlet.Server; import org.restlet.data.ChallengeScheme; import org.restlet.data.Protocol; import org.restlet.ext.jaxrs.JaxRsApplication; import org.restlet.ext.jaxrs.RoleChecker; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.MemoryRealm; import org.restlet.security.User; /** *

    * This class shows how to use the Restlet JAX-RS extension with access control. *

    *

    * Start this class, open a browser and click easy or persons with one of the following user / * password combinations: *

      *
    • admin / adminPW
    • *
    • alice / alicesSecret
    • *
    • bob / bobsSecret
    • *
    *

    * * @author Stephan Koops * @see ExampleServer * @see ExampleApplication */ @SuppressWarnings("deprecation") public class GuardedExample { /** * An example {@link RoleChecker}. This example allows anything to user * admin and only read to any other user.
    * This RoleChecker isn't used by the resources. * * @author Stephan Koops */ private static final class ExampleRoleChecker implements RoleChecker { /** * @see RoleChecker#isInRole(Principal, String) * @see SecurityContext#isUserInRole(String) */ public boolean isInRole(Principal principal, String role) { // access database or whatever // example: user "admin" has all roles if (principal.getName().equalsIgnoreCase("admin")) { return true; } // example: every authenticated user could read if (role.equalsIgnoreCase("read")) { return true; } // the normal users have no other roles. return false; } } public static void main(String[] args) throws Exception { // create Component (as ever for Restlet) final Component comp = new Component(); final Server server = comp.getServers().add(Protocol.HTTP, 80); // create JAX-RS runtime environment final JaxRsApplication application = new JaxRsApplication(comp .getContext().createChildContext()); // create a Guard final ChallengeAuthenticator guard = new ChallengeAuthenticator( application.getContext(), ChallengeScheme.HTTP_BASIC, "JAX-RS example"); // set valid users and their passwords. MemoryRealm realm = new MemoryRealm(); application.getContext().setDefaultEnroler(realm.getEnroler()); application.getContext().setDefaultVerifier(realm.getVerifier()); realm.getUsers().add(new User("admin", "adminPW".toCharArray())); realm.getUsers().add(new User("alice", "alicesSecret".toCharArray())); realm.getUsers().add(new User("bob", "bobsSecret".toCharArray())); // create an RoleChecker (see above) final ExampleRoleChecker roleChecker = new ExampleRoleChecker(); // attach Guard and RoleChecker application.setAuthentication(guard, roleChecker); // attach ApplicationConfig application.add(new ExampleApplication()); // Attach the application to the component and start it comp.getDefaultHost().attach(application); comp.start(); System.out.println("Server started on port " + server.getPort()); System.out.println("Press key to stop server"); System.in.read(); System.out.println("Stopping server"); comp.stop(); System.out.println("Server stopped"); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/EasyRootResource.java0000664000175000017500000000446611757206350032420 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * This demonstrates an very easy JAX-RS resource. It is available on relative * URI "easy" (see annotation @{@link Path} on this class). This resource * has representations of two media types: "text/html" ({@link #getHtml()} and * "text/plain"). * * @author Stephan Koops * @see ExampleApplication */ @Path("easy") public class EasyRootResource { /** * Returns a HTML representation of this resource. * * @return a HTML representation of this resource. */ @GET @Produces("text/html") public String getHtml() { return "\n" + "This is an easy resource (as html text).\n" + ""; } /** * Returns a plain text representation of this resource. * * @return a plain text representation of this resource. */ @GET @Produces("text/plain") public String getPlain() { return "This is an easy resource (as plain text)"; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/0000775000175000017500000000000011757206352030272 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/Employee.java0000664000175000017500000000404011757206350032710 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs.employees; import java.net.URI; import javax.xml.bind.annotation.XmlRootElement; /** * Contains all data about an employee. * * @author Stephan Koops */ @XmlRootElement public class Employee extends AbstractEmployee { private String sex; private String department; private URI departmentUri; public String getDepartment() { return this.department; } public URI getDepartmentUri() { return this.departmentUri; } public String getSex() { return this.sex; } public void setDepartment(String department) { this.department = department; } public void setDepartmentUri(URI departmentUri) { this.departmentUri = departmentUri; } public void setSex(String sex) { this.sex = sex; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/EmployeeResource.java0000664000175000017500000001353111757206350034425 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs.employees; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; import javax.ws.rs.core.UriInfo; /** * This resource class represents one employee. * * @author Stephan Koops * @see EmployeesResource */ public class EmployeeResource { /** * @param uriInfo * @return * @throws IllegalArgumentException * @throws UriBuilderException */ private static URI createEmployeesUri(final UriInfo uriInfo) { final UriBuilder employeesUri = uriInfo.getBaseUriBuilder(); employeesUri.path(uriInfo.getMatchedURIs().get(0)); final URI build = employeesUri.build(); return build; } private final EmployeeMgr employeeMgr = EmployeeMgr.get(); private final int staffNo; EmployeeResource(int persNr) { this.staffNo = persNr; } @DELETE public Object delete(@Context HttpHeaders httpHeaders, @Context UriInfo uriInfo) { this.employeeMgr.remove(this.staffNo); if (httpHeaders.getAcceptableMediaTypes().contains( MediaType.TEXT_HTML_TYPE)) { return Response.seeOther(createEmployeesUri(uriInfo)); } return null; } @GET @Consumes( { "application/xml", "text/xml", "application/json" }) public Employee get(@Context UriInfo uriInfo) { // load employee with requested id final Employee employee = this.employeeMgr.getFull(this.staffNo); // set department uri final UriBuilder departmentUB = uriInfo.getBaseUriBuilder(); departmentUB.segment("departments", "{depId}"); final String department = employee.getDepartment(); employee.setDepartmentUri(departmentUB.build(department)); return employee; } @GET @Produces("text/html") public StreamingOutput getHtml(@Context final UriInfo uriInfo) { final Employee employee = get(uriInfo); final URI employeesUri = createEmployeesUri(uriInfo); return new StreamingOutput() { public void write(OutputStream output) throws IOException { final PrintStream ps = new PrintStream(output); ps.println(""); ps.println("Employee"); ps.println(""); ps.println("

    Employee

    "); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); // departments are not implemented. ps.println("
    staff no."); ps.println(employee.getStaffNo()); ps.println("
    firstname:"); ps.println(employee.getFirstname()); ps.println("
    lastname:"); ps.println(employee.getLastname()); ps.println("
    sex:"); ps.println(employee.getSex()); ps.println("
    department:"); ps.println(employee.getDepartment()); ps.println("
    "); ps.println("
    "); ps.print("
    "); ps .println(""); ps.println("
    "); ps.print("
    all employees"); ps.println(""); } }; } @PUT @Consumes( { "application/xml", "text/xml", "application/json" }) public void update(Employee employee) { this.employeeMgr.update(this.staffNo, employee); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/EmployeesResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/EmployeesResource.jav0000664000175000017500000001516211757206352034453 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs.employees; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Response.Status; /** * This root resource class represents the list of all available employees. * * @author Stephan Koops * @see EmployeeResource */ @Path("employees") public class EmployeesResource { /** The EmployeeMgr manages the data storage */ private final EmployeeMgr employeeMgr = EmployeeMgr.get(); @Context private UriInfo uriInfo; /** * Creates the URI for the location of an created employee. * * @param staffNo * the number of the created employee * @return the URI for the location of an created employee. */ private URI createdLocation(int staffNo) { final UriBuilder locBuilder = this.uriInfo.getRequestUriBuilder(); locBuilder.path("{staffNo}"); return locBuilder.build(staffNo); } /** Creates a new employee from XML or JSON */ @POST @Consumes( { "application/xml", "text/xml", "application/json" }) public Response createEmployee(Employee employee) { final int staffNo = this.employeeMgr.createEmployee(employee); final URI location = createdLocation(staffNo); return Response.created(location).build(); } @POST @Consumes("application/x-www-form-urlencoded") public Response createEmployee(MultivaluedMap employeeData) { final Employee employee = new Employee(); employee.setFirstname(employeeData.getFirst("firstname")); employee.setLastname(employeeData.getFirst("lastname")); employee.setSex(employeeData.getFirst("sex")); employee.setDepartment(employeeData.getFirst("department")); final int persNo = this.employeeMgr.createEmployee(employee); final URI location = createdLocation(persNo); return Response.seeOther(location).build(); } @GET @Produces( { "application/xml", "text/xml", "application/json" }) public EmployeeList getEmployees() { final EmployeeList employees = this.employeeMgr.getAll(); // set detail URIs final UriBuilder uriBuilder = this.uriInfo.getRequestUriBuilder(); uriBuilder.path("{staffNo}"); for (final SmallEmployee employee : employees) { employee.setDetails(uriBuilder.build(employee.getStaffNo())); } return employees; } @GET @Produces("text/html") public StreamingOutput getListAsHtml() { final EmployeeList employees = getEmployees(); return new StreamingOutput() { public void write(OutputStream output) throws IOException { final PrintStream ps = new PrintStream(output); ps.println(""); ps.println("Employees"); ps.println(""); ps.println("

    Employees

    "); ps.println(""); ps.print("
    "); ps.println(""); ps.println(""); ps .println(""); ps.println(""); ps.println(""); ps .println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps.println(""); ps .println(""); ps.println(""); ps.println(""); ps .println(""); ps.println("
    firstname:
    lastname:
    sex:
    department:
    "); ps.println("
    "); ps.println(""); } }; } /** Create sub resource for one concrete employee. */ @Path("{staffNo}") public EmployeeResource getSub(@PathParam("staffNo") int staffNo) { if (!this.employeeMgr.exists(staffNo)) { throw new WebApplicationException(Status.NOT_FOUND); } return new EmployeeResource(staffNo); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/package.html0000664000175000017500000000047711757206352032563 0ustar jamespagejamespage This package includes example resource classes and other related classes for a JAX-RS application. It is used by the ExampleAppConfig . See also the documenation of package org.restlet.example.jaxrs . @since 1.0 restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/AbstractEmployee.java0000664000175000017500000000401411757206350034375 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs.employees; /** * This class is the superclass of {@link Employee} and {@link SmallEmployee}. * * @author Stephan Koops * @see Employee * @see SmallEmployee */ public abstract class AbstractEmployee { private Integer staffNo; private String firstname; private String lastname; public String getFirstname() { return this.firstname; } public String getLastname() { return this.lastname; } public Integer getStaffNo() { return this.staffNo; } public void setFirstname(String firstname) { this.firstname = firstname; } public void setLastname(String lastname) { this.lastname = lastname; } public void setStaffNo(Integer staffNo) { this.staffNo = staffNo; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/SmallEmployee.java0000664000175000017500000000326711757206350033713 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs.employees; import java.net.URI; import javax.xml.bind.annotation.XmlRootElement; /** * Contains a small amount of data about an employee. * * @author Stephan Koops */ @XmlRootElement(name = "employee") public class SmallEmployee extends AbstractEmployee { private URI details; public URI getDetails() { return this.details; } public void setDetails(URI details) { this.details = details; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/EmployeeMgr.java0000664000175000017500000001227111757206350033363 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs.employees; import java.util.HashMap; import java.util.Map; /** * This class is a very small business logic. It helds some employees and fakes * a data storage. It started with some employees as default. All changes get * lost, when the process is stopped. * * @author Stephan Koops */ public class EmployeeMgr { private static EmployeeMgr singelton = new EmployeeMgr(); /** * Returns the singelton instance of the employee manager. */ public static EmployeeMgr get() { return singelton; } /** contains the employees */ private final Map employees = new HashMap(); { final Employee employee1 = new Employee(); employee1.setStaffNo(1234); employee1.setFirstname("Lucy"); employee1.setLastname("Smith"); employee1.setSex("w"); employee1.setDepartment("research"); this.employees.put(employee1.getStaffNo(), employee1); final Employee employee2 = new Employee(); employee2.setStaffNo(3210); employee2.setFirstname("Jack"); employee2.setLastname("Jonson"); employee2.setSex("m"); employee2.setDepartment("purchase"); this.employees.put(employee2.getStaffNo(), employee2); } /** * @return the staffNo of the created employee */ public synchronized int createEmployee(Employee employee) { final int staffNo = createNewStaffNo(); employee.setStaffNo(staffNo); this.employees.put(employee.getStaffNo(), employee); return staffNo; } /** * Creates and return a staff number to be used for a new employee to * create. */ private synchronized int createNewStaffNo() { int newStaffNo = 3456; for (;;) { if (!exists(newStaffNo)) { return newStaffNo; } newStaffNo++; } } /** * Creates a {@link SmallEmployee} from the given {@link Employee}. */ private synchronized SmallEmployee createSmall(Employee employee) { final SmallEmployee smallEmployee = new SmallEmployee(); smallEmployee.setStaffNo(employee.getStaffNo()); smallEmployee.setFirstname(employee.getFirstname()); smallEmployee.setLastname(employee.getLastname()); return smallEmployee; } /** * Checks, if an employee with the given staff number exists. * * @param staffNo * the number of the employee to check for availability. * @return true, if there is an employee with the given staffNo, or false if * not. */ public synchronized boolean exists(int staffNo) { return this.employees.get(staffNo) != null; } /** * Returns a list of all available employees. * * @return a list of all available employees. */ public synchronized EmployeeList getAll() { final EmployeeList employees = new EmployeeList(); for (final Employee employee : this.employees.values()) { employees.add(createSmall(employee)); } return employees; } /** * Returns the employee with the given number, or null, if he/she does not * exist. */ public synchronized Employee getFull(int staffNo) { return this.employees.get(staffNo); } /** * Returns a little amount of information about the employee with the given * staff number. * * @param staffNo * the number of the employee to get. * @return the employee data. */ public synchronized SmallEmployee getSmall(int staffNo) { final Employee employee = getFull(staffNo); return createSmall(employee); } public synchronized void remove(int staffNo) { this.employees.remove(staffNo); } public synchronized void update(int staffNo, Employee employee) { employee.setStaffNo(staffNo); this.employees.put(staffNo, employee); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/employees/EmployeeList.java0000664000175000017500000000407111757206350033550 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs.employees; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * This List is used to be serialized with JAXB. * * @author Stephan Koops */ @XmlRootElement(name = "employees") public class EmployeeList implements Iterable { private final List employees = new ArrayList(); public void add(SmallEmployee employees) { this.employees.add(employees); } @XmlElement(name = "employee") public List getEmployees() { return this.employees; } /** * @see java.lang.Iterable#iterator() */ public Iterator iterator() { return this.employees.iterator(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/package.html0000664000175000017500000000060711757206352030554 0ustar jamespagejamespage This package demonstrates how to use the Restlet JAX-RS extension. The package org.restlet.example.jaxrs.employees contains an example with more details.
    More documentation is available in the Restlet-Wiki . @since 1.0 restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/jaxrs/ExampleServer.java0000664000175000017500000000522211757206350031714 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.jaxrs; import org.restlet.Component; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.ext.jaxrs.JaxRsApplication; /** *

    * This class shows how to use the Restlet JAX-RS extension without access * control. *

    *

    * Start this class, open a browser and click easy or persons. *

    * * @author Stephan Koops * @see ExampleApplication * @see GuardedExample */ public class ExampleServer { public static void main(String[] args) throws Exception { // create Component (as ever for Restlet) final Component comp = new Component(); final Server server = comp.getServers().add(Protocol.HTTP, 80); // create JAX-RS runtime environment final JaxRsApplication application = new JaxRsApplication(comp .getContext().createChildContext()); // attach ApplicationConfig application.add(new ExampleApplication()); // Attach the application to the component and start it comp.getDefaultHost().attach(application); comp.start(); System.out.println("Server started on port " + server.getPort()); System.out.println("Press key to stop server"); System.in.read(); System.out.println("Stopping server"); comp.stop(); System.out.println("Server stopped"); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/0000775000175000017500000000000011757206352026070 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/ItemResource.java0000664000175000017500000001554211757206350031346 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.wadl; import java.io.IOException; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.ParameterInfo; import org.restlet.ext.wadl.ParameterStyle; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.ResponseInfo; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; import org.w3c.dom.Document; import org.w3c.dom.Element; public class ItemResource extends BaseResource { /** The underlying Item object. */ Item item; /** The sequence of characters that identifies the resource. */ String itemName; @Override public Representation describe() { setName("Representation of a single item"); return super.describe(); } @Override protected void describeDelete(MethodInfo info) { info.setDocumentation("Delete the current item."); ResponseInfo response = new ResponseInfo( "No representation is returned."); response.getStatuses().add(Status.SUCCESS_NO_CONTENT); info.getResponses().add(response); } @Override protected void describeGet(MethodInfo info) { info.setIdentifier("item"); info.setDocumentation("To retrieve details of a specific item"); ResponseInfo response = new ResponseInfo(); RepresentationInfo repInfo = new RepresentationInfo(MediaType.TEXT_XML); repInfo.setXmlElement("item"); repInfo.setDocumentation("XML representation of the current item."); response.getRepresentations().add(repInfo); info.getResponses().add(response); response = new ResponseInfo("Item not found"); repInfo = new RepresentationInfo(MediaType.TEXT_HTML); repInfo.setIdentifier("itemError"); response.getStatuses().add(Status.CLIENT_ERROR_NOT_FOUND); response.getRepresentations().add(repInfo); info.getResponses().add(response); } @Override protected void describePut(MethodInfo info) { info.setDocumentation("Update or create the current item."); RepresentationInfo repInfo = new RepresentationInfo( MediaType.APPLICATION_WWW_FORM); ParameterInfo param = new ParameterInfo("name", ParameterStyle.PLAIN, "Name of the item"); repInfo.getParameters().add(param); param = new ParameterInfo("description", ParameterStyle.PLAIN, "Description of the item"); repInfo.getParameters().add(param); repInfo.setDocumentation("Web form."); info.getRequest().getRepresentations().add(repInfo); ResponseInfo response = new ResponseInfo(); response.getStatuses().add(Status.SUCCESS_OK); response.getStatuses().add(Status.SUCCESS_CREATED); info.getResponses().add(response); response = new ResponseInfo(); response.getStatuses().add(Status.SUCCESS_OK); response.getStatuses().add(Status.SUCCESS_CREATED); info.getResponses().add(response); super.describePut(info); } @Override protected void doInit() throws ResourceException { // Get the "itemName" attribute value taken from the URI template // /items/{itemName}. this.itemName = (String) getRequest().getAttributes().get("itemName"); if (itemName != null) { // Get the item directly from the "persistence layer". this.item = getItems().get(itemName); } setExisting(this.item != null); } /** * Handle DELETE requests. */ @Delete public void removeItem() { if (item != null) { // Remove the item from the list. getItems().remove(item.getName()); } // Tells the client that the request has been successfully fulfilled. setStatus(Status.SUCCESS_NO_CONTENT); } /** * Handle PUT requests. * * @throws IOException */ @Put public void storeItem(Representation entity) throws IOException { // The PUT request updates or creates the resource. if (item == null) { item = new Item(itemName); } // Update the description. Form form = new Form(entity); item.setDescription(form.getFirstValue("description")); if (getItems().putIfAbsent(item.getName(), item) == null) { setStatus(Status.SUCCESS_CREATED); } else { setStatus(Status.SUCCESS_OK); } } @Get("xml") public Representation toXml() { try { DomRepresentation representation = new DomRepresentation( MediaType.TEXT_XML); // Generate a DOM document representing the item. Document d = representation.getDocument(); Element eltItem = d.createElement("item"); d.appendChild(eltItem); Element eltName = d.createElement("name"); eltName.appendChild(d.createTextNode(item.getName())); eltItem.appendChild(eltName); Element eltDescription = d.createElement("description"); eltDescription.appendChild(d.createTextNode(item.getDescription())); eltItem.appendChild(eltDescription); d.normalizeDocument(); // Returns the XML representation of this document. return representation; } catch (IOException e) { e.printStackTrace(); } return null; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/BaseResource.java0000664000175000017500000000344711757206350031323 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.wadl; import java.util.concurrent.ConcurrentMap; import org.restlet.ext.wadl.WadlServerResource; /** * Base resource class that supports common behaviours or attributes shared by * all resources. * */ public abstract class BaseResource extends WadlServerResource { /** * Returns the map of items managed by this application. * * @return the map of items managed by this application. */ protected ConcurrentMap getItems() { return ((FirstResourceApplication) getApplication()).getItems(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/FirstResourceClientMain.java0000664000175000017500000000761511757206350033505 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.wadl; import java.io.IOException; import org.restlet.data.Form; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; public class FirstResourceClientMain { public static void main(String[] args) throws IOException, ResourceException { // Define our Restlet client resources. ClientResource app = new ClientResource( "http://localhost:8111/firstResource"); ClientResource itemsResource = new ClientResource( "http://localhost:8111/firstResource/items"); ClientResource itemResource = null; // Displays the WADL documentation of the application app.options().write(System.out); // Create a new item Item item = new Item("item1", "this is an item."); Representation r = itemsResource.post(getRepresentation(item)); if (itemsResource.getStatus().isSuccess()) { itemResource = new ClientResource(r.getLocationRef()); } if (itemResource != null) { // Prints the representation of the newly created resource. get(itemResource); // Prints the list of registered items. get(itemsResource); // Update the item item.setDescription("This is an other description"); itemResource.put(getRepresentation(item)); // Prints the list of registered items. get(itemsResource); // delete the item itemResource.delete(); // Print the list of registered items. get(itemsResource); } } /** * Prints the resource's representation. * * @param clientResource * The Restlet client resource. * @throws IOException * @throws ResourceException */ public static void get(ClientResource clientResource) throws IOException, ResourceException { clientResource.get(); if (clientResource.getStatus().isSuccess() && clientResource.getResponse().isEntityAvailable()) { clientResource.getResponseEntity().write(System.out); } } /** * Returns the Representation of an item. * * @param item * the item. * * @return The Representation of the item. */ public static Representation getRepresentation(Item item) { // Gathering informations into a Web form. Form form = new Form(); form.add("name", item.getName()); form.add("description", item.getDescription()); return form.getWebRepresentation(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/Item.java0000664000175000017500000000363011757206350027631 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.wadl; public class Item { /** A description of the item. */ private String description; /** Name of the item. */ private String name; public Item(String name) { super(); setName(name); } public Item(String name, String description) { super(); setName(name); setDescription(description); } public String getDescription() { return description; } public String getName() { return name; } public void setDescription(String description) { this.description = description; } public void setName(String name) { this.name = name; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/ItemsResource.java0000664000175000017500000001721411757206350031527 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.wadl; import java.io.IOException; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.ext.wadl.MethodInfo; import org.restlet.ext.wadl.ParameterInfo; import org.restlet.ext.wadl.ParameterStyle; import org.restlet.ext.wadl.RepresentationInfo; import org.restlet.ext.wadl.ResponseInfo; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Post; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Resource that manages a list of items. * */ public class ItemsResource extends BaseResource { /** * Handle POST requests: create a new item. */ @Post public Representation acceptItem(Representation entity) { Representation result = null; // Parse the given representation and retrieve pairs of // "name=value" tokens. Form form = new Form(entity); String itemName = form.getFirstValue("name"); String itemDescription = form.getFirstValue("description"); // Register the new item if one is not already registered. if (!getItems().containsKey(itemName) && getItems().putIfAbsent(itemName, new Item(itemName, itemDescription)) == null) { // Set the response's status and entity setStatus(Status.SUCCESS_CREATED); Representation rep = new StringRepresentation("Item created", MediaType.TEXT_PLAIN); // Indicates where is located the new resource. rep.setLocationRef(getRequest().getResourceRef().getIdentifier() + "/" + itemName); result = rep; } else { // Item is already registered. setStatus(Status.CLIENT_ERROR_NOT_FOUND); result = generateErrorRepresentation("Item " + itemName + " already exists.", "1"); } return result; } @Override protected Representation describe() { setName("List of items."); return super.describe(); } @SuppressWarnings("deprecation") @Override protected void describeGet(MethodInfo info) { info.setIdentifier("items"); info.setDocumentation("Retrieve the list of current items."); ResponseInfo response = new ResponseInfo(); RepresentationInfo repInfo = new RepresentationInfo(MediaType.TEXT_XML); repInfo.setXmlElement("items"); repInfo.setDocumentation("List of items as XML file"); response.getRepresentations().add(repInfo); response.getFaults().add( new org.restlet.ext.wadl.FaultInfo( Status.CLIENT_ERROR_BAD_REQUEST, "Not good at all")); info.getResponses().add(response); } @Override protected void describePost(MethodInfo info) { info.setIdentifier("create_item"); info.setDocumentation("To create an item."); RepresentationInfo repInfo = new RepresentationInfo( MediaType.APPLICATION_WWW_FORM); ParameterInfo param = new ParameterInfo("name", ParameterStyle.PLAIN, "Name of the item"); repInfo.getParameters().add(param); param = new ParameterInfo("description", ParameterStyle.PLAIN, "Description of the item"); repInfo.getParameters().add(param); repInfo.setDocumentation("Web form."); info.getRequest().getRepresentations().add(repInfo); ResponseInfo response = new ResponseInfo(); response.getStatuses().add(Status.SUCCESS_CREATED); info.getResponses().add(response); response = new ResponseInfo(); response.getStatuses().add(Status.CLIENT_ERROR_NOT_FOUND); info.getResponses().add(response); repInfo = new RepresentationInfo(MediaType.TEXT_HTML); repInfo.setIdentifier("itemError"); response.getRepresentations().add(repInfo); } /** * Generate an XML representation of an error response. * * @param errorMessage * the error message. * @param errorCode * the error code. */ private Representation generateErrorRepresentation(String errorMessage, String errorCode) { DomRepresentation result = null; // This is an error // Generate the output representation try { result = new DomRepresentation(MediaType.TEXT_XML); // Generate a DOM document representing the list of // items. Document d = result.getDocument(); Element eltError = d.createElement("error"); Element eltCode = d.createElement("code"); eltCode.appendChild(d.createTextNode(errorCode)); eltError.appendChild(eltCode); Element eltMessage = d.createElement("message"); eltMessage.appendChild(d.createTextNode(errorMessage)); eltError.appendChild(eltMessage); } catch (IOException e) { e.printStackTrace(); } return result; } /** * Returns a listing of all registered items. */ public Representation toXml() { // Generate the right representation according to its media type. try { DomRepresentation representation = new DomRepresentation( MediaType.TEXT_XML); // Generate a DOM document representing the list of // items. Document d = representation.getDocument(); Element r = d.createElement("items"); d.appendChild(r); for (Item item : getItems().values()) { Element eltItem = d.createElement("item"); Element eltName = d.createElement("name"); eltName.appendChild(d.createTextNode(item.getName())); eltItem.appendChild(eltName); Element eltDescription = d.createElement("description"); eltDescription.appendChild(d.createTextNode(item .getDescription())); eltItem.appendChild(eltDescription); r.appendChild(eltItem); } d.normalizeDocument(); // Returns the XML representation of this document. return representation; } catch (IOException e) { e.printStackTrace(); } return null; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/FirstResourceServerMain.java0000664000175000017500000000344011757206350033525 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.wadl; import org.restlet.Component; import org.restlet.data.Protocol; public class FirstResourceServerMain { public static void main(String[] args) throws Exception { // Create a new Component. Component component = new Component(); // Add a new HTTP server listening on port 8111. component.getServers().add(Protocol.HTTP, 8111); component.getDefaultHost().attach("/firstResource", new FirstResourceApplication()); // Start the component. component.start(); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/wadl/FirstResourceApplication.java0000664000175000017500000000571411757206352033725 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.wadl; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.ext.wadl.ApplicationInfo; import org.restlet.ext.wadl.DocumentationInfo; import org.restlet.ext.wadl.WadlApplication; import org.restlet.routing.Router; public class FirstResourceApplication extends WadlApplication { /** The list of items is persisted in memory. */ private final ConcurrentMap items = new ConcurrentHashMap(); /** * Creates a root Restlet that will receive all incoming calls. */ @Override public synchronized Restlet createInboundRoot() { // Create a router Restlet that defines routes. Router router = new Router(getContext()); // Defines a route for the resource "list of items" router.attach("/items", ItemsResource.class); // Defines a route for the resource "item" //router.attach("/items/{itemName}", ItemResource.class); return router; } /** * Returns the list of registered items. * * @return the list of registered items. */ public ConcurrentMap getItems() { return items; } @Override public ApplicationInfo getApplicationInfo(Request request, Response response) { ApplicationInfo result = super.getApplicationInfo(request, response); DocumentationInfo docInfo = new DocumentationInfo( "This sample application shows how to generate online documentation."); docInfo.setTitle("First resource sample application."); result.setDocumentation(docInfo); return result; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/0000775000175000017500000000000011757206350025712 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/0000775000175000017500000000000011757206352026627 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/foafApplication.properties0000664000175000017500000000013411757206352034042 0ustar jamespagejamespage# File path of the root directory of the web files (images, templates, etc). web.root.path= restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/0000775000175000017500000000000011757206352030641 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/BaseResource.java0000664000175000017500000001656511757206350034101 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.resources; import java.util.Map; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.example.ext.rdf.foaf.Application; import org.restlet.example.ext.rdf.foaf.objects.Contact; import org.restlet.example.ext.rdf.foaf.objects.ObjectsFacade; import org.restlet.example.ext.rdf.foaf.objects.User; import org.restlet.ext.freemarker.TemplateRepresentation; import org.restlet.ext.rdf.Graph; import org.restlet.ext.rdf.Literal; import org.restlet.ext.rdf.RdfRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ServerResource; import freemarker.template.Configuration; /** * Base resource class that supports common behaviours or attributes shared by * all resources. */ public class BaseResource extends ServerResource { static final String RDF_SYNTAX_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; static final String FOAF_NS = "http://xmlns.com/foaf/0.1/"; /** * Returns the FOAF representation of a user. * * @param user * The user. * @param userRef * Its URI. * @return The FOAF representation of a user. */ protected Representation getFoafRepresentation(User user, Reference userRef) { Graph graph = new Graph(); addFoaf(graph, user, userRef); return new RdfRepresentation(graph, MediaType.TEXT_XML); } /** * Returns the FOAF representation of a contact. * * @param contact * The contact. * @param contactRef * Its URI. * @return The FOAF representation of a contact. */ protected Representation getFoafRepresentation(Contact contact, Reference contactRef) { Graph graph = new Graph(); addFoaf(graph, contact, contactRef); return new RdfRepresentation(graph, MediaType.TEXT_XML); } /** * Completes the given set of links with the links due to the contact. * * @param graph * The graph to complete. * @param contact * The contact. * @param contactRef * Its URI. */ private void addFoaf(Graph graph, Contact contact, Reference contactRef) { addFoaf(graph, (User) contact, contactRef); addFoafProperty(graph, contactRef, "nickname", contact.getNickname()); } /** * Completes the given set of links with the links due to the user. * * @param graph * The graph to complete. * @param user * The user. * @param contactRef * Its URI. */ private void addFoaf(Graph graph, User user, Reference userRef) { addLink(graph, userRef, RDF_SYNTAX_NS + "type", FOAF_NS + "Person"); addFoafProperty(graph, userRef, "name", user.getFirstName() + " " + user.getLastName()); addFoafProperty(graph, userRef, "givenname", user.getFirstName()); addFoafProperty(graph, userRef, "firstName", user.getFirstName()); addFoafProperty(graph, userRef, "family_name", user.getLastName()); addFoafProperty(graph, userRef, "img", user.getImage()); addLink(graph, userRef, FOAF_NS + "homepage", userRef); for (Contact contact : user.getContacts()) { Reference contactRef = null; if (contact.getFoafUri() != null) { contactRef = new Reference(contact.getFoafUri()); } else { contactRef = new Reference(userRef + "/contacts/" + contact.getId()); } addLink(graph, userRef, FOAF_NS + "knows", contactRef); addFoaf(graph, contact, contactRef); } } private void addFoafProperty(Graph graph, Reference subject, String predicate, String object) { graph.add(subject, new Reference(FOAF_NS + predicate), new Literal( object)); } private void addLink(Graph graph, Reference subject, String predicate, Reference object) { graph.add(subject, new Reference(predicate), object); } private void addLink(Graph graph, Reference subject, String predicate, String object) { graph.add(subject, new Reference(predicate), new Reference(object)); } /** * Returns the reference of a resource according to its id and the reference * of its "parent". * * @param parentRef * parent reference. * @param childId * id of this resource * @return the reference object of the child resource. */ protected Reference getChildReference(Reference parentRef, String childId) { if (parentRef.getIdentifier().endsWith("/")) { return new Reference(parentRef.getIdentifier() + childId); } return new Reference(parentRef.getIdentifier() + "/" + childId); } /** * Returns the Freemarker's configuration object used for the generation of * all HTML representations. * * @return the Freemarker's configuration object. */ private Configuration getFmcConfiguration() { final Application application = (Application) getApplication(); return application.getFmc(); } /** * Gives access to the Objects layer. * * @return a facade. */ protected ObjectsFacade getObjectsFacade() { final Application application = (Application) getApplication(); return application.getObjectsFacade(); } /** * Returns a templated representation dedicated to HTML content. * * @param templateName * the name of the template. * @param dataModel * the collection of data processed by the template engine. * @param mediaType * The media type of the representation. * @return the representation. */ protected Representation getTemplateRepresentation(String templateName, Map dataModel, MediaType mediaType) { // The template representation is based on Freemarker. return new TemplateRepresentation(templateName, getFmcConfiguration(), dataModel, mediaType); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/ContactResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/ContactResource.ja0000664000175000017500000001055011757206350034257 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.resources; import java.util.Map; import java.util.TreeMap; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.example.ext.rdf.foaf.objects.Contact; import org.restlet.example.ext.rdf.foaf.objects.User; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; /** * Resource for a user's contact. */ public class ContactResource extends BaseResource { /** The contact represented by this resource. */ private Contact contact; /** The parent user. */ private User user; @Override public void doInit() { // Get user thanks to its ID taken from the resource's URI. final String userId = (String) getRequestAttributes().get("userId"); this.user = getObjectsFacade().getUserById(userId); if (user != null) { // Get the contact and its parent mailbox thanks to their IDs taken // from the resource's URI. final String contactId = (String) getRequestAttributes().get( "contactId"); this.contact = getObjectsFacade().getContactById(contactId); } setExisting(this.contact != null); } /** * Remove this resource. */ @Delete public void removeContact() throws ResourceException { getObjectsFacade().deleteContact(this.user, this.contact); getResponse().redirectSeeOther( getRequest().getResourceRef().getParentRef()); } /** * Update the underlying contact according to the given representation. */ @Put public void storeContact(Representation entity) throws ResourceException { final Form form = new Form(entity); this.contact.setFirstName(form.getFirstValue("firstName")); this.contact.setLastName(form.getFirstValue("lastName")); this.contact.setImage(form.getFirstValue("image")); this.contact.setNickname(form.getFirstValue("nickname")); this.contact.setFoafUri(form.getFirstValue("foafUri")); getObjectsFacade().updateContact(this.user, this.contact); getResponse().redirectSeeOther(getRequest().getResourceRef()); } /** * Generate the HTML representation of this resource. */ @Get("html") public Representation toHtml(Variant variant) throws ResourceException { final Map dataModel = new TreeMap(); dataModel.put("user", this.user); dataModel.put("contact", this.contact); dataModel.put("resourceRef", getRequest().getResourceRef()); dataModel.put("rootRef", getRequest().getRootRef()); return getTemplateRepresentation("contact.html", dataModel, MediaType.TEXT_HTML); } /** * Generate the FOAF representation of this resource. */ @Get("rdf") public Representation toFoaf() throws ResourceException { return getFoafRepresentation(this.contact, getRequest() .getResourceRef()); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/UsersResource.java0000664000175000017500000000760511757206350034323 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.resources; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.example.ext.rdf.foaf.objects.ObjectsException; import org.restlet.example.ext.rdf.foaf.objects.User; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; /** * Resource for a list of users. */ public class UsersResource extends BaseResource { /** The list of application's account. */ private List users; @Override protected void doInit() throws ResourceException { this.users = getObjectsFacade().getUsers(); } /** * Accept the representation of a new user, and create it. */ @Post public void acceptUser(Representation entity) throws ResourceException { final Form form = new Form(entity); User user = new User(); user.setFirstName(form.getFirstValue("firstName")); user.setLastName(form.getFirstValue("lastName")); user.setImage(form.getFirstValue("image")); try { user = getObjectsFacade().createUser(user); getResponse().redirectSeeOther( getChildReference(getRequest().getResourceRef(), user .getId())); } catch (ObjectsException e) { final Map dataModel = new TreeMap(); dataModel.put("users", this.users); dataModel.put("resourceRef", getRequest().getResourceRef()); dataModel.put("rootRef", getRequest().getRootRef()); dataModel.put("firstName", form.getFirstValue("firstName")); dataModel.put("lastName", form.getFirstValue("lastName")); dataModel.put("image", form.getFirstValue("image")); dataModel.put("errorMessage", e.getMessage()); getResponse().setEntity( getTemplateRepresentation("users.html", dataModel, MediaType.TEXT_HTML)); } } /** * Generate the HTML representation of this resource. */ @Get public Representation toHtml(Variant variant) throws ResourceException { final Map dataModel = new TreeMap(); dataModel.put("users", this.users); dataModel.put("resourceRef", getRequest().getResourceRef()); dataModel.put("rootRef", getRequest().getRootRef()); return getTemplateRepresentation("users.html", dataModel, MediaType.TEXT_HTML); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/ContactsResource.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/ContactsResource.j0000664000175000017500000000725111757206352034307 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.resources; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.example.ext.rdf.foaf.objects.Contact; import org.restlet.example.ext.rdf.foaf.objects.User; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; /** * Resource for a list of contacts. */ public class ContactsResource extends BaseResource { /** The list of contacts. */ private List contacts; /** The parent user. */ private User user; /** * Accept the representation of a new contact, and create it. */ @Post public void acceptContact(Representation entity) throws ResourceException { final Form form = new Form(entity); Contact contact = new Contact(); contact.setFirstName(form.getFirstValue("firstName")); contact.setLastName(form.getFirstValue("lastName")); contact.setImage(form.getFirstValue("image")); contact.setNickname(form.getFirstValue("nickname")); contact.setFoafUri(form.getFirstValue("foafUri")); contact = getObjectsFacade().createContact(this.user, contact); getResponse().redirectSeeOther( getChildReference(getRequest().getResourceRef(), contact .getId())); } @Override protected void doInit() throws ResourceException { // Get user thanks to its ID taken from the resource's URI. final String userId = (String) getRequestAttributes().get("userId"); this.user = getObjectsFacade().getUserById(userId); if (user != null) { this.contacts = this.user.getContacts(); } else { setExisting(false); } } /** * Generate the HTML representation of this resource. */ @Get public Representation toHtml(Variant variant) throws ResourceException { final Map dataModel = new TreeMap(); dataModel.put("user", this.user); dataModel.put("contacts", this.contacts); dataModel.put("resourceRef", getRequest().getResourceRef()); dataModel.put("rootRef", getRequest().getRootRef()); return getTemplateRepresentation("contacts.html", dataModel, MediaType.TEXT_HTML); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/resources/UserResource.java0000664000175000017500000000766211757206350034143 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.resources; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.example.ext.rdf.foaf.objects.Contact; import org.restlet.example.ext.rdf.foaf.objects.User; import org.restlet.representation.Representation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; /** * Resource for a user. */ public class UserResource extends BaseResource { /** The list of contacts of this user. */ private List contacts; /** The user represented by this resource. */ private User user; @Override protected void doInit() throws ResourceException { // Get user thanks to its ID taken from the resource's URI. final String userId = (String) getRequestAttributes().get("userId"); this.user = getObjectsFacade().getUserById(userId); if (this.user != null) { this.contacts = this.user.getContacts(); } else { setExisting(false); } } /** * Remove this resource. */ @Delete public void removeUser() throws ResourceException { getObjectsFacade().deleteUser(this.user); getResponse().redirectSeeOther( getRequest().getResourceRef().getParentRef()); } /** * Update the underlying user according to the given representation. */ @Put public void storeUser(Representation entity) throws ResourceException { final Form form = new Form(entity); this.user.setFirstName(form.getFirstValue("firstName")); this.user.setLastName(form.getFirstValue("lastName")); this.user.setImage(form.getFirstValue("image")); getObjectsFacade().updateUser(this.user); getResponse().redirectSeeOther(getRequest().getResourceRef()); } /** * Generates the FOAF representation of this resource. */ @Get("rdf") public Representation toFoaf() throws ResourceException { return getFoafRepresentation(this.user, getRequest().getResourceRef()); } /** * Generate the HTML representation of this resource. */ @Get("html") public Representation toHtml() throws ResourceException { final Map dataModel = new TreeMap(); dataModel.put("user", this.user); dataModel.put("contacts", this.contacts); dataModel.put("resourceRef", getRequest().getResourceRef()); dataModel.put("rootRef", getRequest().getRootRef()); return getTemplateRepresentation("user.html", dataModel, MediaType.TEXT_HTML); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/Application.java0000664000175000017500000001551311757206350031740 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf; import java.io.File; import java.io.IOException; import java.util.Properties; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.data.LocalReference; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.example.ext.rdf.foaf.data.ListFacade; import org.restlet.example.ext.rdf.foaf.objects.ObjectsFacade; import org.restlet.example.ext.rdf.foaf.resources.ContactResource; import org.restlet.example.ext.rdf.foaf.resources.ContactsResource; import org.restlet.example.ext.rdf.foaf.resources.UserResource; import org.restlet.example.ext.rdf.foaf.resources.UsersResource; import org.restlet.resource.ClientResource; import org.restlet.resource.Directory; import org.restlet.routing.Redirector; import org.restlet.routing.Router; /** * The main Web application. */ public class Application extends org.restlet.Application { /** * Returns a Properties instance loaded from the given URI. * * @param propertiesUri * The URI of the properties file. * @return A Properties instance loaded from the given URI. * @throws IOException */ public static Properties getProperties(String propertiesUri) throws IOException { ClientResource resource = new ClientResource(propertiesUri); try { resource.get(); } catch (Exception e) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Cannot access to the configuration file: \""); stringBuilder.append(propertiesUri); stringBuilder.append("\""); throw new IllegalArgumentException(stringBuilder.toString()); } Properties properties = new Properties(); properties.load(resource.getResponseEntity().getStream()); return properties; } public static void main(String... args) throws Exception { // Create a component with an HTTP server connector final Component component = new Component(); component.getServers().add(Protocol.HTTP, 8585); component.getClients().add(Protocol.FILE); component.getClients().add(Protocol.CLAP); component.getClients().add(Protocol.HTTP); // Attach the application to the default host and start it component.getDefaultHost().attach("/foaf", new Application()); component.start(); } /** Facade object for all access to data. */ private final ObjectsFacade dataFacade; /** Freemarker configuration object. */ private freemarker.template.Configuration fmc; /** * File path of the root directory of the web files (images, templates, * etc). */ private final String webRootPath; /** * Constructor. * * @throws IOException */ public Application() throws IOException { // List of protocols required by the application. getConnectorService().getClientProtocols().add(Protocol.FILE); getConnectorService().getClientProtocols().add(Protocol.CLAP); getConnectorService().getClientProtocols().add(Protocol.HTTP); // Look for the configuration file in the classpath Properties properties = getProperties("clap://class/config/foafApplication.properties"); this.webRootPath = properties.getProperty("web.root.path"); /** Create and chain the Objects and Data facades. */ this.dataFacade = new ObjectsFacade(new ListFacade()); try { final File templateDir = new File(webRootPath + "/tmpl"); this.fmc = new freemarker.template.Configuration(); this.fmc.setDirectoryForTemplateLoading(templateDir); } catch (Exception e) { getLogger().severe("Unable to configure FreeMarker."); e.printStackTrace(); } getMetadataService().addExtension("rdf", MediaType.APPLICATION_RDF_XML, true); getTunnelService().setExtensionsTunnel(true); } @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); // Redirect by defaul to the lst of users. router.attachDefault(new Redirector(getContext(), "/users", Redirector.MODE_CLIENT_PERMANENT)); final Directory imgDirectory = new Directory(getContext(), LocalReference.createFileReference(webRootPath + "/images")); // Add a route for the image resources router.attach("/images", imgDirectory); final Directory cssDirectory = new Directory(getContext(), LocalReference .createFileReference(webRootPath + "/stylesheets")); // Add a route for the CSS resources router.attach("/stylesheets", cssDirectory); // Add a route for a Users resource router.attach("/users", UsersResource.class); // Add a route for a User resource router.attach("/users/{userId}", UserResource.class); // Add a route for a Contacts resource router.attach("/users/{userId}/contacts", ContactsResource.class); // Add a route for a Contact resource router.attach("/users/{userId}/contacts/{contactId}", ContactResource.class); return router; } /** * Returns the freemarker configuration object. * * @return the freemarker configuration object. */ public freemarker.template.Configuration getFmc() { return this.fmc; } /** * Returns the data facade. * * @return the data facade. */ public ObjectsFacade getObjectsFacade() { return this.dataFacade; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/0000775000175000017500000000000011757206352027404 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/stylesheets/0000775000175000017500000000000011757206352031760 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/stylesheets/main.css0000664000175000017500000000427411757206352033425 0ustar jamespagejamespage /* general */ * {margin:0; padding:0} html, body {width:100%; height:100%; text-align:center; font:100% "Trebuchet MS", "Lucida Sans", Arial, Helvetica, sans-serif; color:#2e3436; background:#ffffff} acronym {text-decoration:none; font-weight:bold; font-style:normal; cursor:help} img {border: none} th {padding: 2px;background-color: #555753; color:white; font-weight: bold} td {padding: 2px} select {padding:1px;} /* error messages */ .error {color:red; border: 1px solid red; padding: 2px; margin-bottom: 10px} /* container */ #container {width:700px; margin:0 auto;text-align:left; background:#ffffff;overflow:auto;} #container p {margin:10px 20px 0; line-height:140%; text-align:justify} #container p.p1 {text-indent:20px} /* header */ #header {height:50px; background:#66CC00; padding-top: 20px; margin-bottom:20px} /* quickSummary */ #quickSummary {color:#292f33; text-align:center;font-size:110%;} /* content */ #content {width:530px; float:right; overflow:auto;} #content a:link, #content a:visited {color:#292f33; text-decoration:none; background:transparent; border-bottom:1px solid #292f33} #content a:hover, #content a:focus {color:#3c4246; text-decoration:none; background:transparent; border-bottom:2px solid #3c4246} #content a:active {color:#d8dde0; text-decoration:none; background:#3c4246; border-bottom:2px solid #3c4246} /* menu */ #menu {float:left;width:150px; text-align:center ; border-right: 1px solid black; font:100% "Trebuchet MS", "Lucida Sans", Arial, Helvetica, sans-serif; } #menu h3, #menu li {clear:left; width:150px; height:30px; overflow:hidden} #menu li {list-style:none; color:#885c2f} #menu img {height: 20px} #menu a {display:block; color: #3465a4;background:transparent} #menu a:link, #menu a:visited {color:#292f33; text-decoration:none; border-bottom:1px solid #292f33} #menu a:hover, #menu a:focus {color:#d8dde0; text-decoration:none; background:#3c4246; border-bottom:2px solid #3c4246} #menu a:active {color:#d8dde0; text-decoration:none; background:#3c4246; border-bottom:2px solid #3c4246} /* footer */ #footer {height:50px; padding-top: 50px; margin-left:auto; margin-right: auto; clear:both; } #footer img {vertical-align: middle}restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/0000775000175000017500000000000011757206352030360 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/user.html0000664000175000017500000000352711757206352032233 0ustar jamespagejamespage<#include "/header.ftl"/> <#global content>

    Update a user.

    <#if user.image??>
    First name:
    Last name:
    Image:
    ${user.firstName} ${user.lastName}

    <#global menu>
    <#if contacts??>
    <#global foafAlternate> <#include "/footer.ftl"/> restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/footer.ftl0000664000175000017500000000227011757206352032366 0ustar jamespagejamespage ${title} ${foafAlternate}
    ${content}
    restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/contact.html0000664000175000017500000000377011757206352032710 0ustar jamespagejamespage<#include "/header.ftl"/> <#global content>

    Update my contact.

    <#if contact.image??>
    Nickname:
    First name:
    Last name:
    Image:
    ${contact.nickname}
    Foaf Uri:

    <#global foafAlternate> <#global menu> <#include "/footer.ftl"/> restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/contacts.html0000664000175000017500000000266011757206352033070 0ustar jamespagejamespage<#include "/header.ftl"/> <#global content>

    Create a new contact.

    Nickname:
    First name:
    Last name:
    Image:
    Foaf URI:

    <#global menu>
    <#if contacts??>
    <#include "/footer.ftl"/> restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/users.html0000664000175000017500000000201711757206352032407 0ustar jamespagejamespage<#include "/header.ftl"/> <#global content>

    Create a new user.

    <#if errorMessage??>
    ${errorMessage}
    First name:
    Last name:
    Image:

    <#global menu> <#include "/footer.ftl"/> restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/header.ftl0000664000175000017500000000051011757206352032313 0ustar jamespagejamespage<#import "/library.ftl" as lib> <#macro listToString list separator=" "> <#list list as item>${item}<#if item_has_next>${separator} <#macro concatUris parentUri relativeUri> <#if parentUri?ends_with("/")> ${parentUri}${relativeUri} <#else> ${parentUri}/${relativeUri} restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/tmpl/library.ftl0000664000175000017500000000023011757206352032526 0ustar jamespagejamespage<#global title = "FOAF" /> <#global menu = " " /> <#global content = " " /> <#global foafAlternate = " " /> restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/images/0000775000175000017500000000000011757206352030651 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/images/blue.png0000664000175000017500000000474411757206352032317 0ustar jamespagejamespage‰PNG  IHDRJJÐÂqsBIT|dˆ pHYs × ×B(›xtEXtSoftwarewww.inkscape.org›î< aIDATxœíœmlÇÇs>;ÆÆà° ½à#C‘0Jx ¤Å$5ŽJJJÊ—UHjhT¤*H Ž*µ¤€@ Rù¤ $L…H†Ú"5pumƒÏÆÆØ&~~ص㻛ÝÛ=ßÁ™ø'κyf晿gggvæY!¥ä^"„p“€, [ÿd ø¨j|÷ý} øJJÙ}Oý¾B !\À3Às@!0vEÞŽG€¥”mƒ,/$QJ‘ üX ä‰Q©¾NGJ)£R‹”2¢`° hä=þ´êuŠx»"(P<°¨¿~êu_â#Õ¾A_zB,Þ<öó;1*WJ:#SÒp¥¤ÐÖ죵¹¶fwï4#eo8îU¯%r ”PB7p˜k5Orj&žY ñÌ\ȘL7®Ñi8q¦yz{{h»Ý@S—ªoOSõÍiZëì¸Z¬RzídHØB !¥@z(Ûô‰à™µˆÉy‹ÈpO «¾@꽕üçâ§T}ó)¾êï¬dñˤ”gé/,¡„«¿ fvîŸÎã‰_ý.bâQï­äóûñ^:Ê´ø­”ò]»uØJüØ`f—ážÊÏ^ØÀO¦Í±ëÏ øï¿/ðÙ;©÷V†2Ý üAJÙcµlËB !F?7²INËbþ²uäÎ-!¬úY¤¤¢ìçJ÷ÒÒPkfù/à)å+ÅZJïIÇÐf×Jpÿ]•æŒO`ñª-äÎ[ªžûJÅùãœÜ¿•î®N#“5¡xS¡ô)À'(înIÉcYúÊN2sfØpùþQwµœ£»6ÐÞrK•Ü VZèríûä¦úY}éLQ›2îáia-œS2&èm˜žèMJÆÛå"„æ“MFŽQv’Èõ¨„.Iˆ 5~H Úžeoú‚ü¢M$º’-Ûg¸§2çÙ5!íæ<»ÆÖš3Ñ•L~Ñ&ËöVp ´õ£­ÙVa®”4ž^ý:΄ÐÇ5GŽÉ à¥bK7 Gœ“‚—Š9&#¤­3!‘§W¿Ž+Œá Û^ë@;–ìGksCX•Lžµˆ¢í%dO™eh3íñBV¾q˜Ô¬Ëå¦få°òÃL{Dû­~jîS_sŸ.Ï •¡~ l•R6Z©4%„x¨ÒÃÉf.KÀ]˜Š»0—;1¢þ‚á©ï¥þÂ}ê/tÑòMŸ™*íÀf)å‘ôQBˆÀ_€X#¹¥?Kæû³'=xê{9ÿçf®ÿ£;œè ð²”ò]«}X"J~o$çr'²þÙä=—lu<Â/º9÷§f<õ½áDßþ ¥6Û¶i¢„ó€"=™Ôì8Šöf±rcÂØìL¤„KUTºCWó€‘h5P,¥|h¦]SDùŸ¤³h«k%Ü)l;º˜X§ÍL¿SŽAï'÷Ü¢¾æ¾‘Ø`ƒ™'ˬV‡1 iÍîL¶¿³dÆë´±ý%¬Ùi$Vˆ¦[X„}¢ü†û¯ª2{œ-sXµ)ÍL_ u§;¨Ø×ˆo@w1ö›pÞ(ÿàï(ÞnIiv~õn¯rZò£Ãí:/ïí¸AO‡òÐaø¹ÑÒA—(ÿbòkë${œ]þ0jHÅí:/ÇŠ¯é=YíÀSz‹R¥QñoKN¡³˜Ür0'êHx|•“-sôŠÓS~ÝC g}· ³-Y³;sÆÛ$#¬Ú”fdàŸEÓ=!SOá¾A±Áu¤°ý%l4YÞÿí·zK‡›À2)åÐø/UOÔN$¥fDZíèâ¨' @Øvt1©Ùqªâ'Ð8@QþÕ÷Uí¢½Y3j4QÄ:míÍÒ+>àçb ÁšïEaÀ]îDVnŒ^»¤‡•Óô6ìéh\ŒaŒ(!D:P¢ªµ¾4{VL¹`¡é¦ƒ?'@àõòÎÏ{>™¼ç§÷`:a Ÿ ”¨0>k` c Q~¿ÛÚ`©ì‰“rèæ”Œ O¾[ldXâœx».w"Ù+”z®õsƒÝÿE! ¿[~AjÄ·^ïãŸk£é²—»ÿéÃæ¸–'’³:‰vfôGDíöÜâ³ã­4þ»ÏÕ^F†$‹~”ÀcO:ù鯒±4!¢vó Ri¾ràÆM¥R"„xøe°Ô«Õùdæ[{¢F†%Ÿoåã#Ý_Û¹ÀÎæòV¬·öC\9×Eei#ÞNµ7Ý+XWââ…Øb¬½}Zzy£¨AUtBJ¹ÝæØ\šêеL@åþFοÞl8%¼>NìºÉÅÚM·{ñƒvN캩KhSüüëÍTî·îlÉÌO$Õ¥tlBØmÀ3(bò R,wvíÓ|uêžiù3¯5ÑÙdx\ @gÓg^k2ÝîW§îqíÓ¦åG¡£óà ÜN篵NTeémKòƒÞΔ…'àLYƒ^kP«cCsl|f€…K¬ÅTt5„;ÌWâÖ¿btÈ*¥&c‘ŒÇ@ç,ZLR„€¤tko¥¦Ëa]DJôuÓñ]¿nyÇwýôu›ö*MhLI齈KI”s˜0nî`<¸kÉÅTw(¢²ðíZSŒ]à\`W¹”S/y‘¡X‰¬e‘/L3—é¯}ŒÊÂ!’1ÍËPꮞzÉ ­/]?NŒh㜖GbŠòW 1ÅNZŽòÜÈBhc²ŠùJÝuž(µ°!â“bÈ_gýM¹zsøã32ÁÈ_—B|RŒåz:ºgMêIܦò曜ËÈ‹¯:(xñ•LK{΄ù1l*×u"DZ¤mº[#3 É ÎÅ‘žÿù‹bÙúV®©—FŒ]°õ­\æ›°ŽŇs#2 «ûZXr p[äowa %5nrŸNÒ•Y½9’Z7yæ uF^%µnÃi˜ût%5nÜ…ÖMÀ(¨‰ò´•MRšu+#î @Ž@Óe/ž«½x®zqÄÛp-Oä±'ïðGÑz½o¬í¡þ\Ëcm‹ “²U—TÞä ;Š'ÊÛécØ'-¯¥ÆCØ4‡£æ( ”g KÈXšÀO”¸È1ì“z›nrêI =í‘O¿hEOûÞvÊ£4æmßêo+f+ t¾c”‡7 µ†X³:7Ú€‹h¹%•Œ#Õf%ttî.ÚüYJgƒK»<ƒ´4Dv"hièÕ‹]?+¥ô¾L«Tõ[?%ŒVèZßûõ. e) ¡¦kjF5¡£k?7Qþ|·Ú`©æ+½fb¶£žú^•«  v4pü:ö#•ä¹òæ)ÚÌ‚Žcœ’Iyãónn|6u"ja ŸQRÊvàˆªÆ¹òfC@´BJç鈟 4>êZtl<õ½\ªšš ÔG‰KUz6¸‹1åÏ )SÕ¬>tDzom&cÐ;Bõ!åî  ,8GFu(q-à3]ÍœÜskVLA)áäž[z~¿›h „(4l©ª…úšûT 9lˆ:Tô%•Gƒ~œyZzi>y»…ºÓÑk¯êNwðÉÛ-zÅ_¢é%QþDå­( ;@žFn×Mù “ŽÛu^*öéFº´£å+‹îÁ©?'d3ZBM|#¼·ãFT‘5š4¤“3ˆ–o¬Ë¢á ³?ÛèeUYO‡cÅ×¢bÖîàXñ5½Ì*ÐòŒ “²Íf€¾AñšÝ™ís͸k)5Ãm`“Þ”R¾®­¹TY“©²sÉד™|=&<—Îo sDX©8w刅Ês—ØXhàÿäZ¤¹‹¶¦ûF²q„ÍÊ«Ûæ.4‰¹ë%MbZˆ è0J/,ý·YW|xH;¼IEND®B`‚restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/images/back.gif0000664000175000017500000000014011757206352032233 0ustar jamespagejamespageGIF89a –€Ó×Ïÿÿÿ!þCreated with The GIMP, –&„©Ëí£œ´Ú‹³Þ¼û†âH–扦êʶî ÇòL×öçúT;restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/images/yellow.png0000664000175000017500000000503711757206352032677 0ustar jamespagejamespage‰PNG  IHDRJJÐÂqsBIT|dˆ pHYs × ×B(›xtEXtSoftwarewww.inkscape.org›î< œIDATxœíœ}L•×Ç?çÊ‘E.(QãtU‡ò2‹YÌl©šNe›ÙU²®ÉÙ:W330JºˆëšêÖH3Ó®568_fÄ•¶º˜¦hyv­V ˆ¼8… ÈûÙÏE¹—ó<÷y.Ê'¹Üó;Ï9ç{Ï9ÏyÎùý!¥d(Bø‹Y@40Íù‰îó ¸Õçoïÿ×KRÊ®!­÷P%„V)Às@ø/y8 ÎJ)[x= šPBˆÉÀO€µÀr `P ‚6 8üCJù¿A)EJéÓ dÍ€âO³³ì`Ÿ·Ë‡ÙßõA ÷O½³.v_µoÀCO!€ À.`¶Õü6›`Jøx¢DE©Ðšº6n×µq»¶;w;èéñªž×€íÀr€ PBˆÀ`‰Ù<3¦²f•ƒÕ+Ì=ÇÔüü„až®.Im}_^kæÔÙZNž©åfu«•ª~üTJyÓJ¦¾x-”b)p ˆðd;)«¢X»*ЏØ¯Ês§´¼‰gnsüÌmÊ+¿1“¥X'¥¼àMy^ %„øð0ÞÈîÙ§¦’½c¾ÏÄÑ£´¼‰Œ?Vòá¹zO¦Àf)åß­–aI(!Ä8àMàwFvq±!ü)sÏüÐcgó)ý»?dUPZÞäÉt/ð{)e·Ùk›J VêÙÌŒ $+c×MGO;ƒ†”pøX5™ÙW¸Qe8åÏK)®)¡œ=é4ÚêZÉš•rs™äg¦ÜA§¹¥‹Ô´"Næ×™ž3Ó³l&Ë}‘Ò·Ì!ï@Ò° `by’Hß2ÇÈlZÛ<â±G9'î÷Tiþ6öï‰ç…õÓÍ”õØ8”WÍ/_-¡­½GÏäeO¼¡PÎ%ÀG(înS§øsü`O&„Y¨òããbñ=R6R§]•ܧJ:(¥Lh½ª·cîÓ¹Vô¬¥Â^z¥˜ƒG«LÙ¾½{!›_šeÊö÷¯óJz™)ÛMÏÇðþÛ ¦lû2;ñCÕéÎ] Ò$¡ðXíŰ;SPgZ$€ô¬ ¾¾éÙmàë›-¤gU˜¾îÁ£Uœ)¨3mß‹N›Ã$0C•úãYÊì/ÞKKk7Û^ó,À¶×*hi5}àU]À°Í3l™ùsƒumÜ™?7˜Ëç“yÑ`.]2™’sO³vU”¥:÷¥¦VÙö[ÍCÅåˆfêj*tVLÑÓ#ù¼´‘â²FJÊš˜0añ±!,ŽcþwÍ ¤¢ò¿÷¹Tr’ò&<è&~a Cù~\(6ÛÀ¶b£ä«N“?ÀÜü„€ÖªÕ–×R#ÎÎcN©žö*‡ž”P× <£ÕÔ5´ë=NÝRNæ_|Õ<˜u–´¹Æ(þù/C¬Q‰A›oÚ€B´Í)N{ªJtÚ|(´9£”N»§Þ¬n¥¬Â£Ó訡¬¢IÏwý´”²«÷¶v\eqòì·§W´õ8<:×;‹¥äšù[4ütÚÚ†¦&”3Þ­Àݪør£ŸíOiy“ê¨   7°ïŠò„Ê2ýuó›ú#ƒ6>ÔÄ]¨~{²ç(8ßàÛš # ÚׂJ()eð–*Gúë†#) {Ó[NM€þþQFóŽu¡´¼‰ÃǪ}WÃaÂácÕzspšqÊ’¥Ê™™}…æ–! Tš[ºÈ̾¢—œå#£ÚøšÃ§ 7ªZIM+CPJHM+Ò;÷»†¦ ý„rzÃnW]ád~-;³+ZÏÇÎÎìJ£5âvw`Љ\p:¥ŠŽ¯ynNâˆõ5?”WMjZ‘^ògÀTñÇc!°âà̰- Æ…¶öR6r±øž—Uzzƒ†tDê@‹7Ö Î6ÜëuFmV¥Õßi'9å‡ò†ÿ²áP^5É)ô"«@‹36 Êö¸)îŒcÛ«Jkkï!5­ˆ»*‡åÝPJر«’Ô´"£X½½f‚±ÇBe}*ë¼Ð´€e%'ók‰[ö ‡òªkï’RjqË>ñ$R>°Ál¤úX8¿IÆ^a’±WŽ˜dì%6&{-’YÆ^´5Äo$ë#ب|uÛØËM2özI“ ‰P.ŽÐ–þ]nŠ29=IEND®B`‚restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/images/foaf.png0000664000175000017500000000426111757206352032275 0ustar jamespagejamespage‰PNG  IHDR2sT}DsRGB®ÎébKGDÿÿÿ ½§“ pHYs × ×B(›xtIMEÙ .Ž™1IDATXÃ͘{pׯ»Z=lK²dIäÄ8¼š`˜$@J›dH! uC’!%3é„64%éÒ¡hšòÊ´ ¥qêÊ(¥P’PÂ+`ŒÃË` ?0~€±±ä·e[–´Û?,„ ¶±ÛN§ß?Ú»:ûÝóÝsîÙszÇ8`- ´à°XD28Üæ;ׯø2Ègä?„pר |Ì3DÙ…øqbŽv"©µ´·4PSv‰ò‹9ü¾ààãûð[Àó¦<3[¼I'â©÷s=ÏCѱ&J°ÈøoI†ÌqÓÒFòä§EÕ=xݜؽ‘KY»þ\Q¹îDà Þ*9Ÿ^Ë„¹Qˆ*á£æ[>¾Z[Å™n€MÀûàëªn+wÜêHŠK_ö)Ž‘±×4ºp&<†9ÚIéùc+Šì%Ç£“Ü‹v%—ªG…^ù´z)³LXãt\>Øø°"LÀ$`"(@ýý„d†ÌiéË2Ñ›‡ h¬ŽDtFÊòOLŽeÝþÞ¬·JSíJÆhWˆ/ú0t‰¢£MS€'€…À÷ùÀâàØ \ÚïN­±@Þw^]!¤¤=3¸x* ÛV¿Bui~0µÛÆ>Ÿ¾>NxèyË`éøhÎꋽl\3މÌØ,Ú;]måÿ¬fó¶JZZýnà•`±EämƒÙ>uÖ«ï†ÒÉu½„Ë9_ Ö†iíšD–)<¹›%yXbâQIj:<Í4¹nP]z1Læ›b4IóÖ8CéT}¹Ü]uhÂE ¶®É…ó{ê)?ëÁž†J- ¥æÌ.7ïÿ*…ĸt:½„sx8ßagáü”–{ KZÓk@>€L?-´±›\Ul[õ2þN/9j Vþ “=–œ=àÔçŸP’{˜ˆH+E§@Àϵ“JõC,s­³“䙑¡]WéåÃ9…ø:d¬yëP –Z¬»É‘«(ÎjbAF"L7"i¾>á&ÞqOԆشìÌLå§ËòU3Ë2ƒbr$`TÔPgÈÐUY„¿Ó @À×Ime!&{,Õ¥ù!›Ê˧‰–$Þ³Y™g4bVÝ©nÃŠŠ°%èBã›mø:ºŠß+s³  Ë-çZC6¹žÐµ¤19´_mí»Ô °aÕÎ_lRs¦>+a*µ&d;:³}8¦!†žÀ˜GŸEFí9£‘Ó ¼f6÷Ð!ËHÚ;/iª«S €Å©%1­ëÝ7é[(j¼dëÁ¡ÖŠ´wú/·*V Ì–W{kãÐP9 ÓóòÊ¿RWUŠeX’ºË »3I­a®N昄>&°HmõþÐXgT±ä` 5EØGêPëºDŽÿ^Ήz|2¶x]ÏwU½ã'먬jgø°0V­+â‹5Ìy*š_¼9€‡Æ™Hý–™Óçžs5× zIj-vçè€c;6#ûÙ0thŸ"ÆétT^ðôäÓŠ8Ɔ‡D܆)Fsˆ¦êNšoù¸x¹™wVtùõu¶‹k ɽÐÈò÷®}².dÿøT+Àø²âRžFWŸÎ5×Us-ïKm6ÂÅ;Îxd¿¢ô°¥×S|´‰–Zß¿ÕjœÝyÇIŸ_þöœ£ûØ+[~_ÉÝû$/ËÏ&L˜c¼ÓÛ­q»QTDÊÕ«\êè >ೆü _­«´ˆV·¬ŒlV-S'Yøõ/GðíÇl,~-xgK^O¼…лPD Xz)k…§ö÷:Amù’µZ„®¤ò) kÜn@­ßϦ†v57Sàíªx§·»¹°·~À">…m‹Ë0j%.ŸÁ±½i$%èEõ+¤øÔüöÝ„n¹]y£  âvždïÏXNÞá!™·ÑÞÚˆ¥[u’‡úNë¼vv»'(°ýÍ2r>«íê’î‰Ì%TåzØù§T¬Qš/Àá,@v÷Ú¹OQ䈲üìÉ'…0£™Hë0DQEéù£hk+x!22Ô×<¡×ƒ ðŒÁÀO,T‚@‚FCœFƒU¥b•ÝŽIùó¾J²›‰°HDÅj{tÀÍ·|œØ\˶ÅeÐ ³wë#LI°ˆã'ëxÿw%Ëz+@3•ÀdI­Åh‹¡£µ S[3IIƒÎûc«\.ζ·£ÖŠ˜‡kPk»Î#ՠङ©Ì}:zÀ¼ÞN™)OfqáRS.0±¿JšÌF1@ú‘¸8&ètƒÓ"ËŒ*)¡]–w7àÎYÀ߇ÑN?²'‘Á}Ñü……oœã/»n´S€ÇÑcCwGi¹‡-Éãè ·˜|ÞÛQ·?¼lÝâp0Û`ðC…^/3ÊËi—åõÀ[ý˜ƒGçôñF²àÃ{mãwÏ'W/Ù}Ùï‡­á¢øâV‡ƒé÷5.éìä¹ÊJ®û|瀴»C}àqà `Ð=Ï ØÜÖßLJûAlWÁÜ×£¢XbµÞÓ4x…OXírÑ*Ë‚NÕr.upÚ‚ PÜßQW`ðŸËÃE1b–^ÏX³(âQ ½^ö·´àÀ'ÀÛÁO@ÿ·°sþà ~«j¾ –ï¤ÿ¥3ÿÓßìdg#kIEND®B`‚restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/images/red.png0000664000175000017500000000460611757206352032137 0ustar jamespagejamespage‰PNG  IHDRJJÐÂqsBIT|dˆ pHYs × ×B(›xtEXtSoftwarewww.inkscape.org›î< IDATxœíœlS×Ç?×yŽ_®›‡Ø¤ Ð2è:„¨ÚN›´nH‚Ô ÁZ¡m¬Z&¤U]·?¢”¢ý±1†D¥j™º?64¡1*-PT6&­]W¡.bë6Jih0‰M@nbò›Üýñ^Blß÷üží„8ÍW²ùžûã|}ß}çÞsÎRJfB xhbÀë›ò \òwâÿËÀ{RÊÜŒŽ{&ˆB4€¯À}6yèN§¥”é Û+‰i#J¾<¬ôié à ð:ðG)åдô"¥¬êû€@ÎðgÄê;Xu½ªHø¸ ~ÖXüÕÒ¯âGO!€mÀO¼Ö÷aM£EÓX¬iD5 €k¹ƒ¹¹C¹ãå ï° è–*ZQBˆeÀQà1·uî÷ûÙ ²qáBVÔ×Ó¬ihB8ÖÉII"—ãâØ§FF89<Ì'Ù¬—¡þxFJÙç¥ÒT”M”âKÀq RJöá@€Ž`Ž`v½:kz¯aÐ3GZ[Ù;‰mÀÔ­$JÎ(ká~MU‚ÃÑ(ÛB!7}Ý5t§R ’–úýtÅb5O€ºb1–úýªâ09ÈCQ–õ½GU{w$2«ì¤JÑèó±;b»Ÿßcq1‰BÍŒbo×u¶Öðºd‡­¡Ý†=‚ÉÅ$&×(!DÓÃQ´“=¾t)OÌðw¦p6fË•+ª¢4Ð&¥LBþŒz IO46ÎY’ÀQ¿FLN€b¢Š°·¹¹º#›…pÐ1Ÿ(Ëï¶¾Pj®WåÐ-#%®~<à¶Õv¥h×uÖ¨õ\oqƒf}±…ßmS0Xø•k|Éðë›79?:Ê¿34!X­ë¬Óuž ‡iÖ´Ò(Èå8<4Ä9ÃàŸ†ANJ>°¶¡ï55ñP PV»›‚AÞ/>ðÓ1¹9.¤”!~ |»Pêomm|ÁãŒÊJÉ/‡†øÅõëŒÙüÚMuuü¬¥…­÷Üã©ícŸ~ÊO¸y[=?ë…àG‹±3Æ_ÂaQˆ †Á—/_VýNJù9«)psßï÷Óûàƒž:Øs4•r%{ ¥…g›š\ɾvó&/ ¸’}&âÕX¬´`Ú?üPåݹ,ö¢ˆØXÆc÷æÈˆk’ö$|ìÂíôq6ËžDÂu»GS)Þq-?ïõËT¥O.\è¹#·¿øn³{p°¤ÜîÁAn{sz 8ê¼ÌÇ0›<¬¬wôDáJ6[ê0_‰·nÝÂé½%-¯(g<:Ç|˜1Iy˜'˜^p~tÔ“üR·oóÑØ˜mùGcc¤lïj)¢iv›þ%J¢išç·Æ5õkÅu§«]üB°H=A–(½–2l¯fÄT<ì`û8••B9cZ¬Ö]ýèÙ;b®—uVÕV_OS]myS]m×K0—kÛ6“D=£¢eôùÊ2)žvq|ãF¦ƒA‚eœŸÙè«êIÜÁ–îu˜…h×užwvPð|8ìiÏyo][Z\Ë»3Ò6å. ‹5W¢Q\ü’QM£+sõÒð AW,æj¦7ø|¼–µ|€­îqfXr+xÓtƒ¼ÝÖÆã ØÊ< ñÎòå¬ô°P¯ xgùrÇÇðñ x»­Ž 6ójݯ Ì•<MDÓøßŠew0ŽiÇôZ»|Ýçcµ®³V×YUÁ› à?™ ç­vñqV[ÇAk\SØás/ª¼ÉÝŠu=—#+¥g[j*|˜Çép”® X°½ÊçøY)¹n3£”ž;ýœF2—³ÛN]U.æÿuØVÌU8è÷Ê „7Ê8¦¨u8èÜçÞÅ<œÊÃ)çHµ9 oïú¬,¥žÂÒO²Y.”3¸`v±ë=RÊÜÄÛô„JâÔgèñsÐõÜñëÆÌRÊC‰@Ñ9] LnL¢¬|·3…R˜íšG¯a¨\Ug&r§²¯«$÷z8Ô¯U8è8ÉI!QE9gÓiΖN¨Y8è—FE”µqPUco"áè¨UHgÓÁ‰H(Žú9ftlz ƒcüuµ‚c©”ÝœÄäbyDYy!ûT5÷'“¤=úÖf3ÒããìO͉ ì+Ì‘QJü 3à3W²Y:ãñ9ñJ 3·óû]Âä EDYѰ»T-œæå9ð|9‘p²wFƒMæ‚”þwlbÍ»b±š5ïN¥èŒ+LÀL©ý¢*ÿx>Åã¼§xX¶`&Ôä!#%Ûûû9W¦ýn`"iȆ¤1Ì|cÛälÇ#f+Ûh‡ª,™Ë±¹¯î0ºS)6÷õ9Úî(•”]ò,ÞÊc;¤*ËHIg<ξYjJ`_"Ag<îëyÈM2ö|ª¬ËTÙùäëj&_O ϧó{Ãü^*Î_9â¡òü%6øŒ\‹4ÑÖLßH6…°9yuÛüe€.1½¤KÌQyÖè…¥ÿiÁOá⇠IEND®B`‚restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/web/images/logoNoelios.png0000664000175000017500000000306011757206352033647 0ustar jamespagejamespage‰PNG  IHDR$$ᘘbKGDùC» pHYs  šœtIMEØŠto½IDATxÚ͘ql”åÇ?×ö{´8® !(T¹),&,(TKd M#sV±†¢afÀbè’mNViN‰@2É’iDKát£“„†§„JA«Ò:)”k¡Úž×ö®wíÝõ½ûîÇ„®ô¥“ñKÞä}Þßó<ù¾Ïïûý=¿çqH7eŒz†Xç (Ñ ÿÞ ¾µ€L;Ü éÔÿ И\˜óKÈM›vîd¸pNï¥íÏ©«Ù@¿”¶†ï“ŒI;J¿ý-Þ^(EÎËŽl…>N}ÉØÐ~§Üy9ñ04ì‚¿¯„Aý»Ðñ9F¬²Ð)h®1«´yðöBˆ} c'Œ’CDÚ ØÝÍ B_¬8¤ # œÙpÎS aúOÀ3²\xöx3ÏžÕÿüðñë@j€ƒ[`Â0ãg—¨³ û!à ýÝ`%`A…%c†Ð¹“ìÊʾR y^ól/†æpï ›¤¶hÿ+ˆÚäÈ0a¼ÜÎ~gk Ï22m’Úí!è]ÂDßZÈtÂíóáÖ¹{ àPÚ\F_™ixßìm³ž2™|Üû‰ñ‹3wþCŒBK ´~ ÑH%ÀñÍf: /Ò–@ûQ£´±`Ü­0énCòi…5¶Ì€ÇÞ0¤·#û3­mÌM§LÚ¿s‘y.µTúMx”6*sdÀ?טÔ0y–‘w2f¸˜5Îû±ÂÈšzŸý|•õ ùl~ó=rrrFW1ƒAýbÉ£:ñÚ©÷Âà÷h4ªÊ×ÿ¨SÇK©SQþåaioÅÅÁ:óÒ]zæÑù:}ú´Âá°ÒéôU+Æaõõõ©½½]+žyJUÏÞ¥Ô¾ Ú·÷-Z´H7nTqq±šŽ–j¶HHmuÒ9¿ôÞÓÚ»r¢Jÿ©ÇuìØ±•°ÃŠD"êèèP<×[·ê•Õ+TPP ªª*IRmm­žxpŽºŸ%½x“Ò¯ÎЗ«Æ©ìá™*/A¡PH–eiÛ¶m²,kô€$)(H’*++UTT¤ÎÎÎAÿîÝ»µ¢ènýá1¯/œ£ß=¿Zuuu’¤X,¦ 6¨­­mÄE>#éä÷ûU]]-IÚ¾}»Š‹‹URR¢'NèÈ‘#òù|ª®®V8S__¯åË—8T¶IÒÑ£Gµyófµ´´¨±±Q>ŸOË–-ÓŽ;¾Õ¯©©IëÖ­ÓâÅ‹uòäIÙ5ìt…BZ³fÖ¯_/˲”L&•H$ýÍÍÍ*,,TEE…"‘ˆ®Ål\=›6m"//={öàt:q¹\ƒþüü|JJJÈÉÉ!77÷ú¥—.]ŠßïÒWVVÆñãÇéêêº~€<^¯—`0x…/;;›òòrvîÜy}/JKKñù| µóÌž=·ÛM$ù.†±žžÕÔÔ é³,k0Ù±QŸ:+„!~‡Ãa¯,¿Ñ®ôþ'ñ)Ÿ×)IEND®B`‚restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/objects/0000775000175000017500000000000011757206352030260 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/objects/BaseObject.java0000664000175000017500000000312211757206350033120 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.objects; /** * Base class that supports common behaviours or attributes shared by domain * objects. */ public class BaseObject { /** String value that identifies one object. */ private String id; public String getId() { return this.id; } public void setId(String id) { this.id = id; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/objects/ObjectsFacade.java0000664000175000017500000001127511757206352033606 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.objects; import java.util.List; import org.restlet.example.ext.rdf.foaf.data.DataFacade; /** * */ public class ObjectsFacade { /** Data facade. */ protected DataFacade dataFacade; public ObjectsFacade(DataFacade dataFacade) { super(); this.dataFacade = dataFacade; } /** * Add a new Contact object in the database. * * @param User * the parent user. * @param contact * new Contact object to be added. * @return the contact object completed with its identifiant. */ public Contact createContact(User user, Contact contact) { contact = this.dataFacade.createContact(user, contact); user.getContacts().add(contact); this.dataFacade.updateUser(user); return contact; } /** * Add a new User object in the database. * * @param user * new User object to be added. * @return the user object completed with its identfiant. * @throws ObjectsException */ public User createUser(User user) throws ObjectsException { user = this.dataFacade.createUser(user); return user; } /** * Delete a contact. * * @param user * the parent user. * @param contact * the contact to be deleted. */ public void deleteContact(User user, Contact contact) { // Remove the contact from the mailbox's list of contacts. boolean found = false; for (int i = 0; (i < user.getContacts().size()) && !found; i++) { final Contact contact2 = user.getContacts().get(i); if (contact2.getId().equals(contact.getId())) { user.getContacts().remove(i); found = true; } } this.dataFacade.deleteContact(contact); this.dataFacade.updateUser(user); } /** * Delete a user. * * @param user * the user to be deleted. */ public void deleteUser(User user) { // Delete the user and its mailboxes. for (final Contact contact : user.getContacts()) { this.dataFacade.deleteContact(contact); } this.dataFacade.deleteUser(user); } /** * Get a contact by its id. * * @param contactId * the contact's id. * @return a Contact object or null if no contact has been found. */ public Contact getContactById(String contactId) { return this.dataFacade.getContactById(contactId); } /** * Get a user by its id. * * @param userId * the user's id. * @return a User object or null if no user has been found. */ public User getUserById(String userId) { return this.dataFacade.getUserById(userId); } /** * Get the list of all users. * * @return the list of all users. */ public List getUsers() { return this.dataFacade.getUsers(); } /** * Update a contact. * * @param user * the parent user. * @param contact * the contact to be update. */ public void updateContact(User user, Contact contact) { this.dataFacade.updateContact(contact); } /** * Update a user. * * @param user * the user to be upated. */ public void updateUser(User user) { this.dataFacade.updateUser(user); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/objects/ObjectsException.javarestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/objects/ObjectsException.jav0000664000175000017500000000333211757206350034231 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.objects; /** * Exception dedicated to the Objects layer. */ public class ObjectsException extends Exception { static final long serialVersionUID = 1l; public ObjectsException() { super(); } public ObjectsException(String message) { super(message); } public ObjectsException(String message, Throwable cause) { super(message, cause); } public ObjectsException(Throwable cause) { super(cause); } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/objects/Contact.java0000664000175000017500000000337111757206352032522 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.objects; /** * Contact. */ public class Contact extends User { /** FOAF URI of the contact. */ private String foafUri; /** Name of the contact. */ private String nickname; public String getFoafUri() { return foafUri; } public String getNickname() { return nickname; } public void setFoafUri(String foafUri) { this.foafUri = foafUri; } public void setNickname(String nickname) { this.nickname = nickname; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/objects/User.java0000664000175000017500000000463111757206350032043 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.objects; import java.util.ArrayList; import java.util.List; /** * User account. */ public class User extends BaseObject { /** List of contacts of the user. */ private List contacts; /** First name of the user. */ private String firstName; /** Image representation of the user. */ private String image; /** Last name of the user. */ private String lastName; public User() { super(); } public List getContacts() { if(contacts == null){ contacts = new ArrayList(); } return contacts; } public String getFirstName() { return this.firstName; } public String getImage() { return image; } public String getLastName() { return this.lastName; } public void setContacts(List contacts) { this.contacts = contacts; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setImage(String image) { this.image = image; } public void setLastName(String lastName) { this.lastName = lastName; } } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/data/0000775000175000017500000000000011757206350027536 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/data/DataFacade.java0000664000175000017500000000724211757206350032343 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.data; import java.util.List; import org.restlet.example.ext.rdf.foaf.objects.Contact; import org.restlet.example.ext.rdf.foaf.objects.User; /** * Simple factory that generates Data Access Objects. */ public abstract class DataFacade { /** * Add a new Contact object in the database. * * @param user * parent user object. * @param contact * new Contact object to be added. * @return the contact object completed with its identifiant. */ public abstract Contact createContact(User user,Contact contact); /** * * * @param user * */ /** * Add a new User object in the database. * * @param user * new User object to be added. * @return the user object completed with its identifiant. */ public abstract User createUser(User user); /** * Delete a contact. * * @param contact * the contact to be deleted. */ public abstract void deleteContact(Contact contact); /** * Delete a user. * * @param user * the user to be deleted. */ public abstract void deleteUser(User user); /** * Get a contact by its id. * * @param contactId * the contact's id. * @return a Contact object or null if no contact has been found. */ public abstract Contact getContactById(String contactId); /** * Get the list of contacts owned by a given user. * * @param user * the owner. * @return the list of contacts owned by this user. */ public abstract List getContacts(User user); /** * Get a user by its id. * * @param userId * the user's id. * @return a User object or null if no user has been found. */ public abstract User getUserById(String userId); /** * Get the list of all users. * * @return the list of all users. */ public abstract List getUsers(); /** * Update a contact. * * @param mailbox * the parent mailbox. * @param contact * the contact to be update. */ public abstract void updateContact(Contact contact); /** * Update a user. * * @param user * the user to be upated. */ public abstract void updateUser(User user); } restlet-2.0.14/org.restlet.example/src/org/restlet/example/ext/rdf/foaf/data/ListFacade.java0000664000175000017500000000605011757206350032401 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.example.ext.rdf.foaf.data; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.restlet.example.ext.rdf.foaf.objects.Contact; import org.restlet.example.ext.rdf.foaf.objects.User; public class ListFacade extends DataFacade { private ConcurrentMap users; public ListFacade() { super(); this.users = new ConcurrentHashMap(); } @Override public Contact createContact(User user, Contact contact) { contact.setId(Integer.toString(user.getContacts().size() + 1)); return contact; } @Override public User createUser(User user) { user.setId(Integer.toString(users.size() + 1)); users.put(user.getId(), user); return user; } @Override public void deleteContact(Contact contact) { } @Override public void deleteUser(User user) { users.remove(user.getId()); } @Override public Contact getContactById(String contactId) { Contact result = null; for (User user : users.values()) { for (Contact contact : user.getContacts()) { if (contactId.equals(contact.getId())) { result = contact; break; } } } return result; } @Override public List getContacts(User user) { return user.getContacts(); } @Override public User getUserById(String userId) { return users.get(userId); } @Override public List getUsers() { return new ArrayList(users.values()); } @Override public void updateContact(Contact contact) { } @Override public void updateUser(User user) { } } restlet-2.0.14/org.restlet.ext.rome/0000775000175000017500000000000012001473205017736 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rome/pom.xml0000600000175000017500000000177512001473205021253 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.rome Restlet Extension - ROME Support for syndicated representations via the ROME library. rome rome 1.0 org.jdom jdom 1.1 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.rome/src/0000775000175000017500000000000012001473205020525 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rome/src/META-INF/0000775000175000017500000000000011757206452021704 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rome/src/META-INF/services/0000775000175000017500000000000011757206352023526 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootrestlet-2.0.14/org.restlet.ext.rome/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.rome/src/META-INF/services/org.restlet.engine.converter.ConverterHelp0000664000175000017500000000004211757206352033746 0ustar jamespagejamespageorg.restlet.ext.rome.RomeConverterrestlet-2.0.14/org.restlet.ext.rome/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206450023335 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.rome/src/org/0000775000175000017500000000000011757206352021332 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rome/src/org/restlet/0000775000175000017500000000000011757206352023014 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rome/src/org/restlet/ext/0000775000175000017500000000000011757206352023614 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rome/src/org/restlet/ext/rome/0000775000175000017500000000000011757206352024556 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.rome/src/org/restlet/ext/rome/RomeConverter.java0000664000175000017500000001120711757206352030214 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rome; import java.io.IOException; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; import com.sun.syndication.feed.synd.SyndFeed; /** * Converter of SyndFeed objects into Representation instances. * * @author Thierry Boileau * */ public class RomeConverter extends ConverterHelper { private static final VariantInfo VARIANT_APPLICATION_ATOM = new VariantInfo( MediaType.APPLICATION_ATOM); private static final VariantInfo VARIANT_APPLICATION_RSS = new VariantInfo( MediaType.APPLICATION_RSS); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_APPLICATION_ATOM.isCompatible(source) || VARIANT_APPLICATION_RSS.isCompatible(source)) { result = addObjectClass(result, SyndFeed.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (SyndFeed.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_APPLICATION_ATOM); result = addVariant(result, VARIANT_APPLICATION_RSS); } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if ((source != null) && (SyndFeed.class.isAssignableFrom(target))) { result = 1.0F; } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { if (source instanceof SyndFeed) { return 1.0f; } return -1.0f; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { Object result = null; if (SyndFeed.class.isAssignableFrom(target)) { if (source instanceof SyndFeedRepresentation) { result = ((SyndFeedRepresentation) source).getFeed(); } else { result = new SyndFeedRepresentation(source).getFeed(); } } return target.cast(result); } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { if (source instanceof SyndFeed) { SyndFeed feed = (SyndFeed) source; if (feed.getFeedType() == null) { if (VARIANT_APPLICATION_RSS.isCompatible(target)) { feed.setFeedType("rss_2.0"); } else { feed.setFeedType("atom_1.0"); } } return new SyndFeedRepresentation(feed); } return null; } @Override public void updatePreferences(List> preferences, Class entity) { if (SyndFeed.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_ATOM, 1.0F); updatePreferences(preferences, MediaType.APPLICATION_RSS, 1.0F); } } } restlet-2.0.14/org.restlet.ext.rome/src/org/restlet/ext/rome/package.html0000664000175000017500000000037411757206352027043 0ustar jamespagejamespage Integration with ROME 1.0. This extension supports the formatting of syndicated feeds in various versions of the RSS and Atom languages. @since Restlet 2.0 @see ROME home restlet-2.0.14/org.restlet.ext.rome/src/org/restlet/ext/rome/SyndFeedRepresentation.java0000664000175000017500000001271611757206352032054 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.rome; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.xml.sax.InputSource; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.SyndFeedOutput; /** * A syndicated feed representation (such as RSS or Atom) based on the ROME * library. Add feed entries to {@link SyndFeed#getEntries()}, which you can * access via {@link #getFeed()}. * * @author Tal Liron * @see ROME home */ public class SyndFeedRepresentation extends WriterRepresentation { /** * Converts a feed type to a media type. * * @param feedType * The source feed type. * @return The result media type or null. */ private static MediaType getMediaType(String feedType) { MediaType result = null; if (feedType != null) { result = feedType.startsWith("atom") ? MediaType.APPLICATION_ATOM : MediaType.APPLICATION_RSS; } return result; } /** The syndication feed. */ private volatile SyndFeed feed; /** * Constructs a UTF8 RSS 2.0 feed. */ public SyndFeedRepresentation() { this("rss_2.0"); } /** * Constructor that parses the given feed representation. * * @param feedRepresentation * The feed representation to parse. */ public SyndFeedRepresentation(Representation feedRepresentation) { super(null); try { InputSource source = new InputSource(feedRepresentation.getStream()); this.feed = new SyndFeedInput().build(source); setMediaType(getMediaType(this.feed.getFeedType())); } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to parse feed", e); } } /** * Constructs a UTF8 feed. * * @param feedType * The feed type (see ROME documentation) */ public SyndFeedRepresentation(String feedType) { this(feedType, CharacterSet.UTF_8); } /** * Constructs a feed. * * @param feedType * The feed type (see ROME documentation) * @param characterSet * The character set */ public SyndFeedRepresentation(String feedType, CharacterSet characterSet) { this(feedType, new ArrayList(), characterSet); } /** * Constructs a feed. * * @param feedType * The feed type (see ROME documentation) * @param entries * The list of entries * @param characterSet * The character set */ public SyndFeedRepresentation(String feedType, List entries, CharacterSet characterSet) { super(getMediaType(feedType)); setCharacterSet(characterSet); this.feed = new SyndFeedImpl(); this.feed.setFeedType(feedType); this.feed.setEntries(entries); } /** * Constructor around an existing feed. * * @param feed * The feed (must have a valid feedType!) */ public SyndFeedRepresentation(SyndFeed feed) { super(getMediaType(feed.getFeedType())); this.feed = feed; } /** * The wrapped feed. * * @return The feed */ public SyndFeed getFeed() { return this.feed; } @Override public void write(Writer writer) throws IOException { try { SyndFeedOutput output = new SyndFeedOutput(); if (this.feed.getFeedType() == null) { this.feed.setFeedType("atom_1.0"); } output.output(this.feed, writer); } catch (FeedException e) { IOException ioe = new IOException("Feed exception"); ioe.initCause(e); throw ioe; } } } restlet-2.0.14/org.restlet.ext.freemarker/0000775000175000017500000000000012001473176021126 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.freemarker/pom.xml0000600000175000017500000000157612001473175022441 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.freemarker Restlet Extension - FreeMarker Integration with FreeMarker. org.freemarker freemarker 2.3.19 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.freemarker/src/0000775000175000017500000000000012001473175021714 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.freemarker/src/META-INF/0000775000175000017500000000000011757206450023063 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.freemarker/src/META-INF/services/0000775000175000017500000000000011757206352024707 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.freemarker/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.freemarker/src/META-INF/services/org.restlet.engine.converter.Convert0000664000175000017500000000005611757206352033774 0ustar jamespagejamespageorg.restlet.ext.freemarker.FreemarkerConverterrestlet-2.0.14/org.restlet.ext.freemarker/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446024523 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.freemarker/src/org/0000775000175000017500000000000011757206352022513 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/0000775000175000017500000000000011757206352024175 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/0000775000175000017500000000000011757206352024775 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/0000775000175000017500000000000011757206352027120 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/internal/0000775000175000017500000000000011757206352030734 5ustar jamespagejamespage././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootrestlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/internal/ResolverHashModel.javarestlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/internal/ResolverHashModel.0000664000175000017500000000476611757206352034340 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.freemarker.internal; import org.restlet.util.Resolver; import freemarker.template.TemplateHashModel; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; /** * Template Hash Model based on a Resolver instance. * * @author Jerome Louvel */ public class ResolverHashModel implements TemplateHashModel { /** The inner resolver instance. */ private final Resolver resolver; /** * Constructor. * * @param resolver * The inner resolver. */ public ResolverHashModel(Resolver resolver) { super(); this.resolver = resolver; } /** * Returns a scalar model based on the value returned by the resolver * according to the key. */ public TemplateModel get(String key) throws TemplateModelException { Object value = this.resolver.resolve(key); if (value == null) { return null; } else if (value instanceof TemplateModel) { return (TemplateModel) value; } return new ScalarModel(value); } /** * Returns false. * * @Return False. */ public boolean isEmpty() throws TemplateModelException { return false; } } restlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/internal/ScalarModel.java0000664000175000017500000000357011757206352033772 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.freemarker.internal; import freemarker.template.TemplateModelException; import freemarker.template.TemplateScalarModel; /** * Data model that gives access to a Object value. * * @author Jerome Louvel */ class ScalarModel implements TemplateScalarModel { /** The inner value. */ private final Object value; /** * Constructor. * * @param value * the provided value of this scalar model. */ public ScalarModel(Object value) { super(); this.value = value; } public String getAsString() throws TemplateModelException { return this.value.toString(); } } restlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/package.html0000664000175000017500000000045611757206352031406 0ustar jamespagejamespage Integration with FreeMarker 2.3. FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. @since Restlet 1.0 @see FreeMarker template engine restlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/ContextTemplateLoader.java0000664000175000017500000001130711757206352034234 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.freemarker; import java.io.IOException; import java.io.Reader; import java.util.Date; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.representation.Representation; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; /** * FreeMarker template loader based on a Context's client dispatcher. You can * set an instance on a FreeMarker configuration via the * {@link Configuration#setTemplateLoader(TemplateLoader)} method. * * @author Jerome Louvel */ public class ContextTemplateLoader implements TemplateLoader { /** The base URI. */ private final String baseUri; /** The Restlet context. */ private final Context context; /** * Constructor. * * @param context * The Restlet context. * @param baseRef * The base reference. */ public ContextTemplateLoader(Context context, Reference baseRef) { this(context, baseRef.toString()); } /** * Constructor. * * @param context * The Restlet context. * @param baseUri * The base URI. */ public ContextTemplateLoader(Context context, String baseUri) { this.context = context; this.baseUri = baseUri; } /** * Close the template source. * * @param templateSource * The template source {@link Representation}. */ public void closeTemplateSource(Object templateSource) throws IOException { if (templateSource instanceof Representation) { ((Representation) templateSource).release(); } } /** * Finds the object that acts as the source of the template with the given * name. * * @param name * The template name. * @return The template source {@link Representation}. */ public Object findTemplateSource(String name) throws IOException { String fullUri; if (getBaseUri().endsWith("/")) { fullUri = getBaseUri() + name; } else { fullUri = getBaseUri() + "/" + name; } return (getContext() == null) ? null : getContext() .getClientDispatcher().handle(new Request(Method.GET, fullUri)) .getEntity(); } /** * Returns the base URI. * * @return The base URI. */ private String getBaseUri() { return baseUri; } /** * Returns the Restlet context. * * @return The Restlet context. */ private Context getContext() { return context; } /** * Returns the modification time. * * @param templateSource * The template source {@link Representation}. * @return The modification time. */ public long getLastModified(Object templateSource) { Date lastModified = ((Representation) templateSource) .getModificationDate(); return (lastModified == null) ? -1L : lastModified.getTime(); } /** * Returns the reader for the template source. * * @param templateSource * The template source {@link Representation}. * @param encoding * The reader encoding (currently ignored). */ public Reader getReader(Object templateSource, String encoding) throws IOException { return ((Representation) templateSource).getReader(); } } restlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/TemplateFilter.java0000664000175000017500000001436711757206352032717 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.freemarker; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Encoding; import org.restlet.ext.freemarker.internal.ResolverHashModel; import org.restlet.routing.Filter; import org.restlet.util.Resolver; import freemarker.template.Configuration; import freemarker.template.TemplateHashModel; /** * Filter response's entity and wrap it with a FreeMarker's template * representation. By default, the template representation provides a data model * based on the request and response objects. In order for the wrapping to * happen, the representations must have the {@link Encoding#FREEMARKER} * encoding set.
    *
    * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Thierry Boileau */ public class TemplateFilter extends Filter { /** The FreeMarker configuration. */ private volatile Configuration configuration; /** The template's data model. */ private volatile Object dataModel; /** * Constructor. */ public TemplateFilter() { super(); this.configuration = new Configuration(); } /** * Constructor. * * @param context * The context. */ public TemplateFilter(Context context) { super(context); this.configuration = new Configuration(); } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. */ public TemplateFilter(Context context, Restlet next) { super(context, next); this.configuration = new Configuration(); } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. * @param dataModel * The filter's data model. */ public TemplateFilter(Context context, Restlet next, Object dataModel) { this(context, next); this.dataModel = dataModel; } /** * Constructor. * * @param context * The context. * @param next * The next Restlet. * @param dataModel * The filter's data model. */ public TemplateFilter(Context context, Restlet next, Resolver dataModel) { this(context, next); this.dataModel = dataModel; } @Override protected void afterHandle(Request request, Response response) { if (response.isEntityAvailable() && response.getEntity().getEncodings().contains( Encoding.FREEMARKER)) { TemplateRepresentation representation = new TemplateRepresentation( response.getEntity(), this.configuration, response .getEntity().getMediaType()); representation.setDataModel(createDataModel(request, response)); response.setEntity(representation); } } /** * Creates the FreeMarker data model for a given call. By default, it will * create a {@link TemplateHashModel} based on the result of * {@link Resolver#createResolver(Request, Response)}. If the * {@link #getDataModel()} method has a non null value, it will be used. * * @param request * The handled request. * @param response * The handled response. * @return The FreeMarker data model for the given call. */ protected Object createDataModel(Request request, Response response) { Object result = null; if (this.dataModel == null) { result = new ResolverHashModel(Resolver.createResolver(request, response)); } else { result = this.dataModel; } return result; } /** * Returns the FreeMarker configuration. * * @return The FreeMarker configuration. */ public Configuration getConfiguration() { return this.configuration; } /** * Returns the template data model common to all calls. If each call should * have a specific model, you should set this property to null. * * @return The template data model common to all calls. */ public Object getDataModel() { return dataModel; } /** * Sets the FreeMarker configuration. * * @param config * FreeMarker configuration. */ public void setConfiguration(Configuration config) { this.configuration = config; } /** * Sets the template data model common to all calls. If each call should * have a specific model, you should set this property to null. * * @param dataModel * The template data model common to all calls. */ public void setDataModel(Object dataModel) { this.dataModel = dataModel; } } restlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/TemplateRepresentation.java0000664000175000017500000002507111757206352034466 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.freemarker; import java.io.IOException; import java.io.Writer; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.CharacterSet; import org.restlet.data.MediaType; import org.restlet.ext.freemarker.internal.ResolverHashModel; import org.restlet.representation.Representation; import org.restlet.representation.WriterRepresentation; import org.restlet.util.Resolver; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /** * FreeMarker template representation. Useful for dynamic string-based * representations. * * @see FreeMarker home page * @author Jerome Louvel */ public class TemplateRepresentation extends WriterRepresentation { /** * Returns a FreeMarker template from a representation and a configuration. * * @param config * The FreeMarker configuration. * @param templateRepresentation * The template representation. * @return The template or null if not found. */ public static Template getTemplate(Configuration config, Representation templateRepresentation) { try { // Instantiate the template with the character set of the template // representation if it has been set, otherwise use UTF-8. if (templateRepresentation.getCharacterSet() != null) { return new Template("template", templateRepresentation .getReader(), config, templateRepresentation .getCharacterSet().getName()); } return new Template("template", templateRepresentation.getReader(), config, CharacterSet.UTF_8.getName()); } catch (IOException e) { Context.getCurrentLogger().warning( "Unable to get the template from the representation " + templateRepresentation.getLocationRef() + ". Error message: " + e.getMessage()); return null; } } /** * Returns a FreeMarker template from its name and a configuration. * * @param config * The FreeMarker configuration. * @param templateName * The template name. * @return The template or null if not found. */ public static Template getTemplate(Configuration config, String templateName) { try { return config.getTemplate(templateName); } catch (IOException e) { Context.getCurrentLogger().warning( "Unable to get the template " + templateName + ". Error message: " + e.getMessage()); return null; } } /** The template's data model. */ private volatile Object dataModel; /** The FreeMarker template. */ private volatile Template template; /** * Constructor. * * @param templateRepresentation * The FreeMarker template provided via a representation. * @param config * The FreeMarker configuration. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Representation templateRepresentation, Configuration config, MediaType mediaType) { this(getTemplate(config, templateRepresentation), mediaType); } /** * Constructor. * * @param templateRepresentation * The FreeMarker template provided via a representation. * @param config * The FreeMarker configuration. * @param dataModel * The template's data model. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Representation templateRepresentation, Configuration config, Object dataModel, MediaType mediaType) { this(getTemplate(config, templateRepresentation), dataModel, mediaType); } /** * Constructor. * * @param templateRepresentation * The FreeMarker template provided via a representation. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Representation templateRepresentation, MediaType mediaType) { this(templateRepresentation, new Configuration(), mediaType); } /** * Constructor. Uses a default FreeMarker configuration. * * @param templateRepresentation * The FreeMarker template provided via a representation. * @param dataModel * The template's data model. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Representation templateRepresentation, Object dataModel, MediaType mediaType) { this(templateRepresentation, new Configuration(), dataModel, mediaType); } /** * Constructor. * * @param templateName * The FreeMarker template's name. The full path is resolved by * the configuration. * @param config * The FreeMarker configuration. * @param mediaType * The representation's media type. */ public TemplateRepresentation(String templateName, Configuration config, MediaType mediaType) { this(getTemplate(config, templateName), mediaType); } /** * Constructor. * * @param templateName * The FreeMarker template's name. The full path is resolved by * the configuration. * @param config * The FreeMarker configuration. * @param dataModel * The template's data model. * @param mediaType * The representation's media type. */ public TemplateRepresentation(String templateName, Configuration config, Object dataModel, MediaType mediaType) { this(getTemplate(config, templateName), dataModel, mediaType); } /** * Constructor. * * @param template * The FreeMarker template. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Template template, MediaType mediaType) { super(mediaType); this.template = template; } /** * Constructor. * * @param template * The FreeMarker template. * @param dataModel * The template's data model. * @param mediaType * The representation's media type. */ public TemplateRepresentation(Template template, Object dataModel, MediaType mediaType) { super(mediaType); this.template = template; this.dataModel = dataModel; } /** * Returns the template's data model. * * @return The template's data model. */ public Object getDataModel() { return this.dataModel; } /** * Returns the FreeMarker template. * * @return The FreeMarker template. */ public Template getTemplate() { return template; } /** * Sets the template's data model. * * @param dataModel * The template's data model. * @return The template's data model. */ public Object setDataModel(Object dataModel) { this.dataModel = dataModel; return dataModel; } /** * Sets the template's data model from a request/response pair. This default * implementation uses a Resolver. * * @see Resolver * @see Resolver#createResolver(Request, Response) * * @param request * The request where data are located. * @param response * The response where data are located. * @return The template's data model. */ public Object setDataModel(Request request, Response response) { this.dataModel = new ResolverHashModel(Resolver.createResolver(request, response)); return this.dataModel; } /** * Sets the template's data model from a resolver. * * @param resolver * The resolver. * @return The template's data model. */ public Object setDataModel(Resolver resolver) { this.dataModel = new ResolverHashModel(resolver); return this.dataModel; } /** * Sets the FreeMarker template. * * @param template * The FreeMarker template. */ public void setTemplate(Template template) { this.template = template; } /** * Writes the datum as a stream of characters. * * @param writer * The writer to use when writing. */ @Override public void write(Writer writer) throws IOException { if (this.template != null) { try { this.template.process(getDataModel(), writer); } catch (TemplateException te) { throw new IOException("Template processing error " + te.getMessage()); } } else { Context .getCurrentLogger() .warning( "Unable to write the template representation. No template found."); } } } restlet-2.0.14/org.restlet.ext.freemarker/src/org/restlet/ext/freemarker/FreemarkerConverter.java0000664000175000017500000000613211757206352033740 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.freemarker; import java.io.IOException; import java.util.List; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.ext.freemarker.internal.ResolverHashModel; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; import org.restlet.util.Resolver; import freemarker.template.Template; /** * Converter between the Freemarker Template objects and Representations. The * adjoined data model is based on the request and response objects. * * @author Thierry Boileau. */ public class FreemarkerConverter extends ConverterHelper { @Override public List> getObjectClasses(Variant source) { return null; } @Override public List getVariants(Class source) { return null; } @Override public float score(Representation source, Class target, UniformResource resource) { return -1.0f; } @Override public float score(Object source, Variant target, UniformResource resource) { if (source instanceof Template) { return 1.0f; } return -1.0f; } @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { return null; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) throws IOException { if (source instanceof Template) { return new TemplateRepresentation((Template) source, new ResolverHashModel(Resolver.createResolver( resource.getRequest(), resource.getResponse())), target.getMediaType()); } return null; } } restlet-2.0.14/org.restlet.ext.gwt/0000775000175000017500000000000012001473137017601 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.gwt/pom.xml0000600000175000017500000000156512001473137021113 0ustar jamespagejamespage 4.0.0 org.restlet.jse org.restlet.parent 2.0.14 org.restlet.ext.gwt Restlet Extension - GWT Server-side integration with GWT. com.google.gwt gwt-servlet 2.0.3 org.restlet.jse org.restlet 2.0.14 restlet-2.0.14/org.restlet.ext.gwt/src/0000775000175000017500000000000012001473137020370 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.gwt/src/META-INF/0000775000175000017500000000000011757206450021541 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.gwt/src/META-INF/services/0000775000175000017500000000000011757206346023370 5ustar jamespagejamespage././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootrestlet-2.0.14/org.restlet.ext.gwt/src/META-INF/services/org.restlet.engine.converter.ConverterHelperrestlet-2.0.14/org.restlet.ext.gwt/src/META-INF/services/org.restlet.engine.converter.ConverterHelpe0000664000175000017500000000004011757206346033753 0ustar jamespagejamespageorg.restlet.ext.gwt.GwtConverterrestlet-2.0.14/org.restlet.ext.gwt/src/META-INF/MANIFEST.MF0000664000175000017500000000014611757206446023201 0ustar jamespagejamespageManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 20.6-b01 (Sun Microsystems Inc.) restlet-2.0.14/org.restlet.ext.gwt/src/org/0000775000175000017500000000000011757206346021174 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/0000775000175000017500000000000011757206346022656 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/ext/0000775000175000017500000000000011757206346023456 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/ext/gwt/0000775000175000017500000000000011757206346024257 5ustar jamespagejamespagerestlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/ext/gwt/SimpleSerializationPolicyProvider.java0000664000175000017500000000365511757206346034015 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.gwt; import com.google.gwt.user.server.rpc.SerializationPolicy; import com.google.gwt.user.server.rpc.SerializationPolicyProvider; /** * Serialization policy provider that return the * {@link SimpleSerializationPolicy} default instance all the time. * * @author Jerome Louvel */ public class SimpleSerializationPolicyProvider implements SerializationPolicyProvider { /** * Simple policy provider that always returns * {@link SimpleSerializationPolicy#getInstance()}. */ public SerializationPolicy getSerializationPolicy(String moduleBaseURL, String serializationPolicyStrongName) { return SimpleSerializationPolicy.getInstance(); } } restlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/ext/gwt/GwtConverter.java0000664000175000017500000001344411757206346027561 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.gwt; import java.io.IOException; import java.io.Serializable; import java.util.List; import org.restlet.data.MediaType; import org.restlet.data.Preference; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Converter between Object instances and Representations based on GWT * serialization format. * * @author Jerome Louvel */ public class GwtConverter extends ConverterHelper { /** GWT variant. */ private static final VariantInfo VARIANT_GWT = new VariantInfo( MediaType.APPLICATION_JAVA_OBJECT_GWT); @Override public List> getObjectClasses(Variant source) { List> result = null; if (VARIANT_GWT.isCompatible(source)) { result = addObjectClass(result, Serializable.class); result = addObjectClass(result, ObjectRepresentation.class); } return result; } @Override public List getVariants(Class source) { List result = null; if (Serializable.class.isAssignableFrom(source) || ObjectRepresentation.class.isAssignableFrom(source)) { result = addVariant(result, VARIANT_GWT); } return result; } @Override public float score(Object source, Variant target, UniformResource resource) { float result = -1.0F; if (source instanceof Serializable) { if (target == null) { result = 0.5F; } else if (MediaType.APPLICATION_JAVA_OBJECT_GWT.equals(target .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_JAVA_OBJECT_GWT .isCompatible(target.getMediaType())) { result = 0.6F; } else { result = 0.5F; } } return result; } @Override public float score(Representation source, Class target, UniformResource resource) { float result = -1.0F; if (source instanceof ObjectRepresentation) { result = 1.0F; } else if ((target != null) && ObjectRepresentation.class.isAssignableFrom(target)) { result = 1.0F; } else if ((target != null) && Serializable.class.isAssignableFrom(target)) { if (MediaType.APPLICATION_JAVA_OBJECT_GWT.equals(source .getMediaType())) { result = 1.0F; } else if (MediaType.APPLICATION_JAVA_OBJECT_GWT .isCompatible(source.getMediaType())) { result = 0.6F; } } return result; } @SuppressWarnings("unchecked") @Override public T toObject(Representation source, Class target, UniformResource resource) throws IOException { T result = null; if (target != null) { if (ObjectRepresentation.class.isAssignableFrom(target)) { if (source instanceof ObjectRepresentation) { result = (T) source; } else { result = (T) new ObjectRepresentation(source.getText(), target); } } else if (Serializable.class.isAssignableFrom(target)) { result = new ObjectRepresentation(source.getText(), target) .getObject(); } } else if (source instanceof ObjectRepresentation) { result = ((ObjectRepresentation) source).getObject(); } return result; } @Override public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; if (source instanceof Serializable) { result = new ObjectRepresentation( (Serializable) source); } else if (source instanceof Representation) { result = (Representation) source; } return result; } @Override public void updatePreferences(List> preferences, Class entity) { if (Serializable.class.isAssignableFrom(entity) || ObjectRepresentation.class.isAssignableFrom(entity)) { updatePreferences(preferences, MediaType.APPLICATION_JAVA_OBJECT_GWT, 1.0F); } } } restlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/ext/gwt/ObjectRepresentation.java0000664000175000017500000001456011757206346031261 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.gwt; import org.restlet.data.MediaType; import org.restlet.engine.Engine; import org.restlet.representation.StringRepresentation; import com.google.gwt.user.client.rpc.impl.AbstractSerializationStream; import com.google.gwt.user.server.rpc.SerializationPolicy; import com.google.gwt.user.server.rpc.SerializationPolicyProvider; import com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader; import com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter; /** * Representation based on a serializable Java object. This internally reuses * the GWT-RPC serialization logic. * * @author Jerome Louvel * @param * The class to serialize. */ public class ObjectRepresentation extends StringRepresentation { /** The wrapped object. */ private T object; /** The GWT-RPC serialization policy. */ private SerializationPolicy serializationPolicy; /** The GWT-RPC serialization policy provider. */ private SerializationPolicyProvider serializationPolicyProvider; /** The target object class. */ private Class targetClass; /** * Constructor for deserialization. * * @param serializedObject * The object serialization text. * @param targetClass * The target object class. */ public ObjectRepresentation(String serializedObject, Class targetClass) { super(serializedObject, MediaType.APPLICATION_JAVA_OBJECT_GWT); this.targetClass = targetClass; this.object = null; this.serializationPolicy = SimpleSerializationPolicy.getInstance(); this.serializationPolicyProvider = new SimpleSerializationPolicyProvider(); } /** * Constructor for serialization. * * @param object * The object to serialize. */ @SuppressWarnings("unchecked") public ObjectRepresentation(T object) { super(null, MediaType.APPLICATION_JAVA_OBJECT_GWT); this.object = object; this.targetClass = (Class) object.getClass(); this.serializationPolicy = SimpleSerializationPolicy.getInstance(); this.serializationPolicyProvider = new SimpleSerializationPolicyProvider(); } /** * The wrapped object. Triggers the deserialization if necessary. * * @return The wrapped object. */ @SuppressWarnings("unchecked") public T getObject() { if ((this.object == null) && (getText() != null)) { try { ServerSerializationStreamReader objectReader = new ServerSerializationStreamReader( Engine.getInstance().getClassLoader(), new SimpleSerializationPolicyProvider()); String encodedString = getText(); if (encodedString.indexOf('|') == -1) { encodedString = AbstractSerializationStream.SERIALIZATION_STREAM_VERSION + "|1|0|0|0|" + getText() + '|'; } objectReader.prepareToRead(encodedString); this.object = (T) objectReader .deserializeValue(this.targetClass); } catch (Exception e) { this.object = null; e.printStackTrace(); } } return object; } /** * Returns the GWT-RPC serialization policy. * * @return The GWT-RPC serialization policy. */ public SerializationPolicy getSerializationPolicy() { return serializationPolicy; } /** * Returns the GWT-RPC serialization policy provider. * * @return The GWT-RPC serialization policy provider. */ public SerializationPolicyProvider getSerializationPolicyProvider() { return serializationPolicyProvider; } @Override public String getText() { if ((this.object != null) && (super.getText() == null)) { try { ServerSerializationStreamWriter objectWriter = new ServerSerializationStreamWriter( getSerializationPolicy()); objectWriter.serializeValue(this.object, this.targetClass); setText("//OK" + objectWriter.toString()); } catch (Exception e) { e.printStackTrace(); } } return super.getText(); } /** * Sets the wrapped object. * * @param object * The wrapped object. */ public void setObject(T object) { this.object = object; } /** * Sets the GWT-RPC serialization policy. * * @param serializationPolicy * The GWT-RPC serialization policy. */ public void setSerializationPolicy(SerializationPolicy serializationPolicy) { this.serializationPolicy = serializationPolicy; } /** * Sets the GWT-RPC serialization policy provider. * * @param serializationPolicyProvider * The GWT-RPC serialization policy provider. */ public void setSerializationPolicyProvider( SerializationPolicyProvider serializationPolicyProvider) { this.serializationPolicyProvider = serializationPolicyProvider; } } restlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/ext/gwt/package.html0000664000175000017500000000025011757206346026535 0ustar jamespagejamespage Server-side integration with GWT 2.0. @since Restlet 1.1 @see Google Web Toolkit restlet-2.0.14/org.restlet.ext.gwt/src/org/restlet/ext/gwt/SimpleSerializationPolicy.java0000664000175000017500000000456311757206346032301 0ustar jamespagejamespage/** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.gwt; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.SerializationPolicy; /** * Serialization policy that allows the serialization of all the classes and * fields. * * @author Jerome Louvel */ public class SimpleSerializationPolicy extends SerializationPolicy { private static final SimpleSerializationPolicy instance = new SimpleSerializationPolicy(); /** * Returns the common instance of this simple policy file. * * @return The common instance of this simple policy file. */ public static SerializationPolicy getInstance() { return instance; } @Override public boolean shouldDeserializeFields(Class clazz) { return (clazz != null); } @Override public boolean shouldSerializeFields(Class clazz) { return (clazz != null); } @Override public void validateDeserialize(Class clazz) throws SerializationException { // No validation } @Override public void validateSerialize(Class clazz) throws SerializationException { // No validation } }