Java Code Examples for org.restlet.Application

The following are top voted examples for showing how to use org.restlet.Application. 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
@Override
protected final void configure() {

    if (injector != null) {
        throw new IllegalStateException(
                "can't reconfigure with existing Injector");
    }

    if (!alreadyBound.get()) {
        alreadyBound.set(true);

        bind(FinderFactory.class).toInstance(this);

        bind(Application.class).toProvider(newApplicationProvider());
        bind(Context.class).toProvider(newContextProvider());
        bind(Request.class).toProvider(newRequestProvider());
        bind(Response.class).toProvider(newResponseProvider());
    }

    for (com.google.inject.Module module : modules) {
        install(module);
    }
}
 
Example 2
Project: restlet-framework   File: MemoryRealm.java   Source Code and License 6 votes vote down vote up
/**
 * Finds the roles mapped to a given user group.
 * 
 * @param application
 *            The parent application. Can't be null.
 * @param userGroup
 *            The user group.
 * @return The roles found.
 * @throws IllegalArgumentException
 *             If application is null.
 */
public Set<Role> findRoles(Application application, Group userGroup) {
    if (application == null) {
        throw new IllegalArgumentException(
                "The application argument can't be null");
    }

    Set<Role> result = new HashSet<Role>();
    Object source;

    for (RoleMapping mapping : getRoleMappings()) {
        source = mapping.getSource();

        if ((userGroup != null) && userGroup.equals(source)) {
            if (mapping.getTarget().getApplication() == application) {
                result.add(mapping.getTarget());
            }
        }
    }

    return result;
}
 
Example 3
Project: restlet-framework   File: MemoryRealm.java   Source Code and License 6 votes vote down vote up
/**
 * Finds the roles mapped to given user groups.
 * 
 * @param application
 *            The parent application. Can't be null.
 * @param userGroups
 *            The user groups.
 * @return The roles found.
 * @throws IllegalArgumentException
 *             If application is null.
 */
public Set<Role> findRoles(Application application, Set<Group> userGroups) {
    if (application == null) {
        throw new IllegalArgumentException(
                "The application argument can't be null");
    }

    Set<Role> result = new HashSet<Role>();
    Object source;

    for (RoleMapping mapping : getRoleMappings()) {
        source = mapping.getSource();

        if ((userGroups != null) && userGroups.contains(source)) {
            if (mapping.getTarget().getApplication() == application) {
                result.add(mapping.getTarget());
            }
        }
    }

    return result;
}
 
Example 4
Project: restlet-framework   File: MemoryRealm.java   Source Code and License 6 votes vote down vote up
/**
 * Finds the roles mapped to a given user, for a specific application.
 * 
 * @param application
 *            The parent application. Can't be null.
 * @param user
 *            The user.
 * @return The roles found.
 * @throws IllegalArgumentException
 *             If application is null.
 */
public Set<Role> findRoles(Application application, User user) {
    if (application == null) {
        throw new IllegalArgumentException(
                "The application argument can't be null");
    }

    Set<Role> result = new HashSet<Role>();
    Object source;

    for (RoleMapping mapping : getRoleMappings()) {
        source = mapping.getSource();

        if ((user != null) && user.equals(source)) {
            if (mapping.getTarget().getApplication() == application) {
                result.add(mapping.getTarget());
            }
        }
    }

    return result;
}
 
Example 5
Project: prudence   File: SerializableApplicationTask.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the application task.
 * 
 * @return The application task or null if the application was not found
 * @see InstanceUtil#getApplication(String)
 */
public ApplicationTask<T> getApplicationTask()
{
	if( applicationTask == null )
	{
		Application application = InstanceUtil.getApplication( applicationName );
		if( application != null )
		{
			if( code != null )
				applicationTask = new ApplicationTask<T>( application, code, context );
			else
				applicationTask = new ApplicationTask<T>( application, documentName, entryPointName, context );
		}
	}

	return applicationTask;
}
 
Example 6
Project: prudence   File: InstanceUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Gets an application associated with the current Prudence instance.
 * <p>
 * Expects that a map of applications was set in the
 * "com.threecrickets.prudence.applications" attribute of the component's
 * context.
 * 
 * @param name
 *        The application's full name
 * @return The application or null
 * @see #getComponent()
 */
public static Application getApplication( String name )
{
	Component component = getComponent();
	if( component != null )
	{
		ConcurrentMap<String, Object> attributes = component.getContext().getAttributes();
		if( attributes != null )
		{
			@SuppressWarnings("unchecked")
			Iterable<Application> applications = (Iterable<Application>) attributes.get( APPLICATIONS_ATTRIBUTE );
			if( applications != null )
				for( Application application : applications )
					if( name.equals( application.getName() ) )
						return application;
		}
	}

	return null;
}
 
Example 7
Project: xproclet   File: ClassResource.java   Source Code and License 6 votes vote down vote up
/** Creates a new instance of ClassResource */
public ClassResource(ClassLoader classLoader,String path)
{
   setNegotiated(false);
   this.classLoader = classLoader;
   this.path = path;
   int extPos = path.lastIndexOf('.');
   Application app = this.getApplication();
   type = app.getMetadataService().getDefaultMediaType(); 
   if (extPos>=0) {
      String ext = path.substring(extPos+1);
      Metadata mdata = this.getApplication().getMetadataService().getMetadata(ext);
      if (mdata!=null) {
         type = MediaType.valueOf(mdata.getName());
      }
   }
}
 
Example 8
Project: xproclet   File: LoginApplication.java   Source Code and License 6 votes vote down vote up
/** Creates a new instance of ClassResource */
public ClassResource(Class baseClass,String path)
{
   setNegotiated(false);
   this.baseClass = baseClass;
   this.path = path;
   int extPos = path.lastIndexOf('.');
   Application app = this.getApplication();
   type = app.getMetadataService().getDefaultMediaType(); 
   if (extPos>=0) {
      String ext = path.substring(extPos+1);
      Metadata mdata = this.getApplication().getMetadataService().getMetadata(ext);
      if (mdata!=null) {
         type = MediaType.valueOf(mdata.getName());
      }
   }
}
 
Example 9
Project: SlipStreamServer   File: ReportRouter.java   Source Code and License 6 votes vote down vote up
public ReportRouter(Context context, Application application) throws ConfigurationException, ValidationException {
	super(context);

	String reportsLocation = Configuration.getInstance().getProperty("slipstream.reports.location");

	Authorizer authorizer = new ReportsAuthorizer();
	Authenticator authenticator = new CookieAuthenticator(getContext());
	authenticator.setOptional(false);
	authenticator.setEnroler(new SuperEnroler(application));
	authenticator.setNext(authorizer);

	ResultsDirectory directory = new ResultsDirectory(getContext(), "file://" + reportsLocation);
	Filter decorator = new ReportDecorator();
	decorator.setNext(directory);
	authorizer.setNext(decorator);
	attach("", authenticator);
}
 
Example 10
Project: SlipStreamServer   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws ValidationException {

		Component component = new Component();

		component.getServers().add(Protocol.HTTP, 8182);
		component.getClients().add(Protocol.FILE);
		component.getClients().add(Protocol.HTTP);
		Application rootApplication = new RootApplication();
		component.getDefaultHost().attach("", rootApplication);

		try {
			component.start();
		} catch (Exception e) {
			log.log(Level.SEVERE, "Start error", e);
			log.severe("Starting SlipStream FAILED!");
			System.exit(1);
		}
		log.finest("SlipStream started!");
		log.finer("SlipStream started!");
		log.fine("SlipStream started!");
		log.info("SlipStream started!");
	}
 
Example 11
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 12
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 13
Project: bigstreams   File: CollectorDI.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a restlet application object with the correct router
 * configuration and resources added.
 * 
 * @return
 */
@Bean
public Application restApplication() {

	final Router router = new Router();

	attachFinder(router, "/collector/status",
			CollectorStatusResource.class, Template.MODE_STARTS_WITH);

	attachFinder(router, "/config", CollectorConfigResource.class,
			Template.MODE_STARTS_WITH);

	attachFinder(router, "/collector/shutdown", AppShutdownResource.class,
			Template.MODE_STARTS_WITH);

	attachFinder(router, "/collectors/status",
			CollectorsStatusResource.class, Template.MODE_STARTS_WITH);

	attachFinder(router, "/agents/status", AgentsStatusResource.class,
			Template.MODE_STARTS_WITH);

	attachFinder(router, "/agent/files", AgentStatusResource.class,
			Template.MODE_STARTS_WITH);
	attachFinder(router, "/agent/files?{query}", AgentStatusResource.class,
			Template.MODE_STARTS_WITH);

	Application app = new Application() {

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

	};

	return app;
}
 
Example 14
Project: bigstreams   File: CollectorDI.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a restlet application for the PingOKResource
 * 
 * @return
 */
@Bean
public Application restletPingApplication() {

	final Router router = new Router();
	attachFinder(router, "/", PingOKResource.class,
			Template.MODE_STARTS_WITH);

	Application app = new Application() {

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

	};

	return app;
}
 
Example 15
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 16
Project: restlet-framework   File: RestletGuice.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a {@link Provider}r for the current {@link Application}.
 * Override to use a custom Application provider.
 * 
 * @return A {@link Provider} for the current {@link Application}.
 */
protected Provider<Application> newApplicationProvider() {
    return new Provider<Application>() {
        public Application get() {
            return Application.getCurrent();
        }
    };
}
 
Example 17
Project: restlet-framework   File: ResourceInjectingApplication.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a new instance of {@link Router} linked to this application.
 * 
 * @return A new instance of {@link Router}.
 */
public Router newRouter() {
    final Application app = this;
    return new Router(getContext()) {
        @Override
        public Application getApplication() {
            return app;
        }
    };
}
 
Example 18
Project: restlet-framework   File: ApplicationHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 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) {
    Application current = Application.getCurrent();
    // Save the current application
    Application.setCurrent(getHelped());

    // Actually handle call
    try {
        super.handle(request, response);
    } finally {
        // restaure the current application
        Application.setCurrent(current);
    }
}
 
Example 19
Project: prudence   File: DocumentService.java   Source Code and License 5 votes vote down vote up
/**
 * Get a media type by its MIME type name.
 * 
 * @param name
 *        The MIME type name
 * @return The media type
 */
private static MediaType getMediaType( String name )
{
	MediaType mediaType = MediaType.valueOf( name );
	if( mediaType == null )
		mediaType = Application.getCurrent().getMetadataService().getMediaType( name );
	return mediaType;
}
 
Example 20
Project: prudence   File: LoggingUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Gets a Prudence application logger from a Restlet application logger.
 * 
 * @param application
 *        The Restlet application
 * @return The logger
 */
public static Logger getLogger( Application application )
{
	Logger logger = application.getLogger();

	String name = logger.getName();
	if( name.startsWith( RESTLET_LOGGER_PREFIX ) )
	{
		name = PRUDENCE_LOGGER_PREFIX + name.substring( RESTLET_LOGGER_PREFIX_LENGTH );
		logger = Engine.getLogger( name );
	}

	return logger;
}
 
Example 21
Project: prudence   File: ResolvingTemplate.java   Source Code and License 5 votes vote down vote up
/**
 * The constructor for the map resolver for the current application.
 * <p>
 * The constructor accepts a {@link Map} argument.
 * 
 * @return The constructor for the map resolver
 */
public static Constructor<Resolver<?>> getMapResolverConstructor()
{
	Application application = Application.getCurrent();
	if( application != null )
		return getMapResolverConstructor( application );
	else
		return null;
}
 
Example 22
Project: prudence   File: ResolvingTemplate.java   Source Code and License 5 votes vote down vote up
/**
 * The constructor for the call resolver for the current application.
 * <p>
 * The constructor accepts {@link Request} and {@link Response} arguments.
 * 
 * @return The constructor for the call resolver
 */
public static Constructor<Resolver<?>> getCallResolverConstructor()
{
	Application application = Application.getCurrent();
	if( application != null )
		return getCallResolverConstructor( application );
	else
		return null;
}
 
Example 23
Project: microservices-comparison   File: RestComponent.java   Source Code and License 5 votes vote down vote up
@Inject
public RestComponent(@Hello Application helloApp, @Car Application carApp, Verifier authTokenVerifier) {
    getClients().add(Protocol.HTTPS);
    Server secureServer = getServers().add(Protocol.HTTPS, 8043);
    Series<Parameter> parameters = secureServer.getContext().getParameters();
    parameters.add("sslContextFactory", "org.restlet.engine.ssl.DefaultSslContextFactory");
    parameters.add("keyStorePath", System.getProperty("javax.net.ssl.keyStorePath"));
    getDefaultHost().attach("/api/hello", secure(helloApp, authTokenVerifier, "ame"));
    getDefaultHost().attach("/api/cars", secure(carApp, authTokenVerifier, "ame"));
    replaceConverter(JacksonConverter.class, new JacksonCustomConverter());
}
 
Example 24
Project: microservices-comparison   File: RestComponent.java   Source Code and License 5 votes vote down vote up
private Restlet secure(Application app, Verifier verifier, String realm) {
    ChallengeAuthenticator guard = new ChallengeAuthenticator(getContext().createChildContext(),
            ChallengeScheme.HTTP_OAUTH_BEARER, realm);
    guard.setVerifier(verifier);
    guard.setNext(app);
    return guard;
}
 
Example 25
Project: ontopia   File: ContextUtils.java   Source Code and License 5 votes vote down vote up
public static Context getCurrentApplicationContext() {
	Application application = Application.getCurrent();
	if (application == null) {
		return null;
	}
	return application.getContext();
}
 
Example 26
Project: ontopia   File: OntopiaServlet.java   Source Code and License 5 votes vote down vote up
@Override
protected Application createApplication(Context parentContext) {
	Application application = super.createApplication(parentContext);
	
	if (application == null) {
		application = new OntopiaRestApplication(parentContext.createChildContext());
	}
	
	return application;
}
 
Example 27
Project: st-toolset   File: AbstractApplicationModule.java   Source Code and License 5 votes vote down vote up
private void configureRestlets() {
    bind(Application.class).to(getRestletApplication());

    final Map<String, String> params = new HashMap<>();
    params.put("org.restlet.application", getRestletApplication().getName());
    bind(RestletApplicationServlet.class).in(Scopes.SINGLETON);
    serve(getApiPrefix() + "/*").with(RestletApplicationServlet.class, params);
}
 
Example 28
Project: hobson-hub-core   File: Activator.java   Source Code and License 5 votes vote down vote up
private void registerRestletApplication(ServiceReference ref) {
    if (ref != null) {
        Object o = getContext().getService(ref);
        if (o instanceof HubWebApplication) {
            Application a = (Application)injector.getInstance(((HubWebApplication)o).getClazz());
            String path = ((HubWebApplication)o).getPath();
            appMap.put(path, a);
            registerRestletApplication(a, path);
        } else {
            logger.debug("Ignoring unknown published Restlet service: {}", o);
        }
    }
}
 
Example 29
Project: hobson-hub-core   File: Activator.java   Source Code and License 5 votes vote down vote up
private void unregisterRestletApplication(String path) {
    Application a = appMap.get(path);
    if (a != null) {
        unregisterRestletApplication(a);
        appMap.remove(path);
    }
}
 
Example 30
Project: hobson-hub-core   File: Activator.java   Source Code and License 5 votes vote down vote up
private void registerRestletApplication(Application a, String path) {
    if (path != null) {
        logger.debug("Registering Restlet application {} with path {}", a, path);
        component.getDefaultHost().attach(path, a);
    } else {
        logger.warn("Restlet application {} registered with no path; ignoring", a);
    }
}
 
Example 31
Project: geoar-codebase   File: CodebaseProperties.java   Source Code and License 5 votes vote down vote up
private CodebaseProperties(Application application) {
	// private constructor for singleton pattern

	this.p = new Properties();

	InputStream inStream = CodebaseProperties.class
			.getResourceAsStream(PROPERTIES_FILE);
	try {
		this.p.load(inStream);
	} catch (IOException e) {
		log.error("Cannot read properties file.", e);
	}

	//
	Series<Parameter> parameters = application.getContext().getParameters();
	this.codebasePath = parameters.getFirstValue(
			CODEBASE_PATH_CONTEXT_PARAM, true);
	this.imagePath = parameters.getFirstValue(IMAGE_PATH_CONTEXT_PARAM,
			true);
	this.sc = (ServletContext) application.getContext().getAttributes()
			.get("org.restlet.ext.servlet.ServletContext");

	String servicePath = parameters.getFirstValue(
			SERVICE_URL_CONTEXT_PARAM, true);

	this.downloadUrlPrefix = servicePath + "/" + CODEBASE_SERVICE_PARAM
			+ "/";
}
 
Example 32
Project: spring-restlet   File: XStreamSerializationTest.java   Source Code and License 5 votes vote down vote up
@Before
public void startServer() throws Exception {
	persistence = null;
	component = new Component();

	// The status service is disabled by default.
	component.getStatusService().setEnabled(false);

	component.getServers().add(Protocol.HTTP, portNumber);
	Application application = new Application() {

		@Override
		public Restlet createInboundRoot() {
			Router router = new Router(getContext());

			// Defines a route for the resource "list of customers"
			router.attach("/customers", CustomerResource.class);
			// Defines a route for the resource customer
			router.attach("/customers/{customerId}", CustomerResource.class);
			return router;
		}
	};
	// Attach the sample application.
	component.getDefaultHost().attach(application);
	component.start();

	Engine engine = Engine.getInstance();
	List<ConverterHelper> converters = engine.getRegisteredConverters();
	for (ConverterHelper converterHelper : converters) {
		if (converterHelper instanceof XstreamConverter) {
			xstreamConverter = (XstreamConverter) converterHelper;
			xstreamConverter.registerObjects(AnnotedCustomer.class);
			return;
		}
	}
	throw new RuntimeException("Xstream extension restlet module is required.");
}
 
Example 33
Project: spring-restlet   File: RestletSpringApplicationContextServlet.java   Source Code and License 5 votes vote down vote up
@Override
protected HttpServerHelper createServer(HttpServletRequest request) {
    HttpServerHelper server = super.createServer(request);
    String uriPattern = this.getContextPath(request) + request.getServletPath();

    String serverName = null;
    try {
        serverName = InetAddress.getLocalHost()
                .getCanonicalHostName();
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
    if (serverName == null) {
        serverName = request.getLocalName();
    }

    String baseUrl = new StringBuilder().append(request.getScheme())
            .append("://")
            .append(serverName)
            .append(':')
            .append(request.getLocalPort())
            .toString();

    Application application = getApplication();
    if (application instanceof RestletSpringApplication) {
        RestletSpringApplication bridge = (RestletSpringApplication) application;
        bridge.doAfterCreateServer(server, baseUrl, uriPattern);
    }
    return server;
}
 
Example 34
Project: spring-restlet   File: RestletSpringApplicationContextServlet.java   Source Code and License 5 votes vote down vote up
@Override
public void init() throws ServletException {
    /*
     * Logging configuration.
     *
     * Routes all incoming JUL (Java Util Logging) records to the SLF4j API. To avoid logging several times the same
     * line, handlers of JUL root logger are removed.
     */
    java.util.logging.Logger rootLogger = LogManager.getLogManager()
            .getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        rootLogger.removeHandler(handler);
    }
    SLF4JBridgeHandler.install();

    logger = LoggerFactory.getLogger(RestletSpringApplicationContextServlet.class);
    //Log4jWebConfigurer.initLogging(getServletContext());
    if (ContextLoader.getCurrentWebApplicationContext() == null) {
        this.contextLoader = createContextLoader();
        // test context spring exist
        if (ContextLoader.getCurrentWebApplicationContext() != null)
            this.contextLoader.initWebApplicationContext(getServletContext());
    }
    // initialize application before Component
    Application.setCurrent(getApplication());
    super.init();
    Application.setCurrent(null);

}
 
Example 35
Project: bigstreams   File: CollectorDI.java   Source Code and License 4 votes vote down vote up
/**
 * Configures a restlet component
 * 
 * @return
 * @throws Exception
 */
@Bean
public Component restletComponent() throws Exception {

	org.apache.commons.configuration.Configuration configuration = beanFactory
			.getBean(org.apache.commons.configuration.Configuration.class);

	// we must initialise velocity before hand.
	// a cleaner solution for this must be found in the future.

	final String templateDir = configuration.getString(
			CollectorProperties.WEB.VELOCITY_TEMPLATE_DIR.toString(),
			(String) CollectorProperties.WEB.VELOCITY_TEMPLATE_DIR
					.getDefaultValue());

	String logFile = configuration.getString(
			CollectorProperties.WEB.VELOCITY_LOG_FILE.toString(),
			(String) CollectorProperties.WEB.VELOCITY_LOG_FILE
					.getDefaultValue());

	RuntimeSingleton.setProperty(
			RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateDir);
	RuntimeSingleton.setProperty(RuntimeConstants.RUNTIME_LOG, logFile);
	RuntimeSingleton.init();

	LOG.info("Using templates: " + templateDir);
	LOG.info("Using display log file : " + logFile);

	Component component = new Component();

	int port = configuration.getInt(
			CollectorProperties.WRITER.COLLECTOR_MON_PORT.toString(),
			(Integer) CollectorProperties.WRITER.COLLECTOR_MON_PORT
					.getDefaultValue());

	LOG.info("Using collector monitoring port: " + port);

	component.getServers().add(org.restlet.data.Protocol.HTTP, port);
	component.getClients().add(org.restlet.data.Protocol.FILE);

	Application staticApp = new Application(component.getContext()) {
		@Override
		public Restlet createRoot() {
			return new Directory(getContext(), "file://"
					+ new File(templateDir).getAbsolutePath());
		}
	};

	component.getDefaultHost().attach("/view", restApplication());
	component.getDefaultHost().attach("/static", staticApp);
	component.getDefaultHost().attach("/images", staticApp);

	return component;
}
 
Example 36
Project: bigstreams   File: CoordinationDI.java   Source Code and License 4 votes vote down vote up
/**
 * Returns a restlet application object with the correct router
 * configuration and resources added.
 * 
 * @return
 */
@Bean
public Application restletApplication() {

	// CoordinationStatusResource
	final Router router = new Router();

	attachFinder(router, "/config", CoordinationConfigResource.class,
			Template.MODE_EQUALS);

	attachFinder(router, "/cluster/status",
			CoordinationClusterResource.class, Template.MODE_EQUALS);

	attachFinder(router, "/coordination/status",
			CoordinationStatusResource.class, Template.MODE_EQUALS);

	attachFinder(router, "/coordination/shutdown",
			AppShutdownResource.class, Template.MODE_EQUALS);

	attachFinder(router, "/files/list",
			CoordinationFileTrackingResource.class,
			Template.MODE_STARTS_WITH);
	attachFinder(router, "/files/count",
			CoordinationFileTrackingCountResource.class,
			Template.MODE_STARTS_WITH);

	attachFinder(router, "/agents/list",
			CoordinationAgentNamesResource.class, Template.MODE_STARTS_WITH);
	attachFinder(router, "/agents/count",
			CoordinationAgentCountResource.class, Template.MODE_STARTS_WITH);

	attachFinder(router, "/logTypes/list",
			CoordinationLogTypesResource.class, Template.MODE_STARTS_WITH);
	attachFinder(router, "/logTypes/count",
			CoordinationLogTypeCountResource.class,
			Template.MODE_STARTS_WITH);

	attachFinder(router, "/agent/{agent}/history",
			CoordinationFileTrackingHistoryResource.class,
			Template.MODE_STARTS_WITH);

	attachFinder(router, "/agents/latest",
			CoordinationHistoryAgentsLatestResource.class,
			Template.MODE_STARTS_WITH);

	attachFinder(router, "/collectors/latest",
			CoordinationHistoryCollectorsLatestResource.class,
			Template.MODE_STARTS_WITH);

	Application app = new Application() {

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

	};

	return app;
}
 
Example 37
Project: restlet-framework   File: StatusService.java   Source Code and License 4 votes vote down vote up
/**
 * Returns a representation for the given status. In order to customize the
 * default representation, this method can be overridden. It returns a
 * {@link org.restlet.message.Status} representation by default or a
 * {@link java.lang.Throwable} representation if the throwable is annotated
 * with {@link org.restlet.resource.Status}.
 * 
 * @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 toRepresentation(Status status, Request request,
        Response response) {
    Representation result = null;

    // Do content negotiation for status
    if (converterService != null && connegService != null
            && metadataService != null) {
        Object representationObject = null;

        // Serialize exception if any and if {@link
        // org.restlet.resource.Status} annotation asks for it
        Throwable cause = status.getThrowable();

        if (cause != null) {
            org.restlet.engine.resource.ThrowableAnnotationInfo tai = org.restlet.engine.resource.AnnotationUtils
                    .getInstance().getThrowableAnnotationInfo(
                            cause.getClass());

            if (tai != null && tai.isSerializable()) {
                if (Application.getCurrent() != null
                        && !Application.getCurrent().isDebugging()) {
                    // We clear the stack trace to prevent technical
                    // information leak
                    cause.setStackTrace(new StackTraceElement[] {});

                    if (cause.getCause() != null) {
                        Context.getCurrentLogger()
                                .warn("The cause of the exception should be null except in debug mode");
                    }
                }

                representationObject = cause;
            }
        }

        try {
            // Default representation match with the status properties
            if (representationObject == null) {
                representationObject = new StatusInfo(status,
                        getContactEmail(), getHomeRef().toString());
            }

            List<org.restlet.engine.resource.VariantInfo> variants = org.restlet.engine.converter.ConverterUtils
                    .getVariants(representationObject.getClass(), null);
            if (variants == null) {
                variants = new ArrayList<>();
            }

            Variant variant = connegService.getPreferredVariant(variants,
                    request, metadataService);
            result = converterService.toRepresentation(
                    representationObject, variant);
        } catch (Exception e) {
            Context.getCurrentLogger().warn(
                    "Could not serialize throwable class "
                            + ((cause == null) ? null : cause.getClass()),
                    e);
        }
    }
    return result;
}
 
Example 38
Project: polygene-java   File: PolygeneServerServlet.java   Source Code and License 4 votes vote down vote up
@Override
@SuppressWarnings( "unchecked" )
protected Application createApplication( Context context )
{
    return module.newObject( Application.class, context.createChildContext(), getServletConfig(), getServletContext() );
}
 
Example 39
Project: jemma.osgi.dal.web-apis   File: RestApplicationServlet.java   Source Code and License 4 votes vote down vote up
@Override
protected Application createApplication(Context context) {
	return new JemmaApplication();
}
 
Example 40
Project: fpgate   File: FPCBase.java   Source Code and License 4 votes vote down vote up
public static void log(Level level, String msg) {
    Application.getCurrent().getLogger().log(level, msg);
}
 
Example 41
Project: microservices-comparison   File: CarModule.java   Source Code and License 4 votes vote down vote up
@Override
protected void configure() {
    bind(Application.class).annotatedWith(Car.class).to(CarApplication.class);
    bind(CarRepository.class).to(InMemoryCarRepository.class);
}
 
Example 42
Project: microservices-comparison   File: HelloModule.java   Source Code and License 4 votes vote down vote up
@Override
protected void configure() {
    bind(Application.class).annotatedWith(Hello.class).to(HelloApplication.class);
    bind(CarService.class).to(RemoteCarService.class);
}
 
Example 43
Project: it.ismb.pert.osgi.dal.web-apis   File: RestApplicationServlet.java   Source Code and License 4 votes vote down vote up
@Override
protected Application createApplication(Context context)
{
	return new JemmaApplication();
}
 
Example 44
Project: st-toolset   File: RestletApplicationServlet.java   Source Code and License 4 votes vote down vote up
@Override
protected Application createApplication(final Context parentContext) {
    return applicationProvider.get();
}
 
Example 45
Project: xproclet   File: ConfiguredHost.java   Source Code and License 4 votes vote down vote up
AppInfo(Application app,Date edited) {
   this.app = app;
   this.edited = edited;
   this.match = null;
}
 
Example 46
Project: Ptoceti   File: ObixServlet.java   Source Code and License 4 votes vote down vote up
public ObixServlet(Application obixApplication) {
	super();
	this.obixApplication = obixApplication;
}
 
Example 47
Project: Ptoceti   File: ObixServlet.java   Source Code and License 4 votes vote down vote up
public Application getApplication(){
	return obixApplication;
}
 
Example 48
Project: Ptoceti   File: Oauth2Servlet.java   Source Code and License 4 votes vote down vote up
public Oauth2Servlet(Application oauth2Application) {
	super();
	this.oauth2Application = oauth2Application;
}
 
Example 49
Project: Ptoceti   File: Oauth2Servlet.java   Source Code and License 4 votes vote down vote up
public Application getApplication(){
	return oauth2Application;
}
 
Example 50
Project: Ptoceti   File: Oauth2ApplicationFactory.java   Source Code and License 4 votes vote down vote up
public  Application getApplication() {
	if( application == null){
		make();
	}
	return application;
}
 
Example 51
Project: Ptoceti   File: ObixApplicationFactory.java   Source Code and License 4 votes vote down vote up
private void make() {
	
	XMLConverter obixConverter = new XMLConverter();
	Engine.getInstance().getRegisteredConverters().add( obixConverter);
	
	JSonConverter jsonConverter = new JSonConverter();
	Engine.getInstance().getRegisteredConverters().add(jsonConverter);
	
	// remove standart JacksonConverter
	List<ConverterHelper> converters = Engine.getInstance().getRegisteredConverters();
               for (ConverterHelper converter : converters) {
                   if (converter instanceof JacksonConverter) {
                       converters.remove(converter);
                       break;
                   }
               }
               // and add our that add special mixins
               converters.add(new JacksonCustomConverter());
	
	application = new Application();
	Context context = new Context();
	application.setContext(context);
	
	guiceFinderFactory = new GuiceFinderFactory();
	
	root = new GuiceRouter(context);
	root.setFinderFactory(guiceFinderFactory);
	
	// Cors filter for cross domain requests
	CorsFilter corsFilter = new CorsFilter(root.getContext());		
	corsFilter.setNext(root);
	// attach resources to root
	addRoutes();

	// if the rest resources have to be secured, add verification up front.
	if( doSecure.booleanValue()){
		// Create authentifier, will attempt to authentify every request
		ChallengeAuthenticator authenticator = createAuthenticator();		
		// authorizer will block request on resources based on role for current authentified user
		//RoleAuthorizer roleAuth = createRoleAuthorizer();
		authenticator.setNext(corsFilter);
		//roleAuth.setNext(corsFilter);
		application.setInboundRoot(authenticator);
	} else {
		// otherwie just the cors filter
		application.setInboundRoot(corsFilter);
	}
	
	Activator.log(LogService.LOG_INFO, "Restlet application initialised.");
	//Engine.setRestletLogLevel(Level.OFF);
	
}
 
Example 52
Project: Ptoceti   File: ObixApplicationFactory.java   Source Code and License 4 votes vote down vote up
public  Application getApplication() {
	if( application == null){
		make();
	}
	return application;
}
 
Example 53
Project: hobson-hub-core   File: Activator.java   Source Code and License 4 votes vote down vote up
private void unregisterRestletApplication(Application a) {
    logger.debug("Unregistering Restlet application {}", a);
    component.getDefaultHost().detach(a);
}
 
Example 54
Project: geoar-codebase   File: CodebaseProperties.java   Source Code and License 4 votes vote down vote up
public static CodebaseProperties getInstance(Application application) {
	if (instance == null)
		instance = new CodebaseProperties(application);

	return instance;
}
 
Example 55
Project: spring-restlet   File: RestletSpringApplicationContextServlet.java   Source Code and License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected Application createApplication(Context parentContext) {
    Application application = super.createApplication(parentContext);
    try {
        registerComponent(application, RESTLET_APPLICATION_BEAN_NAME + "." + getServletConfig().getServletName());

    } catch (Exception e) {
        logger.error("Error while creating Restlet Application", e);
        throw new RuntimeException(e);
    };

    application.setName(getServletConfig().getServletName());

    application.setContext(parentContext.createChildContext());

    // setting logger explicitly, to override the stupid logger put there by
    // ServletContextAdapter
    application.getContext()
            .setLogger(application.getClass()
                    .getName());

    final Context applicationContext = application.getContext();
    String initParam;

    // Copy all the Servlet component initialization parameters
    final javax.servlet.ServletConfig servletConfig = getServletConfig();

    for (final Enumeration<String> enum1 = servletConfig.getInitParameterNames(); enum1.hasMoreElements();) {
        initParam = enum1.nextElement();

        applicationContext.getParameters()
                .add(initParam, servletConfig.getInitParameter(initParam));
    }

    // Copy all the Servlet application initialization parameters
    for (final Enumeration<String> enum1 = getServletContext().getInitParameterNames(); enum1.hasMoreElements();) {
        initParam = enum1.nextElement();

        applicationContext.getParameters()
                .add(initParam, getServletContext().getInitParameter(initParam));
    }

    this.serverAdapter = new ServletAdapter(this.getServletContext(), application);
    if (application instanceof RestletSpringApplication) {
        RestletSpringApplication bridge = (RestletSpringApplication) application;
        bridge.doAfterCreateApplication();
    }
    return application;
}
 
Example 56
Project: freedomotic   File: RestApi.java   Source Code and License 4 votes vote down vote up
@Override
public void onStart() {
    try {
        super.onStart();
        component = new Component();
        component.getClients().add(Protocol.FILE);
        //TODO: To test with the restlet 2.1 Maybe the maxTotalConnections could be avoided
        // see: http://restlet-discuss.1400322.n2.nabble.com/rejectedExecution-td4513620.html 
        //component.getServers().add(Protocol.HTTP, SERVER_PORT);
        Server server = new Server(Protocol.HTTP, SERVER_PORT);
        component.getServers().add(server);
        server.getContext().getParameters().add("maxTotalConnections", "50");
        //end TODO
        
        // enable SSL 
        Server SSLserver = new Server(Protocol.HTTPS, configuration.getIntProperty("SSL_PORT", SERVER_PORT + 2 ));
        component.getServers().add(SSLserver);
        Series<Parameter> parameters = SSLserver.getContext().getParameters();
        parameters.add("sslContextFactory", "org.restlet.ext.ssl.PkixSslContextFactory");
        // Certificate's data is taken from config file
        parameters.add("keystorePath", new File(this.getFile().getParent() + "/data/" + configuration.getStringProperty("KEYSTORE_FILE", "keystore")).getAbsolutePath());
        parameters.add("keystorePassword", configuration.getStringProperty("KEYSTORE_PASSWORD", "password"));
        parameters.add("keyPassword", configuration.getStringProperty("KEYSTORE_PASSWORD", "password"));
        parameters.add("keystoreType", configuration.getStringProperty("KEYSTORE_TYPE", "JKS")); 
        // end enable SSL
        
        // Engine.getInstance().getRegisteredServers().clear();
        // Engine.getInstance().getRegisteredServers().add(new HttpServerHelper(server));
        // Engine.getInstance().getRegisteredServers().add(new HttpServerHelper(SSLserver));
        component.getClients().add(Protocol.FILE);
        
        OriginFilter originFilter = new OriginFilter(component.getContext().createChildContext(),this);
        Application FDapp =  new FreedomRestServer(Info.PATHS.PATH_RESOURCES_FOLDER.getAbsolutePath(), component.getContext().createChildContext());  
        
        if (getApi().getAuth().isInited()) {
            // Instantiates a Verifier of identifier/secret couples based on Freedomotic Auth
            Verifier v = new SecretVerifier() {
                @Override
                public int verify(String identifier, char[] secret) {
                    if (getApi().getAuth().login(identifier, secret)) {
                        return RESULT_VALID;
                    }
                    return RESULT_INVALID;
                }
            };
            // Guard the restlet with BASIC authentication.
            ChallengeAuthenticator guard = new ChallengeAuthenticator(component.getContext().createChildContext(), false, ChallengeScheme.HTTP_BASIC, "testRealm", v);
            
            // WIP: Guard the restlet with DIGEST authentication.
            DigestAuthenticator dguard = new DigestAuthenticator(component.getContext().createChildContext(), "DigestRealm", configuration.getStringProperty("DIGEST_SECRET", "s3cr3t"));
            dguard.setOptional(true);
            // TODO: set proper verifier before enabling DIGEST AUTH.                
            
            originFilter.setNext(guard);
            guard.setNext(FDapp);
            
        } else {
            originFilter.setNext(FDapp);
        }

        component.getDefaultHost().attachDefault(originFilter);
        component.start();
        freedomoticApi = getApi();
    } catch (Exception ex) {
        Logger.getLogger(RestApi.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
Example 57
Project: SlipStreamServer   File: SuperEnroler.java   Source Code and License 4 votes vote down vote up
public SuperEnroler(Application application) {
	Super = new Role(application,
			"Privileged user (i.e. administrator)");
}
 
Example 58
Project: restlet-framework   File: Role.java   Source Code and License 3 votes vote down vote up
/**
 * Constructor.
 * 
 * @param application
 *            The parent application or null.
 * @param name
 *            The name.
 * @param description
 *            The description.
 */
public Role(Application application, String name, String description) {
    this.application = application;
    this.name = name;
    this.description = description;
    this.childRoles = new CopyOnWriteArrayList<Role>();
}
 
Example 59
Project: prudence   File: ApplicationTask.java   Source Code and License 3 votes vote down vote up
/**
 * Constructor.
 * 
 * @param application
 *        The Restlet application in which this task will execute
 * @param documentName
 *        The document name
 * @param entryPointName
 *        The entry point name or null
 * @param context
 *        The context made available to the task
 */
public ApplicationTask( Application application, String documentName, String entryPointName, Object context )
{
	attributes = new ApplicationTaskAttributes( application );
	this.application = application;
	this.documentName = documentName;
	this.entryPointName = entryPointName;
	this.context = context;
	code = null;
}
 
Example 60
Project: prudence   File: ApplicationTask.java   Source Code and License 3 votes vote down vote up
/**
 * Constructor.
 * 
 * @param application
 *        The Restlet application in which this task will execute
 * @param code
 *        The code to execute
 * @param context
 *        The context made available to the task
 */
public ApplicationTask( Application application, String code, Object context )
{
	attributes = new ApplicationTaskAttributes( application );
	this.application = application;
	this.code = code;
	this.context = context;
	documentName = getDocumentName( code );
	entryPointName = null;
}