Java Code Examples for org.restlet.resource.ServerResource

The following are top voted examples for showing how to use org.restlet.resource.ServerResource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: restlet-framework   File: RestletGuice.java   Source Code and License 6 votes vote down vote up
public final Class<? extends ServerResource> getTargetClass() {

                // If the key type is a subtype of ServerResource, return it.
                Class<ServerResource> src = ServerResource.class;
                if (src != null && targetClass != null
                        && src.isAssignableFrom(targetClass)) {
                    @SuppressWarnings("unchecked")
                    Class<? extends ServerResource> result = (Class<? extends ServerResource>) targetClass;
                    return result;
                }

                // Otherwise, we can't in general determine the true target
                // type, so we revert to the superclass implementation.
                // Since we used the no-arg Finder constructor, it will return
                // null unless someone has explicitly set a target class. This
                // is only relevant to the use of the Router.detach(Class<?>
                // targetClass) method; it implies that we cannot detach routes
                // that target dependency-injected resources attached as
                // non-ServerResource types without explicitly setting a target
                // class type. This seems like a *very* minor restriction.
                return super.getTargetClass();
            }
 
Example 2
Project: restlet-framework   File: ResourceInjectingApplication.java   Source Code and License 6 votes vote down vote up
/**
 * Wraps a {@link Finder} returned by {@link #createFinder(Class)} to do
 * member injection using the passed in {@link MembersInjector}.
 * 
 * @param finder
 *            The finder.
 * @param membersInjector
 *            The instance of {@link MembersInjector}.
 * @return A wrapped {@link Finder}.
 */
public static Finder wrapFinderWithMemberInjection(final Finder finder,
        final SelfInjectingServerResource.MembersInjector membersInjector) {
    return new Finder(finder.getContext(), finder.getTargetClass()) {
        @Override
        public ServerResource find(Request request, Response response) {
            ServerResource res = finder.find(request, response);
            if (res instanceof SelfInjectingServerResource) {
                SelfInjectingServerResource tmp = (SelfInjectingServerResource) res;
                tmp.ensureInjected(membersInjector);
            } else {
                membersInjector.injectMembers(res);
            }
            return res;
        }
    };
}
 
Example 3
Project: soaba   File: RestletServer.java   Source Code and License 6 votes vote down vote up
/**
 * Binds all server resources to their corresponding URIs with the current
 * application.
 */
@SuppressWarnings("unchecked")
@Override
public synchronized Restlet createInboundRoot() {
    Context routerContext = getContext().createChildContext();
    final Router appRouter = new Router(routerContext);
    appRouter.attachDefault(BonjourService.class);

    for (String resxURI : resx.keySet())
        appRouter.attach(resxURI, (Class<ServerResource>) resx.get(resxURI));

    // attachs bonjour service, which presents the API UI
    appRouter.attach("", BonjourService.class);
    appRouter.attach("/", BonjourService.class);

    return appRouter;
}
 
Example 4
Project: Pinot   File: ControllerRestApplication.java   Source Code and License 6 votes vote down vote up
private void attachRoutesForClass(Router router, Class<? extends ServerResource> clazz) {
  TreeSet<String> pathsOrderedByLength = new TreeSet<String>(ComparatorUtils.chainedComparator(new Comparator<String>() {
    private IntComparator _intComparator = IntComparators.NATURAL_COMPARATOR;
    @Override
    public int compare(String o1, String o2) {
      return _intComparator.compare(o1.length(), o2.length());
    }
  }, ComparatorUtils.NATURAL_COMPARATOR));

  for (Method method : clazz.getDeclaredMethods()) {
    Annotation annotationInstance = method.getAnnotation(Paths.class);
    if (annotationInstance != null) {
      pathsOrderedByLength.addAll(Arrays.asList(((Paths) annotationInstance).value()));
    }
  }

  for (String routePath : pathsOrderedByLength) {
    LOGGER.info("Attaching route {} -> {}", routePath, clazz.getSimpleName());
    router.attach(routePath, new AddHeaderFilter(getContext(), createFinder(clazz)));
  }
}
 
Example 5
Project: SlipStreamServer   File: UserRouter.java   Source Code and License 6 votes vote down vote up
private void attachPath(String path,
		Class<? extends ServerResource> resourceClass, Role role) {
	RoleAuthorizer ra = new RoleAuthorizer();
	TemplateRoute route;
	if (role != null) {
		ra.getAuthorizedRoles().add(role);
		ra.setNext(resourceClass);
		route = attach(path, ra);
	} else {
		route = attach(path, resourceClass);
	}
	route.setMatchingMode(Template.MODE_STARTS_WITH);

	// Allow the user variable to match any valid path characters.
	// Needed because usernames from external sources may contain slashes.
	Template template = route.getTemplate();
	Map<String, Variable> variables = template.getVariables();
	variables.put(UserResource.USERNAME_URI_ATTRIBUTE, new Variable(Variable.TYPE_URI_PATH));
	template.setVariables(variables);
}
 
Example 6
Project: SlipStreamServer   File: ModuleResourceTest.java   Source Code and License 6 votes vote down vote up
protected Response executeRequest(Request request, MediaType mediaType) {

		List<Preference<MediaType>> accepts = request.getClientInfo().getAcceptedMediaTypes();
		accepts.clear();
		if (mediaType != null) {
			accepts.add(new Preference<>(mediaType));
		}

		ServerResource resource = new ModuleResource();
		Response response = new Response(request);

		resource.init(null, request, response);
		if (response.getStatus().isSuccess()) {
			resource.handle();
		}

		return resource.getResponse();
	}
 
Example 7
Project: bigstreams   File: TestFileTrackerStatusResource.java   Source Code and License 5 votes vote down vote up
protected Application setupApp() throws Exception {

		final MapTrackerMemory memory = new MapTrackerMemory();

		memory.updateFile(new FileTrackingStatus(1L, 10L, "test1.txt",
				FileTrackingStatus.STATUS.READY, 3, 4L, "testType1", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, "test2.txt",
				FileTrackingStatus.STATUS.READING, 3, 4L, "testType2", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, "test3.txt",
				FileTrackingStatus.STATUS.DONE, 3, 4L, "testType3", new Date(), new Date()));

		this.memory = memory;

		Finder finder = new Finder() {

			@Override
			public ServerResource find(Request request, Response response) {
				return fileTrackingStatusResource(memory);
			}

		};

		final Router router = new Router();
		router.attach("/files/list", finder);
		router.attach("/files/list/", finder);
		router.attach("/files/list/{status}", finder);

		return new Application() {

			@Override
			public Restlet createInboundRoot() {
				return router;
			}

		};

	}
 
Example 8
Project: bigstreams   File: TestFileTrackerStatusPathResource.java   Source Code and License 5 votes vote down vote up
protected Application setupApp() throws Exception {

		final MapTrackerMemory memory = new MapTrackerMemory();

		memory.updateFile(new FileTrackingStatus(1L, 10L, new File("test1.txt")
				.getAbsolutePath(), FileTrackingStatus.STATUS.READY, 3, 4L,
				"testType1", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, new File("test2.txt")
				.getAbsolutePath(), FileTrackingStatus.STATUS.READING, 3, 4L,
				"testType2", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, new File("test3.txt")
				.getAbsolutePath(), FileTrackingStatus.STATUS.DONE, 3, 4L,
				"testType3", new Date(), new Date()));

		this.memory = memory;

		Finder finder = new Finder() {

			@Override
			public ServerResource find(Request request, Response response) {
				return fileTrackingStatusPathResource(memory);
			}

		};

		final Router router = new Router();
		router.attach("/files/status", finder, Template.MODE_STARTS_WITH);
		Application app = new Application() {

			@Override
			public Restlet createInboundRoot() {
				return router;
			}

		};

		return app;
	}
 
Example 9
Project: bigstreams   File: CollectorDI.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to attch the server resource to the router.
 * 
 * @param router
 * @param pathTemplate
 * @param resourceClass
 * @param matchingMode
 */
private final void attachFinder(Router router, String pathTemplate,
		final Class<? extends ServerResource> resourceClass,
		int matchingMode) {

	Finder finder = new Finder() {

		@Override
		public ServerResource find(Request request, Response response) {
			return beanFactory.getBean(resourceClass);
		}

	};

	router.attach(pathTemplate, finder, matchingMode);
}
 
Example 10
Project: bigstreams   File: CoordinationDI.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to attch the server resource to the router.
 * 
 * @param router
 * @param pathTemplate
 * @param resourceClass
 * @param matchingMode
 */
private final void attachFinder(Router router, String pathTemplate,
		final Class<? extends ServerResource> resourceClass,
		int matchingMode) {

	Finder finder = new Finder() {

		@Override
		public ServerResource find(Request request, Response response) {
			return beanFactory.getBean(resourceClass);
		}

	};

	router.attach(pathTemplate, finder, matchingMode);
}
 
Example 11
Project: bigstreams   File: AlwaysOKRestlet.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a Component that will used this reasource to always return ok.
 * 
 * @param port
 * @return
 */
public static Component createComponent(int port) {

	Finder finder = new Finder() {

		@Override
		public ServerResource find(Request request, Response response) {
			return new AlwaysOKRestlet();
		}

	};

	final Router router = new Router();
	router.attach("/", finder, Template.MODE_STARTS_WITH);
	
	Application app = new Application() {

		@Override
		public Restlet createInboundRoot() {
			return router;
		}

	};

	Component component = new Component();
	component.getServers().add(org.restlet.data.Protocol.HTTP, port);
	component.getDefaultHost().attach(app);

	return component;
}
 
Example 12
Project: restlet-framework   File: RestletGuice.java   Source Code and License 5 votes vote down vote up
@Override
public ServerResource create(Request request, Response response) {
    try {
        return ServerResource.class.cast(getInjector().getInstance(
                serverResourceKey));
    } catch (ClassCastException ex) {
        String msg = String.format(
                "Must bind %s to ServerResource (or subclass)",
                serverResourceKey);
        throw new ProvisionException(msg, ex);
    }
}
 
Example 13
Project: MCRest   File: RestApplication.java   Source Code and License 5 votes vote down vote up
private void setUpAuth(Router router,String path,String resourceKey,Class<? extends ServerResource> targetClass){
    if(authpara == null ){
        router.attach(path,targetClass);
        return;
    }
    if((!authpara.isProtected(resourceKey))|| (!authpara.isEnabled())){
        router.attach(path,targetClass);
        return;
    }
    ChallengeAuthenticator auth = createAuthenticator();
    auth.setNext(targetClass);
    router.attach(path,auth);
    logger.info("Resource "+router+" need to auth.");
}
 
Example 14
Project: xproclet   File: ClassResourceFinder.java   Source Code and License 5 votes vote down vote up
public ServerResource find(Request request,Response response)
{
   String path = packageName+request.getResourceRef().getRemainingPart();
   if (path.endsWith("/")) {
      path += indexName;
   }
   getLogger().info("resource: "+path);
   ServerResource r = new ClassResource(classLoader,path);
   r.setRequest(request);
   r.setResponse(response);
   return r;
}
 
Example 15
Project: xproclet   File: LoginApplication.java   Source Code and License 5 votes vote down vote up
public ServerResource find(Request request,Response response)
{
   String path = packageName+request.getResourceRef().getRemainingPart();
   ServerResource r = new ClassResource(baseClass,path);
   r.setRequest(request);
   r.setResponse(response);
   return r;
}
 
Example 16
Project: Ptoceti   File: GuiceFinder.java   Source Code and License 5 votes vote down vote up
/**
    * Create an instance of the desired ServerResource, and inject dependencies.
    * 
    * @param targetClass the desired class for the ServerResource
    * @param request the current restlet request
    * @param response the current restlet response
    */
@Override
public ServerResource create(Class<? extends ServerResource> targetClass,
		Request request, Response response) {
	ServerResource result = null;

	if (targetClass != null) {
		result = injector.getInstance(targetClass);
	}
	
	return result;
}
 
Example 17
Project: geowave   File: GeoWaveOperationFinder.java   Source Code and License 5 votes vote down vote up
@Override
public ServerResource create(
		final Class<? extends ServerResource> targetClass,
		final Request request,
		final Response response ) {
	return new GeoWaveOperationServiceWrapper<>(
			operation);
}
 
Example 18
Project: spring-restlet   File: ServerResourceInjectedFinder.java   Source Code and License 5 votes vote down vote up
@Override
public ServerResource create(Request request, Response response) {
    ServerResource resource = super.create(request, response);
    return resource;
}
 
Example 19
Project: wattdepot   File: GvizHelper.java   Source Code and License 5 votes vote down vote up
/**
 * @param server
 *          the restlet ServerResource
 * @param type
 *          type of the gviz query string, such as tqx, or tq
 * @return the value of the gviz query string from the request
 */
public static String getGvizQueryString(ServerResource server, String type) {
  String qs = server.getRequest().getResourceRef().getQueryAsForm().getFirstValue(type);
  try {
    if (qs != null) {
      qs = URLDecoder.decode(qs, "UTF-8");
    }
  }
  catch (UnsupportedEncodingException e) {
    qs = null;
  }
  return qs;
}
 
Example 20
Project: SlipStreamServer   File: RootApplication.java   Source Code and License 5 votes vote down vote up
private AuthenticatorsTemplateRoute guardAndAttach(Router rootRouter, Class<? extends ServerResource> router,
		String rootUri) {
	Authenticators authenticators = getAuthenticators(rootRouter.getApplication());
	authenticators.getLast().setNext(router);
	TemplateRoute route = attach(rootRouter, rootUri, authenticators.getFirst());
	return new AuthenticatorsTemplateRoute(route, authenticators);
}
 
Example 21
Project: SlipStreamServer   File: ModuleResourceCopyToTest.java   Source Code and License 5 votes vote down vote up
protected Response executeRequest(Request request) {

		ServerResource resource = new ModuleResource();
		Response response = new Response(request);

		resource.init(null, request, response);
		if (response.getStatus().isSuccess()) {
			resource.handle();
		}

		return resource.getResponse();
	}
 
Example 22
Project: SlipStreamServer   File: ResourceTestBase.java   Source Code and License 5 votes vote down vote up
protected Response executeRequest(Request request, ServerResource resource) {

		Response response = new Response(request);

		resource.init(null, request, response);
		if (response.getStatus().isSuccess()) {
			resource.handle();
		}

		return resource.getResponse();
	}
 
Example 23
Project: restlet-framework   File: ResourceInjectingApplication.java   Source Code and License 4 votes vote down vote up
@Override
public Finder createFinder(Class<? extends ServerResource> targetClass) {
    Finder finder = super.createFinder(targetClass);
    return wrapFinderWithMemberInjection(finder, membersInjector);
}
 
Example 24
Project: restlet-framework   File: InternalRouter.java   Source Code and License 4 votes vote down vote up
@Override
public Finder createFinder(Class<? extends ServerResource> targetClass) {
    Finder result = super.createFinder(targetClass);
    result.setContext(getContext().createChildContext());
    return result;
}
 
Example 25
Project: polygene-java   File: PolygeneFinder.java   Source Code and License 4 votes vote down vote up
@Override
public ServerResource create( Class<? extends ServerResource> targetClass, Request request, Response response )
{
    return factory.newObject( targetClass );
}
 
Example 26
Project: polygene-java   File: RestApplication.java   Source Code and License 4 votes vote down vote up
private Finder newFinder( Class<? extends ServerResource> resource )
{
    Finder finder = objectFactory.newObject( Finder.class );
    finder.setTargetClass( resource );
    return finder;
}
 
Example 27
Project: prudence   File: ResourceContextualAttributes.java   Source Code and License 4 votes vote down vote up
public ResourceContextualAttributes( ServerResource resource )
{
	super( resource.getClass().getCanonicalName() );
	this.resource = resource;
}
 
Example 28
Project: Pinot   File: SwaggerResource.java   Source Code and License 4 votes vote down vote up
private void generateSwaggerForFinder(JSONObject pathObject, String routePath, Finder finder)
    throws JSONException {
  Class<? extends ServerResource> targetClass = finder.getTargetClass();
  for (Method method : targetClass.getDeclaredMethods()) {
    String httpVerb = null;
    Annotation annotationInstance = method.getAnnotation(HttpVerb.class);
    if (annotationInstance != null) {
      httpVerb = ((HttpVerb) annotationInstance).value().toLowerCase();
    }

    HashSet<String> methodPaths = new HashSet<String>();
    annotationInstance = method.getAnnotation(Paths.class);
    if (annotationInstance != null) {
      methodPaths.addAll(Arrays.asList(((Paths) annotationInstance).value()));
    }

    if (httpVerb != null && methodPaths.contains(routePath) && !routePath.endsWith("/")) {
      JSONObject operation = new JSONObject();
      pathObject.put(httpVerb, operation);

      annotationInstance = method.getAnnotation(Summary.class);
      if (annotationInstance != null) {
        operation.put(Summary.class.getSimpleName().toLowerCase(), ((Summary) annotationInstance).value());
      }

      annotationInstance = method.getAnnotation(Description.class);
      if (annotationInstance != null) {
        operation.put(Description.class.getSimpleName().toLowerCase(), ((Description) annotationInstance).value());
      }

      annotationInstance = method.getAnnotation(Tags.class);
      if (annotationInstance != null) {
        operation.put(Tags.class.getSimpleName().toLowerCase(), ((Tags) annotationInstance).value());
      }

      operation.put("operationId", method.getName());

      ArrayList<JSONObject> parameters = new ArrayList<JSONObject>();

      for (Annotation[] annotations : method.getParameterAnnotations()) {
        if (annotations.length != 0) {
          JSONObject parameter = new JSONObject();
          for (Annotation annotation : annotations) {
            if (annotation instanceof Parameter) {
              Parameter parameterAnnotation = (Parameter) annotation;
              parameter.put("name", parameterAnnotation.name());
              parameter.put("in", parameterAnnotation.in());
              if (parameterAnnotation.description() != null) {
                parameter.put("description", parameterAnnotation.description());
              }
              parameter.put("type", "string");
              parameter.put("required", parameterAnnotation.required());
            }
          }

          if(parameter.keys().hasNext()) {
            parameters.add(parameter);
          }
        }
      }

      operation.put("parameters", parameters.toArray(new JSONObject[parameters.size()]));
    }
  }
}
 
Example 29
Project: st-toolset   File: ResourceBasedFinder.java   Source Code and License 4 votes vote down vote up
public ResourceBasedFinder(final ServerResource newResource) {
    this.resource = newResource;
}
 
Example 30
Project: st-toolset   File: ResourceBasedFinder.java   Source Code and License 4 votes vote down vote up
@Override
public ServerResource create(final Class<? extends ServerResource> targetClass, final Request request, final Response response) {
    return resource;
}
 
Example 31
Project: st-toolset   File: ResourceBasedFinder.java   Source Code and License 4 votes vote down vote up
@Override
public ServerResource create(final Request request, final Response response) {
    return create(null, request, response);
}
 
Example 32
Project: xproclet   File: Configuration.java   Source Code and License 4 votes vote down vote up
static boolean isServerResource(Class targetClass) {
   return ServerResource.class.isAssignableFrom(targetClass);
}
 
Example 33
Project: Ptoceti   File: GuiceFinder.java   Source Code and License 4 votes vote down vote up
public static GuiceFinder createGuiceFinder(Class<? extends ServerResource> targetClass, Context context, Logger logger) {
	return (GuiceFinder)GuiceFinder.createFinder( targetClass, GuiceFinder.class, context, logger);
}
 
Example 34
Project: geowave   File: GeoWaveOperationFinder.java   Source Code and License 4 votes vote down vote up
@Override
public Class<? extends ServerResource> getTargetClass() {
	return GeoWaveOperationServiceWrapper.class;
}
 
Example 35
Project: spring-restlet   File: WebAppDirectory.java   Source Code and License 4 votes vote down vote up
@Override
public ServerResource find(Request request, Response response) {
    StaticHeaderUtil.addResponseHeaders(response);
    return super.find(request, response);
}
 
Example 36
Project: spring-restlet   File: ResourceFinder.java   Source Code and License 4 votes vote down vote up
@Override
public ServerResource create(Request request, Response response) {
    return new RestletResource( resource);
}
 
Example 37
Project: SlipStreamServer   File: UserRouter.java   Source Code and License 4 votes vote down vote up
private void attachPaths(String[] paths,
		Class<? extends ServerResource> resourceClass) {
	attachPathsWithRole(paths, resourceClass, null);
}
 
Example 38
Project: SlipStreamServer   File: UserRouter.java   Source Code and License 4 votes vote down vote up
private void attachPathsWithSuper(String[] paths,
		Class<? extends ServerResource> resourceClass) {
	attachPathsWithRole(paths, resourceClass, SuperEnroler.Super);
}
 
Example 39
Project: SlipStreamServer   File: UserRouter.java   Source Code and License 4 votes vote down vote up
private void attachPathsWithRole(String[] paths,
		Class<? extends ServerResource> c, Role role) {
	for (String path : paths) {
		attachPath(path, c, role);
	}
}
 
Example 40
Project: restlet-framework   File: VirtualHost.java   Source Code and License 3 votes vote down vote up
/**
 * 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<? extends ServerResource> targetClass) {
    Finder result = super.createFinder(targetClass);
    result.setContext(getContext().createChildContext());
    return result;
}