class RestletRealmRouter extends Router {

    @Override
    protected void doHandle(Restlet next, Request request, Response response) {
        RealmInfo realmInfo = getRealmFromURI(request);

        if (realmInfo == null) {
            realmInfo = getRealmFromServerName(request);
        }
        if (next != delegateRoute) {
            String overrideRealm = getRealmFromQueryString(request);
            if (overrideRealm != null) {
                realmInfo = realmInfo.withOverrideRealm(overrideRealm);
            }
            request.getAttributes().put(REALM_URL, request.getResourceRef().getBaseRef().toString());
        }

        // Check that the path references an existing realm
        if (!realmValidator.isRealm(realmInfo.getAbsoluteRealm())) {
            String realm = realmInfo.getAbsoluteRealm();
            try {
                SSOToken adminToken = coreWrapper.getAdminToken();
                //Need to strip off leading '/' from realm otherwise just generates a DN based of the realm value, which is wrong
                if (realmInfo.getAbsoluteRealm().startsWith("/")) {
                    realm = realm.substring(1);
                }
                String orgDN = coreWrapper.getOrganization(adminToken, realm);
                realmInfo = realmInfo.withAbsoluteRealm(coreWrapper.convertOrgNameToRealmName(orgDN));
            } catch (IdRepoException | SSOException e) {
                throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid realm, " + realm);
            }
        }

        request.getAttributes().put(REALM, realmInfo.getAbsoluteRealm());
        request.getAttributes().put(REALM_INFO, realmInfo);
        HttpServletRequest httpRequest = ServletUtils.getRequest(request);
        httpRequest.setAttribute(REALM, realmInfo.getAbsoluteRealm());
        httpRequest.setAttribute(REALM_INFO, realmInfo);
        request.getAttributes().remove("subrealm");

        super.doHandle(next, request, response);
    }

    public  RestletRealmRouter(RestRealmValidator realmValidator, CoreWrapper coreWrapper);

}