OpenMRS 2.0 Development Examples

Fragments

Simple Controller-only Fragment

Imagine we want to create a fragment which, when included in a page, requires the user to be logged in to see that page. (In practice this fragment would only be useful on a home or menu page that doesn't call the API and do privilege checks "naturally".)

We will call our fragment 'maybeRequireLogin', and it will have only a controller, but no view. The controller would be:

package org.openmrs.ui2.fragment.controller; import org.openmrs.api.APIAuthenticationException; import org.openmrs.api.context.Context; /** * When you include this fragment in a page, then trying to view that page while not logged in will * send you back to the login page. To override this behavior, set the 'security.allowAnonymousBrowsing' * global property to 'true'. * This fragment has no display component. */ public class MaybeRequireLoginFragmentController { public void controller() { if (!Context.isAuthenticated()) { boolean allowAnonymousBrowsing = false; try { String gp = Context.getAdministrationService().getGlobalProperty("security.allowAnonymousBrowsing"); allowAnonymousBrowsing = Boolean.valueOf(gp); } catch (Exception ex) { } if (!allowAnonymousBrowsing) throw new APIAuthenticationException("Login is required"); } } }