text:
package org.keycloak.testsuite.federation.ldap.base;

import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runners.MethodSorters;
import org.keycloak.OAuth2Constants;
import org.keycloak.credential.CredentialModel;
import org.keycloak.federation.ldap.LDAPConfig;
import org.keycloak.federation.ldap.LDAPFederationProvider;
import org.keycloak.federation.ldap.LDAPFederationProviderFactory;
import org.keycloak.federation.ldap.idm.model.LDAPObject;
import org.keycloak.federation.ldap.mappers.FullNameLDAPFederationMapper;
import org.keycloak.federation.ldap.mappers.FullNameLDAPFederationMapperFactory;
import org.keycloak.federation.ldap.mappers.HardcodedLDAPRoleMapper;
import org.keycloak.federation.ldap.mappers.HardcodedLDAPRoleMapperFactory;
import org.keycloak.federation.ldap.mappers.UserAttributeLDAPFederationMapper;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.ModelException;
import org.keycloak.models.ModelReadOnlyException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserFederationMapperModel;
import org.keycloak.models.UserFederationProvider;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.AccessToken;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.federation.ldap.FederationTestUtils;
import org.keycloak.testsuite.pages.AccountPasswordPage;
import org.keycloak.testsuite.pages.AccountUpdateProfilePage;
import org.keycloak.testsuite.pages.AppPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.RegisterPage;
import org.keycloak.testsuite.rule.KeycloakRule;
import org.keycloak.testsuite.rule.LDAPRule;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.openqa.selenium.WebDriver;

import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

/**
 * @author Marek Posolda
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class FederationProvidersIntegrationTest {

    private static LDAPRule ldapRule = new LDAPRule();

    private static UserFederationProviderModel ldapModel = null;

    private static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {

        @Override
        public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
            FederationTestUtils.addLocalUser(manager.getSession(), appRealm, "marykeycloak", "mary@test.com", "password-app");

            Map<String,String> ldapConfig = ldapRule.getConfig();
            ldapConfig.put(LDAPConstants.SYNC_REGISTRATIONS, "true");
            ldapConfig.put(LDAPConstants.EDIT_MODE, UserFederationProvider.EditMode.WRITABLE.toString());

            ldapModel = appRealm.addUserFederationProvider(LDAPFederationProviderFactory.PROVIDER_NAME, ldapConfig, 0, "test-ldap", -1, -1, 0);
            FederationTestUtils.addZipCodeLDAPMapper(appRealm, ldapModel);

            // Delete all LDAP users and add some new for testing
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            FederationTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);

            LDAPObject john = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnkeycloak", "John", "Doe", "john@email.org", null, "1234");
            FederationTestUtils.updateLDAPPassword(ldapFedProvider, john, "Password1");

            LDAPObject existing = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "existing", "Existing", "Foo", "existing@email.org", null, "5678");

            appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
        }
    });

    @ClassRule
    public static TestRule chain = RuleChain
            .outerRule(ldapRule)
            .around(keycloakRule);

    @Rule
    public WebRule webRule = new WebRule(this);

    @WebResource
    protected OAuthClient oauth;

    @WebResource
    protected WebDriver driver;

    @WebResource
    protected AppPage appPage;

    @WebResource
    protected RegisterPage registerPage;

    @WebResource
    protected LoginPage loginPage;

    @WebResource
    protected AccountUpdateProfilePage profilePage;

    @WebResource
    protected AccountPasswordPage changePasswordPage;

//    @Test
//    @Ignore
//    public void runit() throws Exception {
//        Thread.sleep(10000000);
//
//    }

    @Test
    public void caseInSensitiveImport() {
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmManager manager = new RealmManager(session);
            RealmModel appRealm = manager.getRealm("test");
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            LDAPObject jbrown2 = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "JBrown2", "John", "Brown2", "jbrown2@email.org", null, "1234");
            FederationTestUtils.updateLDAPPassword(ldapFedProvider, jbrown2, "Password1");
            LDAPObject jbrown3 = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "jbrown3", "John", "Brown3", "JBrown3@email.org", null, "1234");
            FederationTestUtils.updateLDAPPassword(ldapFedProvider, jbrown3, "Password1");
        } finally {
            keycloakRule.stopSession(session, true);
        }

        loginSuccessAndLogout("jbrown2", "Password1");
        loginSuccessAndLogout("JBrown2", "Password1");
        loginSuccessAndLogout("jbrown2@email.org", "Password1");
        loginSuccessAndLogout("JBrown2@email.org", "Password1");

        loginSuccessAndLogout("jbrown3", "Password1");
        loginSuccessAndLogout("JBrown3", "Password1");
        loginSuccessAndLogout("jbrown3@email.org", "Password1");
        loginSuccessAndLogout("JBrown3@email.org", "Password1");
    }

    private void loginSuccessAndLogout(String username, String password) {
        loginPage.open();
        loginPage.login(username, password);
        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
        Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
        oauth.openLogout();
    }

    @Test
    public void caseInsensitiveSearch() {
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmManager manager = new RealmManager(session);
            RealmModel appRealm = manager.getRealm("test");
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            LDAPObject jbrown4 = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "JBrown4", "John", "Brown4", "jbrown4@email.org", null, "1234");
            FederationTestUtils.updateLDAPPassword(ldapFedProvider, jbrown4, "Password1");
            LDAPObject jbrown5 = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "jbrown5", "John", "Brown5", "JBrown5@Email.org", null, "1234");
            FederationTestUtils.updateLDAPPassword(ldapFedProvider, jbrown5, "Password1");
        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmManager manager = new RealmManager(session);
            RealmModel appRealm = manager.getRealm("test");

            // search by username
            List<UserModel> users = session.users().searchForUser("JBROwn4", appRealm);
            Assert.assertEquals(1, users.size());
            UserModel user4 = users.get(0);
            Assert.assertEquals("jbrown4", user4.getUsername());
            Assert.assertEquals("jbrown4@email.org", user4.getEmail());

            // search by email
            users = session.users().searchForUser("JBROwn5@eMAil.org", appRealm);
            Assert.assertEquals(1, users.size());
            UserModel user5 = users.get(0);
            Assert.assertEquals("jbrown5", user5.getUsername());
            Assert.assertEquals("jbrown5@email.org", user5.getEmail());
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    @Test
    public void deleteFederationLink() {
        loginLdap();
        {
            KeycloakSession session = keycloakRule.startSession();
            try {
                RealmManager manager = new RealmManager(session);

                RealmModel appRealm = manager.getRealm("test");
                appRealm.removeUserFederationProvider(ldapModel);
                Assert.assertEquals(0, appRealm.getUserFederationProviders().size());
            } finally {
                keycloakRule.stopSession(session, true);
            }
        }
        loginPage.open();
        loginPage.login("johnkeycloak", "Password1");
        loginPage.assertCurrent();

        Assert.assertEquals("Invalid username or password.", loginPage.getError());

        {
            KeycloakSession session = keycloakRule.startSession();
            try {
                RealmManager manager = new RealmManager(session);

                RealmModel appRealm = manager.getRealm("test");
                ldapModel = appRealm.addUserFederationProvider(ldapModel.getProviderName(), ldapModel.getConfig(), ldapModel.getPriority(), ldapModel.getDisplayName(), -1, -1, 0);
                FederationTestUtils.addZipCodeLDAPMapper(appRealm, ldapModel);
            } finally {
                keycloakRule.stopSession(session, true);
            }
        }
        loginLdap();

    }

    @Test
    public void loginClassic() {
        loginPage.open();
        loginPage.login("marykeycloak", "password-app");

        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
        Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));

    }

    @Test
    public void loginLdap() {
        loginPage.open();
        loginPage.login("johnkeycloak", "Password1");

        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
        Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));

        profilePage.open();
        Assert.assertEquals("John", profilePage.getFirstName());
        Assert.assertEquals("Doe", profilePage.getLastName());
        Assert.assertEquals("john@email.org", profilePage.getEmail());
    }

    @Test
    public void loginLdapWithDirectGrant() throws Exception {
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "johnkeycloak", "Password1");
        assertEquals(200, response.getStatusCode());
        AccessToken accessToken = oauth.verifyToken(response.getAccessToken());

        response = oauth.doGrantAccessTokenRequest("password", "johnkeycloak", "");
        assertEquals(401, response.getStatusCode());
    }

    @Test
    public void loginLdapWithEmail() {
        loginPage.open();
        loginPage.login("john@email.org", "Password1");

        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
        Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
    }

    @Test
    public void loginLdapWithoutPassword() {
        loginPage.open();
        loginPage.login("john@email.org", "");
        Assert.assertEquals("Invalid username or password.", loginPage.getError());
    }

    @Test
    public void passwordChangeLdap() throws Exception {
        changePasswordPage.open();
        loginPage.login("johnkeycloak", "Password1");
        changePasswordPage.changePassword("Password1", "New-password1", "New-password1");

        Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());

        changePasswordPage.logout();

        loginPage.open();
        loginPage.login("johnkeycloak", "Bad-password1");
        Assert.assertEquals("Invalid username or password.", loginPage.getError());

        loginPage.open();
        loginPage.login("johnkeycloak", "New-password1");
        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

        // Change password back to previous value
        changePasswordPage.open();
        changePasswordPage.changePassword("New-password1", "Password1", "Password1");
        Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
    }

    @Test
    public void registerExistingLdapUser() {
        loginPage.open();
        loginPage.clickRegister();
        registerPage.assertCurrent();

        // check existing username
        registerPage.register("firstName", "lastName", "email@mail.cz", "existing", "Password1", "Password1");
        registerPage.assertCurrent();
        Assert.assertEquals("Username already exists.", registerPage.getError());

        // Check existing email
        registerPage.register("firstName", "lastName", "existing@email.org", "nonExisting", "Password1", "Password1");
        registerPage.assertCurrent();
        Assert.assertEquals("Email already exists.", registerPage.getError());
    }

    @Test
    public void registerUserLdapSuccess() {
        loginPage.open();
        loginPage.clickRegister();
        registerPage.assertCurrent();

        registerPage.register("firstName", "lastName", "email2@check.cz", "registerUserSuccess2", "Password1", "Password1");
        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");
            UserModel user = session.users().getUserByUsername("registerUserSuccess2", appRealm);
            Assert.assertNotNull(user);
            Assert.assertNotNull(user.getFederationLink());
            Assert.assertEquals(user.getFederationLink(), ldapModel.getId());
        } finally {
            keycloakRule.stopSession(session, false);
        }
    }

    @Test
    public void testCaseSensitiveAttributeName() {
        KeycloakSession session = keycloakRule.startSession();

        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");

            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            LDAPObject johnZip = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnzip", "John", "Zip", "johnzip@email.org", null, "12398");

            // Remove default zipcode mapper and add the mapper for "POstalCode" to test case sensitivity
            UserFederationMapperModel currentZipMapper = appRealm.getUserFederationMapperByName(ldapModel.getId(), "zipCodeMapper");
            appRealm.removeUserFederationMapper(currentZipMapper);
            FederationTestUtils.addUserAttributeMapper(appRealm, ldapModel, "zipCodeMapper-cs", "postal_code", "POstalCode");

            // Fetch user from LDAP and check that postalCode is filled
            UserModel user = session.users().getUserByUsername("johnzip", appRealm);
            String postalCode = user.getFirstAttribute("postal_code");
            Assert.assertEquals("12398", postalCode);

        } finally {
            keycloakRule.stopSession(session, false);
        }
    }

    @Test
    public void testCommaInUsername() {
        KeycloakSession session = keycloakRule.startSession();
        boolean skip = false;

        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);

            // Workaround as comma is not allowed in sAMAccountName on active directory. So we will skip the test for this configuration
            LDAPConfig config = ldapFedProvider.getLdapIdentityStore().getConfig();
            if (config.isActiveDirectory() && config.getUsernameLdapAttribute().equals(LDAPConstants.SAM_ACCOUNT_NAME)) {
                skip = true;
            }

            if (!skip) {
                LDAPObject johnComma = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "john,comma", "John", "Comma", "johncomma@email.org", null, "12387");
                FederationTestUtils.updateLDAPPassword(ldapFedProvider, johnComma, "Password1");

                LDAPObject johnPlus = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "john+plus,comma", "John", "Plus", "johnplus@email.org", null, "12387");
                FederationTestUtils.updateLDAPPassword(ldapFedProvider, johnPlus, "Password1");
            }
        } finally {
            keycloakRule.stopSession(session, false);
        }

        if (!skip) {
            // Try to import the user with comma in username into Keycloak
            loginSuccessAndLogout("john,comma", "Password1");
            loginSuccessAndLogout("john+plus,comma", "Password1");
        }
    }

    @Test
    public void testDirectLDAPUpdate() {
        KeycloakSession session = keycloakRule.startSession();

        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");

            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            LDAPObject johnDirect = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johndirect", "John", "Direct", "johndirect@email.org", null, "12399");

            // Fetch user from LDAP and check that postalCode is filled
            UserModel user = session.users().getUserByUsername("johndirect", appRealm);
            String postalCode = user.getFirstAttribute("postal_code");
            Assert.assertEquals("12399", postalCode);

            // Directly update user in LDAP
            johnDirect.setSingleAttribute(LDAPConstants.POSTAL_CODE, "12400");
            johnDirect.setSingleAttribute(LDAPConstants.SN, "DirectLDAPUpdated");
            ldapFedProvider.getLdapIdentityStore().update(johnDirect);

        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");
            UserModel user = session.users().getUserByUsername("johndirect", appRealm);

            // Verify that postalCode is still the same as we read it's value from Keycloak DB
            user = session.users().getUserByUsername("johndirect", appRealm);
            String postalCode = user.getFirstAttribute("postal_code");
            Assert.assertEquals("12399", postalCode);

            // Check user.getAttributes()
            postalCode = user.getAttributes().get("postal_code").get(0);
            Assert.assertEquals("12399", postalCode);

            // LastName is new as lastName mapper will read the value from LDAP
            String lastName = user.getLastName();
            Assert.assertEquals("DirectLDAPUpdated", lastName);
        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");

            // Update postalCode mapper to always read the value from LDAP
            UserFederationMapperModel zipMapper = appRealm.getUserFederationMapperByName(ldapModel.getId(), "zipCodeMapper");
            zipMapper.getConfig().put(UserAttributeLDAPFederationMapper.ALWAYS_READ_VALUE_FROM_LDAP, "true");
            appRealm.updateUserFederationMapper(zipMapper);

            // Update lastName mapper to read the value from Keycloak DB
            UserFederationMapperModel lastNameMapper = appRealm.getUserFederationMapperByName(ldapModel.getId(), "last name");
            lastNameMapper.getConfig().put(UserAttributeLDAPFederationMapper.ALWAYS_READ_VALUE_FROM_LDAP, "false");
            appRealm.updateUserFederationMapper(lastNameMapper);

            // Verify that postalCode is read from LDAP now
            UserModel user = session.users().getUserByUsername("johndirect", appRealm);
            String postalCode = user.getFirstAttribute("postal_code");
            Assert.assertEquals("12400", postalCode);

            // Check user.getAttributes()
            postalCode = user.getAttributes().get("postal_code").get(0);
            Assert.assertEquals("12400", postalCode);

            Assert.assertFalse(user.getAttributes().containsKey(UserModel.LAST_NAME));

            // lastName is read from Keycloak DB now
            String lastName = user.getLastName();
            Assert.assertEquals("Direct", lastName);

        } finally {
            keycloakRule.stopSession(session, false);
        }
    }

    // TODO: Rather separate test for fullNameMapper to better test all the possibilities
    @Test
    public void testFullNameMapper() {
        KeycloakSession session = keycloakRule.startSession();
        UserFederationMapperModel firstNameMapper = null;

        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");

            // assert that user "fullnameUser" is not in local DB
            Assert.assertNull(session.users().getUserByUsername("fullname", appRealm));

            // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName)
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "fullname", "James Dee", "Dee", "fullname@email.org", null, "4578");

            // add fullname mapper to the provider and remove "firstNameMapper". For this test, we will simply map full name to the LDAP attribute, which was before firstName ( "givenName" on active directory, "cn" on other LDAP servers)
            firstNameMapper = appRealm.getUserFederationMapperByName(ldapModel.getId(), "first name");
            String ldapFirstNameAttributeName = firstNameMapper.getConfig().get(UserAttributeLDAPFederationMapper.LDAP_ATTRIBUTE);
            appRealm.removeUserFederationMapper(firstNameMapper);

            UserFederationMapperModel fullNameMapperModel = KeycloakModelUtils.createUserFederationMapperModel("full name", ldapModel.getId(), FullNameLDAPFederationMapperFactory.PROVIDER_ID,
                    FullNameLDAPFederationMapper.LDAP_FULL_NAME_ATTRIBUTE, ldapFirstNameAttributeName,
                    FullNameLDAPFederationMapper.READ_ONLY, "false");
            appRealm.addUserFederationMapper(fullNameMapperModel);
        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");

            // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
            FederationTestUtils.assertUserImported(session.users(), appRealm, "fullname", "James", "Dee", "fullname@email.org", "4578");

            // change mapper to writeOnly
            UserFederationMapperModel fullNameMapperModel = appRealm.getUserFederationMapperByName(ldapModel.getId(), "full name");
            fullNameMapperModel.getConfig().put(FullNameLDAPFederationMapper.WRITE_ONLY, "true");
            appRealm.updateUserFederationMapper(fullNameMapperModel);
        } finally {
            keycloakRule.stopSession(session, true);
        }

        // Assert changing user in Keycloak will change him in LDAP too...
        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");

            UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
            fullnameUser.setFirstName("James2");
            fullnameUser.setLastName("Dee2");
        } finally {
            keycloakRule.stopSession(session, true);
        }

        // Assert changed user available in Keycloak
        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");

            // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
            FederationTestUtils.assertUserImported(session.users(), appRealm, "fullname", "James2", "Dee2", "fullname@email.org", "4578");

            // Remove "fullnameUser" to assert he is removed from LDAP. Revert mappers to previous state
            UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
            session.users().removeUser(appRealm, fullnameUser);

            // Revert mappers
            UserFederationMapperModel fullNameMapperModel = appRealm.getUserFederationMapperByName(ldapModel.getId(), "full name");
            appRealm.removeUserFederationMapper(fullNameMapperModel);

            firstNameMapper.setId(null);
            appRealm.addUserFederationMapper(firstNameMapper);
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    @Test
    public void testHardcodedRoleMapper() {
        KeycloakSession session = keycloakRule.startSession();
        UserFederationMapperModel firstNameMapper = null;

        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");
            RoleModel hardcodedRole = appRealm.addRole("hardcoded-role");

            // assert that user "johnkeycloak" doesn't have hardcoded role
            UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
            Assert.assertFalse(john.hasRole(hardcodedRole));

            UserFederationMapperModel hardcodedMapperModel = KeycloakModelUtils.createUserFederationMapperModel("hardcoded role", ldapModel.getId(), HardcodedLDAPRoleMapperFactory.PROVIDER_ID,
                    HardcodedLDAPRoleMapper.ROLE, "hardcoded-role");
            appRealm.addUserFederationMapper(hardcodedMapperModel);
        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = new RealmManager(session).getRealmByName("test");
            RoleModel hardcodedRole = appRealm.getRole("hardcoded-role");

            // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
            UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
            Assert.assertTrue(john.hasRole(hardcodedRole));

            // Can't remove user from hardcoded role
            try {
                john.deleteRoleMapping(hardcodedRole);
                Assert.fail("Didn't expected to remove role mapping");
            } catch (ModelException expected) {
            }

            // Revert mappers
            UserFederationMapperModel hardcodedMapperModel = appRealm.getUserFederationMapperByName(ldapModel.getId(), "hardcoded role");
            appRealm.removeUserFederationMapper(hardcodedMapperModel);
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    @Test
    public void testImportExistingUserFromLDAP() throws Exception {
        // Add LDAP user with same email like existing model user
        keycloakRule.update(new KeycloakRule.KeycloakSetup() {

            @Override
            public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
                LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
                FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "marykeycloak", "Mary1", "Kelly1", "mary1@email.org", null, "123");
                FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "mary-duplicatemail", "Mary2", "Kelly2", "mary@test.com", null, "123");
                LDAPObject marynoemail = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "marynoemail", "Mary1", "Kelly1", null, null, "123");
                FederationTestUtils.updateLDAPPassword(ldapFedProvider, marynoemail, "Password1");
            }

        });

        // Try to import the duplicated LDAP user into Keycloak
        loginPage.open();
        loginPage.login("mary-duplicatemail", "password");
        Assert.assertEquals("Email already exists.", loginPage.getError());

        loginPage.login("mary1@email.org", "password");
        Assert.assertEquals("Username already exists.", loginPage.getError());

        loginSuccessAndLogout("marynoemail", "Password1");
    }

    @Test
    public void testReadonly() {
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");

            UserFederationProviderModel model = new UserFederationProviderModel(ldapModel.getId(), ldapModel.getProviderName(), ldapModel.getConfig(),
                    ldapModel.getPriority(), ldapModel.getDisplayName(), -1, -1, 0);
            model.getConfig().put(LDAPConstants.EDIT_MODE, UserFederationProvider.EditMode.READ_ONLY.toString());
            appRealm.updateUserFederationProvider(model);
            UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
            Assert.assertNotNull(user);
            Assert.assertNotNull(user.getFederationLink());
            Assert.assertEquals(user.getFederationLink(), ldapModel.getId());
            try {
                user.setEmail("error@error.com");
                Assert.fail("should fail");
            } catch (ModelReadOnlyException e) {

            }
            try {
                user.setLastName("Berk");
                Assert.fail("should fail");
            } catch (ModelReadOnlyException e) {

            }
            try {
                user.setFirstName("Bilbo");
                Assert.fail("should fail");
            } catch (ModelReadOnlyException e) {

            }
            try {
                UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1");
                session.userCredentialManager().updateCredential(appRealm, user, cred);
                Assert.fail("should fail");
            } catch (ModelReadOnlyException e) {

            }

            Assert.assertTrue(session.users().removeUser(appRealm, user));
        } finally {
            keycloakRule.stopSession(session, false);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");
            Assert.assertEquals(UserFederationProvider.EditMode.WRITABLE.toString(), appRealm.getUserFederationProviders().get(0).getConfig().get(LDAPConstants.EDIT_MODE));
        } finally {
            keycloakRule.stopSession(session, false);
        }
    }

    @Test
    public void testRemoveFederatedUser() {
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");
            UserModel user = session.users().getUserByUsername("registerUserSuccess2", appRealm);
            Assert.assertNotNull(user);
            Assert.assertNotNull(user.getFederationLink());
            Assert.assertEquals(user.getFederationLink(), ldapModel.getId());

            Assert.assertTrue(session.users().removeUser(appRealm, user));
            Assert.assertNull(session.users().getUserByUsername("registerUserSuccess2", appRealm));
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    @Test
    public void testSearch() {
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");
            LDAPFederationProvider ldapProvider = FederationTestUtils.getLdapProvider(session, ldapModel);

            FederationTestUtils.addLDAPUser(ldapProvider, appRealm, "username1", "John1", "Doel1", "user1@email.org", null, "121");
            FederationTestUtils.addLDAPUser(ldapProvider, appRealm, "username2", "John2", "Doel2", "user2@email.org", null, "122");
            FederationTestUtils.addLDAPUser(ldapProvider, appRealm, "username3", "John3", "Doel3", "user3@email.org", null, "123");
            FederationTestUtils.addLDAPUser(ldapProvider, appRealm, "username4", "John4", "Doel4", "user4@email.org", null, "124");

            // Users are not at local store at this moment
            Assert.assertNull(session.userStorage().getUserByUsername("username1", appRealm));
            Assert.assertNull(session.userStorage().getUserByUsername("username2", appRealm));
            Assert.assertNull(session.userStorage().getUserByUsername("username3", appRealm));
            Assert.assertNull(session.userStorage().getUserByUsername("username4", appRealm));

            // search by username
            session.users().searchForUser("username1", appRealm);
            FederationTestUtils.assertUserImported(session.userStorage(), appRealm, "username1", "John1", "Doel1", "user1@email.org", "121");

            // search by email
            session.users().searchForUser("user2@email.org", appRealm);
            FederationTestUtils.assertUserImported(session.userStorage(), appRealm, "username2", "John2", "Doel2", "user2@email.org", "122");

            // search by lastName
            session.users().searchForUser("Doel3", appRealm);
            FederationTestUtils.assertUserImported(session.userStorage(), appRealm, "username3", "John3", "Doel3", "user3@email.org", "123");

            // search by firstName + lastName
            session.users().searchForUser("John4 Doel4", appRealm);
            FederationTestUtils.assertUserImported(session.userStorage(), appRealm, "username4", "John4", "Doel4", "user4@email.org", "124");
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    @Test
    public void testSearchWithCustomLDAPFilter() {
        // Add custom filter for searching users
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");
            ldapModel.getConfig().put(LDAPConstants.CUSTOM_USER_SEARCH_FILTER, "(|(mail=user5@email.org)(mail=user6@email.org))");
            appRealm.updateUserFederationProvider(ldapModel);
        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            LDAPFederationProvider ldapProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            RealmModel appRealm = session.realms().getRealmByName("test");

            FederationTestUtils.addLDAPUser(ldapProvider, appRealm, "username5", "John5", "Doel5", "user5@email.org", null, "125");
            FederationTestUtils.addLDAPUser(ldapProvider, appRealm, "username6", "John6", "Doel6", "user6@email.org", null, "126");
            FederationTestUtils.addLDAPUser(ldapProvider, appRealm, "username7", "John7", "Doel7", "user7@email.org", null, "127");

            // search by email
            session.users().searchForUser("user5@email.org", appRealm);
            FederationTestUtils.assertUserImported(session.userStorage(), appRealm, "username5", "John5", "Doel5", "user5@email.org", "125");

            session.users().searchForUser("John6 Doel6", appRealm);
            FederationTestUtils.assertUserImported(session.userStorage(), appRealm, "username6", "John6", "Doel6", "user6@email.org", "126");

            session.users().searchForUser("user7@email.org", appRealm);
            session.users().searchForUser("John7 Doel7", appRealm);
            Assert.assertNull(session.userStorage().getUserByUsername("username7", appRealm));

            // Remove custom filter
            ldapModel.getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER);
            appRealm.updateUserFederationProvider(ldapModel);
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    @Test
    public void testUnsynced() throws Exception {
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");

            UserFederationProviderModel model = new UserFederationProviderModel(ldapModel.getId(), ldapModel.getProviderName(), ldapModel.getConfig(), ldapModel.getPriority(),
                    ldapModel.getDisplayName(), -1, -1, 0);
            model.getConfig().put(LDAPConstants.EDIT_MODE, UserFederationProvider.EditMode.UNSYNCED.toString());
            appRealm.updateUserFederationProvider(model);
            UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
            Assert.assertNotNull(user);
            Assert.assertNotNull(user.getFederationLink());
            Assert.assertEquals(user.getFederationLink(), ldapModel.getId());

            UserCredentialModel cred = UserCredentialModel.password("Candycand1");
            session.userCredentialManager().updateCredential(appRealm, user, cred);
            CredentialModel userCredentialValueModel = session.userCredentialManager().getStoredCredentialsByType(appRealm, user, CredentialModel.PASSWORD).get(0);
            Assert.assertEquals(UserCredentialModel.PASSWORD, userCredentialValueModel.getType());
            Assert.assertTrue(session.userCredentialManager().isValid(appRealm, user, cred));

            // LDAP password is still unchanged
            LDAPFederationProvider ldapProvider = FederationTestUtils.getLdapProvider(session, model);
            LDAPObject ldapUser = ldapProvider.loadLDAPUserByUsername(appRealm, "johnkeycloak");
            ldapProvider.getLdapIdentityStore().validatePassword(ldapUser, "Password1");

            // User is deleted just locally
            Assert.assertTrue(session.users().removeUser(appRealm, user));

            // Assert user not available locally, but will be reimported from LDAP once searched
            Assert.assertNull(session.userStorage().getUserByUsername("johnkeycloak", appRealm));
            Assert.assertNotNull(session.users().getUserByUsername("johnkeycloak", appRealm));
        } finally {
            keycloakRule.stopSession(session, false);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel appRealm = session.realms().getRealmByName("test");
            Assert.assertEquals(UserFederationProvider.EditMode.WRITABLE.toString(), appRealm.getUserFederationProviders().get(0).getConfig().get(LDAPConstants.EDIT_MODE));
        } finally {
            keycloakRule.stopSession(session, false);
        }
    }

}


text:
		<input type="checkbox"
		class="formly-field-checkbox input-lg"
		ng-model="model[options.key]">
		{{to.label}}
		{{to.required ? '*' : ''}}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _IAS_QS_SDF_Dir_OutputDriver_H_
#define _IAS_QS_SDF_Dir_OutputDriver_H_

#include "../Driver.h"
#include <qs/api.h>

namespace IAS {
namespace QS {
namespace SDF {
namespace Dir {

/*************************************************************************/
/** The OutputDriver class.
 *
 */
class OutputDriver : public SDF::OutputDriver {
public:

	virtual ~OutputDriver() throw();

	virtual bool send(Message* pMessage);

protected:

	OutputDriver(const API::Destination& destination);

	Mutex mutex;

	int    iCount;
	friend class Factory<OutputDriver>;

	IAS_DFT_FACTORY<Template>::PtrHolder ptrTemplate;
};

/*************************************************************************/
}
}
}
}

#endif /* _IAS_QS_SDF_Dir_OutputDriver_H_ */


text:
<?php
namespace TYPO3\CMS\Fluid\ViewHelpers\Uri;

/*                                                                        *
 * This script is part of the TYPO3 project - inspiring people to share!  *
 *                                                                        *
 * TYPO3 is free software; you can redistribute it and/or modify it under *
 * the terms of the GNU General Public License version 2 as published by  *
 * the Free Software Foundation.                                          *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General      *
 * Public License for more details.                                       *
 *                                                                        */

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3\CMS\Fluid\Core\ViewHelper\Facets\CompilableInterface;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;

/**
 * A ViewHelper to create uris from fields supported by the link wizard
 *
 * == Example ==
 *
 * {link} contains "19 - - - &X=y"
 * Please note that due to the nature of typolink you have to provide a
 * full set of parameters if you use the parameter only. Target, class
 * and title will be discarded.
 *
 *
 * <f:uri.typolink parameter="{link}" />
 * <output>
 * index.php?id=19&X=y
 * </output>
 *
 *
 *
 * <f:uri.typolink parameter="{link}" additionalParams="&u=b" />
 *
 * <output>
 * index.php?id=19&X=y&u=b
 * </output>
 *
 */
class TypolinkViewHelper extends AbstractViewHelper implements CompilableInterface
{
    /**
     * Render
     *
     * @param string $parameter stdWrap.typolink style parameter string
     * @param string $additionalParams
     *
     * @return string
     */
    public function render($parameter, $additionalParams = '')
    {
        return static::renderStatic(
            [
                'parameter' => $parameter,
                'additionalParams' => $additionalParams
            ],
            $this->buildRenderChildrenClosure(),
            $this->renderingContext
        );
    }

    /**
     * @param array $arguments
     * @param callable $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     *
     * @return string
     */
    public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
    {
        $parameter = $arguments['parameter'];
        $additionalParams = $arguments['additionalParams'];

        $content = '';
        if ($parameter) {
            $contentObject = GeneralUtility::makeInstance(ContentObjectRenderer::class);
            $content = $contentObject->typoLink_URL(
                [
                    'parameter' => self::createTypolinkParameterArrayFromArguments($parameter, $additionalParams),
                ]
            );
        }

        return $content;
    }

    /**
     * Transforms ViewHelper arguments to typo3link.parameters.typoscript option as array.
     *
     * @param string $parameter Example: 19 _blank - "testtitle with whitespace" &X=y
     * @param string $additionalParameters
     *
     * @return string The final TypoLink string
     */
    protected static function createTypolinkParameterArrayFromArguments($parameter, $additionalParameters = '')
    {
        $typoLinkCodec = GeneralUtility::makeInstance(TypoLinkCodecService::class);
        $typolinkConfiguration = $typoLinkCodec->decode($parameter);
        if (empty($typolinkConfiguration)) {
            return $typolinkConfiguration;
        }

        // Combine additionalParams
        if ($additionalParameters) {
            $typolinkConfiguration['additionalParams'] .= $additionalParameters;
        }

        return $typoLinkCodec->encode($typolinkConfiguration);
    }
}


text:
(function(angular) {
  'use strict';

  angular.module('htmlSortable', [])
    .directive('htmlSortable', [
      '$timeout', '$parse', function($timeout, $parse) {
        return {
          require: '?ngModel',
          link: function(scope, element, attrs, ngModel) {
            var opts, model;

            opts = angular.extend({}, scope.$eval(attrs.htmlSortable));
            element.sortable(opts);

            if (ngModel) {
              model = $parse(attrs.ngModel);

              ngModel.$render = function() {
                $timeout(function () {
                  element.sortable('reload');
                }, 50);
              };

              scope.$watch(model, function() {
                $timeout(function () {
                  element.sortable('reload');
                }, 50);
              }, true);

              element.sortable().bind('sortupdate', function(e, data) {
                var $source = data.startparent.attr('ng-model');
                var $dest   = data.endparent.attr('ng-model');

                var $sourceModel = $parse($source);
                var $destModel = $parse($dest);

                var $start = data.oldindex;
                var $end   = data.item.index();

                scope.$apply(function () {
                  if ($sourceModel(data.startparent.scope()) === $destModel(data.endparent.scope())) {
                    var $items = $sourceModel(data.startparent.scope());
                    $items.splice($end, 0, $items.splice($start, 1)[0]);
                    $sourceModel.assign(scope, $items);
                  }
                  else {
                    var $item = $sourceModel(data.startparent.scope())[$start];
                    var $sourceItems = $sourceModel(data.startparent.scope());
                    var $destItems = $destModel(data.endparent.scope()) || [];

                    $sourceItems.splice($start, 1);
                    $destItems.splice($end, 0, $item);

                    $sourceModel.assign(scope, $sourceItems);
                    $destModel.assign(scope, $destItems);
                  }
                });
              });
            }
          }
        };
      }
    ]);
}(angular));


text:
if(typeof(CKEDITOR) != 'undefined')
{
    CKEDITOR.editorConfig = function(config) {
        config.toolbar = [
            { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'RemoveFormat' ] },
            { name: 'links', items: [ 'Link'] },
            { name: 'insert', items: [ 'Image'] },
//            '/',
            { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
            { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
        ];    }
} else{
    console.log("ckeditor not loaded")
}
;


text:
namespace Dasher
{
    /// <summary>
    /// An enum whose members define how deserialisers behave when they encounter unexpected fields on complex types,
    /// or unexpected members in unions and enums.
    /// </summary>
    public enum UnexpectedFieldBehaviour
    {
        /// <summary>
        /// Unexpected fields/members raise exceptions.
        /// </summary>
        Throw,

        /// <summary>
        /// Unexpected fields/members are ignored.
        /// </summary>
        Ignore
    }
}


text:
'use strict';

var extend = require('util')._extend;
var logger = require('../logger/logger').logger;

var festivalsModel = require('festivals-model');
var FestivalNotFoundError = festivalsModel.error.FestivalNotFoundError;
var FestivalEventNotFoundError = festivalsModel.error.FestivalEventNotFoundError;
var FestivalPlaceNotFoundError = festivalsModel.error.FestivalPlaceNotFoundError;
var NewsNotFoundError = festivalsModel.error.NewsNotFoundError;
var FestivalCategoryNotFoundError = festivalsModel.error.FestivalCategoryNotFoundError;
var ServiceUnavailableError = festivalsModel.error.ServiceUnavailableError;

module.exports.provider = function provider(db) {
  var _festivalsRef = db.ref('festivals');
  var _festivalsEventsRef = db.ref('festivals-events');
  var _festivalsPlacesRef = db.ref('festivals-places');
  var _festivalsCategoriesRef = db.ref('festivals-categories');
  var _newsRef = db.ref('news');

  var changeFestivalCategoryCounter = function changeFestivalCategoryCounter(festivalId, change) {
    return _festivalsCategoriesRef
      .child(festivalId)
      .child('counter')
      .transaction(function updateFunction(counter) {
        return (counter || 0) + change;
      },
      function onComplete(error, committed, snapshot) {
        if (error) {
          logger.warn('firebase.changeFestivalCategoryCounter: ', error);
        } else if (!committed) {
          logger.info('firebase.changeFestivalCategoryCounter: skip');
        }

        var val = snapshot.val();
        logger.debug('firebase.changeFestivalCategoryCounter: ', val);

        if (val < 1) {
          return _festivalsCategoriesRef
            .child(festivalId)
            .child('counter')
            .remove(
            function onCompleteCounter(errorCounter) {

              if (errorCounter) {
                logger.warn('firebase.changeFestivalCategoryCounter: ', errorCounter);
              }
            });
        }

        return false;
      });
  };

  var changeFestivalPlaceCounter = function changeFestivalPlaceCounter(festivalId, change) {
    return _festivalsPlacesRef
      .child(festivalId)
      .child('counter')
      .transaction(function updateFunction(counter) {
        return (counter || 0) + change;
      },
      function onComplete(error, committed, snapshot) {
        if (error) {
          logger.warn('firebase.changeFestivalPlaceCounter: ', error);
        } else if (!committed) {
          logger.info('firebase.changeFestivalPlaceCounter: skip');
        }

        var val = snapshot.val();
        logger.debug('firebase.changeFestivalPlaceCounter: ', val);

        if (val < 1) {
          return _festivalsPlacesRef
            .child(festivalId)
            .child('counter')
            .remove(
            function onCompleteCounter(errorCounter) {

              if (errorCounter) {
                logger.warn('firebase.changeFestivalPlaceCounter: ', errorCounter);
              }
            });
        }

        return false;
      });
  };

  var changeFestivalCounter = function changeFestivalCounter(change) {
    return _festivalsRef
      .child('counter')
      .transaction(function updateFunction(counter) {
        return (counter || 0) + change;
      },
      function onComplete(error, committed, snapshot) {
        if (error) {
          logger.warn('firebase.changeFestivalCounter: ', error);
        } else if (!committed) {
          logger.info('firebase.changeFestivalCounter: skip');
        }

        var val = snapshot.val();
        logger.debug('firebase.changeFestivalCounter: ', val);

        if (val < 1) {
          return _festivalsRef
            .child('counter')
            .remove(
            function onCompleteCounter(errorCounter) {

              if (errorCounter) {
                logger.warn('firebase.changeFestivalCounter: ', errorCounter);
              }
            });
        }
        return false;
      });
  };

  var changeNewsCounter = function changeNewsCounter(festivalId, change) {
    return _newsRef
      .child(festivalId)
      .child('counter')
      .transaction(function updateFunction(counter) {
        return (counter || 0) + change;
      },
      function onComplete(error, committed, snapshot) {
        if (error) {
          logger.warn('firebase.changeNewsCounter: ', error);
        } else if (!committed) {
          logger.debug('firebase.changeNewsCounter: skip');
        }

        var val = snapshot.val();
        logger.debug('firebase.changeNewsCounter: ', val);

        if (val < 1) {
          return _newsRef
            .child(festivalId)
            .child('counter')
            .remove(
            function onCompleteCounter(errorCounter) {

              if (errorCounter) {
                logger.warn('firebase.changeNewsCounter: ', errorCounter);
              }
            });
        }
        return false;
      });
  };

  var changeFestivalEventsCounter = function changeFestivalEventsCounter(festivalId, change) {
    return _festivalsEventsRef
      .child(festivalId)
      .child('counter')
      .transaction(function updateFunction(counter) {
        return (counter || 0) + change;
      },
      function onComplete(error, committed, snapshot) {
        if (error) {
          logger.warn('firebase.changeFestivalEventsCounter: ', error);
        } else if (!committed) {
          logger.debug('firebase.changeFestivalEventsCounter: skip');
        }

        var val = snapshot.val();
        logger.debug('firebase.changeFestivalEventsCounter: ', val);

        if (val < 1) {
          return _festivalsEventsRef
            .child(festivalId)
            .child('counter')
            .remove(
            function onCompleteCounter(errorCounter) {

              if (errorCounter) {
                logger.warn('firebase.changeFestivalEventsCounter: ', errorCounter);
              }
            });
        }
        return false;
      });
  };

  var createFestival = function createFestival(newFestival, callback) {
    logger.args('createFestival: ', arguments);

    var festivalId = newFestival.id;

    return _festivalsRef
      .child('festivals')
      .child(festivalId)
      .set(newFestival, function (error) {

        if (error) {
          logger.warn('Unable to add festival', error);
          return callback(new ServiceUnavailableError('Unable to add festival'));
        }

        changeFestivalCounter(+1);

        return callback(null, newFestival);
      });
  };

  var updateFestival = function updateFestival(festivalId, newFestival, callback) {
    logger.args('updateFestival: ', arguments);

    return _festivalsRef
      .child('festivals')
      .child(festivalId)
      .transaction(function updateFunction(data) {
        if (data) {
          newFestival = extend(data, newFestival);
        }

        return newFestival;
      },
      function onComplete(error, committed, snapshot) {

        if (error) {
          logger.warn('firebase.updateFestival: ', error);
          return callback(new ServiceUnavailableError('Unable to add festival'));
        }

        if (!committed) {
          logger.debug('firebase.updateFestival: skip');
        }

        logger.debug('firebase.updateFestival: ', snapshot.val());
        return callback(error, snapshot.val());
      });
  };

  var getFestival = function getFestival(festivalId, callback) {
    logger.args('getFestival: ', arguments);

    return _festivalsRef
      .child('festivals')
      .child(festivalId)
      .once('value',
      function onSuccess(snapshot) {

        if (!snapshot.exists()) {
          return callback(new FestivalNotFoundError('Festival not found'));
        }

        return callback(null, snapshot.val());
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestival.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      });
  };

  var deleteFestival = function deleteFestival(festivalId, callback) {
    logger.args('getFestival: ', arguments);

    return _festivalsRef
      .child('festivals')
      .child(festivalId)
      .remove(
      function onCompleteCounter(errorCounter) {

        if (errorCounter) {
          logger.warn('firebase.deleteFestival: ', errorCounter);
          return callback(new FestivalNotFoundError('Festival not found'));
        }

        changeFestivalCounter(-1);

        return callback(null);
      });
  };

  var getFestivals = function getFestivals(searchFestivalsRequest, callback) {
    logger.args('getFestivals: ', arguments);

    var results = {
      total: 0,
      festivals: []
    };

    return _festivalsRef
      .child('counter')
      .once('value',
      function onSuccess(totalSnapshot) {

        results.total = totalSnapshot.val();

        var queryRef = _festivalsRef
          .child('festivals');

        if (searchFestivalsRequest.limit > 0) {
          queryRef = queryRef.limitToFirst(searchFestivalsRequest.limit);
        }

        return queryRef
          .once('value',
          function (snapshot) {
            var festivals = [];

            snapshot.forEach(function (childSnapshot) {
              festivals.push(childSnapshot.val());
            });

            results.festivals = festivals;

            return callback(null, results);
          },
          function onAuthError(err) {
            logger.warn('firebase.getFestivals.onAuthError: ', err);
            return callback(new ServiceUnavailableError('Forbidden access'));
          }
        );
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestivals.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      }
    );
  };

  var createFestivalEvent = function (festivalId, newEvent, callback) {
    logger.args('createFestivalEvent: ', arguments);

    var id = newEvent.id;

    return getFestival(festivalId, function (err, festival) {
      logger.debug('firebase.createFestivalEvent: getFestival', festival);

      if (err || !festival) {
        logger.debug(err);
        return callback(new FestivalNotFoundError('Festival not found'));
      }

      return _festivalsEventsRef
        .child(festivalId)
        .child('events')
        .child(id)
        .set(newEvent, function (error) {

          if (error) {
            logger.warn('Unable to add festival', error);
            return callback(new ServiceUnavailableError('Unable to add festival'));
          }

          changeFestivalEventsCounter(festivalId, +1);

          return callback(null, newEvent);
        });
    });
  };

  var updateFestivalEvent = function updateFestivalEvent(festivalId, eventId, newEvent, callback) {
    logger.args('updateFestivalEvent: ', arguments);

    return getFestival(festivalId, function (err, festival) {
      if (err || !festival) {
        logger.debug(err);
        return callback(new FestivalNotFoundError('Festival not found'));
      }

      return _festivalsEventsRef
        .child(festivalId)
        .child('events')
        .child(eventId)
        .transaction(function updateFunction(data) {
          if (data) {
            newEvent = extend(data, newEvent);
          }

          return newEvent;
        },
        function onComplete(error, committed, snapshot) {

          if (error) {
            logger.warn('firebase.updateFestivalEvent: ', error);
            return callback(new ServiceUnavailableError('Unable to update festival event'));
          }

          if (!committed) {
            logger.debug('firebase.updateFestivalEvent: skip');
          }

          logger.debug('firebase.updateFestivalEvent: ', snapshot.val());
          return callback(error, snapshot.val());
        });
    });
  };

  var getFestivalEvents = function (festivalId, searchFestivalEventsRequest, callback) {
    logger.args('getFestivalEvents: ', arguments);

    var results = {
      total: 0,
      events: []
    };

    return _festivalsEventsRef
      .child(festivalId)
      .child('counter')
      .once('value',
      function onSuccess(totalSnapshot) {

        if (totalSnapshot.val() === null || !totalSnapshot.exists()) {
          return callback(new FestivalNotFoundError('Festival not found'));
        }

        results.total = totalSnapshot.val();

        var queryRef = _festivalsEventsRef
          .child(festivalId)
          .child('events');

        if (searchFestivalEventsRequest.limit > 0) {
          queryRef = queryRef.limitToFirst(searchFestivalEventsRequest.limit);
        }

        return queryRef
          .once('value',
          function (snapshot) {
            var events = [];

            snapshot.forEach(function (childSnapshot) {
              events.push(childSnapshot.val());
            });

            results.events = events;

            return callback(null, results);
          },
          function onAuthError(err) {
            logger.warn('firebase.getFestivalEvents.onAuthError: ', err);
            return callback(new ServiceUnavailableError('Forbidden access'));
          }
        );
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestivalEvents.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      }
    );
  };

  var getFestivalEvent = function (festivalId, eventId, callback) {
    logger.args('getFestivalEvent: ', arguments);

    return _festivalsEventsRef
      .child(festivalId)
      .child('events')
      .child(eventId)
      .once('value',
      function onSuccess(snapshot) {

        if (!snapshot.exists()) {
          return callback(new FestivalEventNotFoundError('Festival event not found'));
        }

        return callback(null, snapshot.val());
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestivalEvent.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      });
  };

  var deleteFestivalEvent = function deleteFestivalEvent(festivalId, eventId, callback) {
    logger.args('deleteFestivalEvent: ', arguments);

    return _festivalsEventsRef
      .child(festivalId)
      .child('events')
      .child(eventId)
      .remove(
      function onCompleteCounter(errorCounter) {

        if (errorCounter) {
          logger.warn('firebase.deleteFestivalEvent: ', errorCounter);
          return callback(new FestivalEventNotFoundError('Festival event not found'));
        }

        changeFestivalEventsCounter(festivalId, -1);
        return callback(null);
      });
  };

  var createFestivalPlace = function createFestivalPlace(festivalId, newPlace, callback) {
    logger.args('createFestivalPlace: ', arguments);

    var id = newPlace.id;

    return getFestival(festivalId, function (err, festival) {
      logger.debug('firebase.createFestivalPlace: getFestival', festival);

      if (err || !festival) {
        logger.debug(err);
        return callback(new FestivalNotFoundError('Festival not found'));
      }

      return _festivalsPlacesRef
        .child(festivalId)
        .child('places')
        .child(id)
        .set(newPlace, function (error) {

          if (error) {
            logger.warn('Unable to add festival place', error);
            return callback(new ServiceUnavailableError('Unable to add festival place'));
          }

          changeFestivalPlaceCounter(festivalId, +1);

          return callback(null, newPlace);
        });
    });
  };

  var updateFestivalPlace = function updateFestivalPlace(festivalId, placeId, newPlace, callback) {
    logger.args('updateFestivalPlace: ', arguments);

    return _festivalsPlacesRef
      .child(festivalId)
      .child('places')
      .child(placeId)
      .transaction(function updateFunction(data) {
        if (data) {
          newPlace = extend(data, newPlace);
        }

        return newPlace;
      },
      function onComplete(error, committed, snapshot) {

        if (error) {
          logger.warn('firebase.updateFestivalPlace: ', error);
          return callback(new ServiceUnavailableError('Unable to update festival place'));
        }

        if (!committed) {
          logger.debug('firebase.updateFestivalPlace: skip');
        }

        logger.debug('firebase.updateFestivalPlace: ', snapshot.val());
        return callback(error, snapshot.val());
      });
  };

  var getFestivalPlaces = function (festivalId, searchFestivalPlacesRequest, callback) {
    logger.args('getFestivalPlaces: ', arguments);

    var results = {
      total: 0,
      places: []
    };

    return _festivalsPlacesRef
      .child(festivalId)
      .child('counter')
      .once('value',
      function onSuccess(totalSnapshot) {

        if (totalSnapshot.val() === null || !totalSnapshot.exists()) {
          return callback(new FestivalNotFoundError('Festival not found'));
        }

        results.total = totalSnapshot.val();

        var queryRef = _festivalsPlacesRef
          .child(festivalId)
          .child('places');

        if (searchFestivalPlacesRequest.limit > 0) {
          queryRef = queryRef.limitToFirst(searchFestivalPlacesRequest.limit);
        }

        return queryRef
          .once('value',
          function (snapshot) {
            var places = [];

            snapshot.forEach(function (childSnapshot) {
              places.push(childSnapshot.val());
            });

            results.places = places;

            return callback(null, results);
          },
          function onAuthError(err) {
            logger.warn('firebase.getFestivalPlaces.onAuthError: ', err);
            return callback(new ServiceUnavailableError('Forbidden access'));
          }
        );
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestivalPlaces.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      }
    );
  };

  var getFestivalPlace = function (festivalId, placeId, callback) {
    logger.args('getFestivalPlace: ', arguments);

    return _festivalsPlacesRef
      .child(festivalId)
      .child('places')
      .child(placeId)
      .once('value',
      function onSuccess(snapshot) {

        if (!snapshot.exists()) {
          return callback(new FestivalPlaceNotFoundError('Festival place not found'));
        }

        return callback(null, snapshot.val());
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestivalPlace.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      });
  };

  var deleteFestivalPlace = function deleteFestivalPlace(festivalId, placeId, callback) {
    logger.args('deleteFestivalPlace: ', arguments);

    return _festivalsPlacesRef
      .child(festivalId)
      .child('places')
      .child(placeId)
      .remove(
      function onCompleteCounter(errorCounter) {

        if (errorCounter) {
          logger.warn('firebase.deleteFestivalPlace: ', errorCounter);
          return callback(new FestivalPlaceNotFoundError('Festival place not found'));
        }

        changeFestivalPlaceCounter(festivalId, -1);

        return callback(null);
      });
  };

  var createFestivalCategory = function createFestivalCategory(festivalId, newCategory, callback) {
    logger.args('createFestivalCategory: ', arguments);

    var id = newCategory.id;

    return getFestival(festivalId, function (err, festival) {
      logger.debug('firebase.createFestivalCategory: getFestival', festival);

      if (err || !festival) {
        logger.debug(err);
        return callback(new FestivalNotFoundError('Festival not found'));
      }

      return _festivalsCategoriesRef
        .child(festivalId)
        .child('categories')
        .child(id)
        .set(newCategory, function (error) {

          if (error) {
            logger.warn('Unable to add festival category', error);
            return callback(new ServiceUnavailableError('Unable to add festival category'));
          }

          changeFestivalCategoryCounter(festivalId, +1);

          return callback(null, newCategory);
        });
    });
  };

  var updateFestivalCategory = function updateFestivalCategory(festivalId, categoryId, newCategory, callback) {
    logger.args('updateFestivalCategory: ', arguments);

    return _festivalsCategoriesRef
      .child(festivalId)
      .child('categories')
      .child(categoryId)
      .transaction(function updateFunction(data) {
        if (data) {
          newCategory = extend(data, newCategory);
        }

        return newCategory;
      },
      function onComplete(error, committed, snapshot) {

        if (error) {
          logger.warn('firebase.updateFestivalCategory: ', error);
          return callback(new ServiceUnavailableError('Unable to update festival category'));
        }

        if (!committed) {
          logger.debug('firebase.updateFestivalCategory: skip');
        }

        logger.debug('firebase.updateFestivalCategory: ', snapshot.val());
        return callback(error, snapshot.val());
      });
  };

  var getFestivalCategories = function (festivalId, searchFestivalCategoriesRequest, callback) {
    logger.args('getFestivalCategories: ', arguments);

    var results = {
      total: 0,
      categories: []
    };

    return _festivalsCategoriesRef
      .child(festivalId)
      .child('counter')
      .once('value',
      function onSuccess(totalSnapshot) {

        if (totalSnapshot.val() === null || !totalSnapshot.exists()) {
          return callback(new FestivalNotFoundError('Festival not found'));
        }

        results.total = totalSnapshot.val();

        var queryRef = _festivalsCategoriesRef
          .child(festivalId)
          .child('categories');

        if (searchFestivalCategoriesRequest.limit > 0) {
          queryRef = queryRef.limitToFirst(searchFestivalCategoriesRequest.limit);
        }

        return queryRef
          .once('value',
          function (snapshot) {
            var categories = [];

            snapshot.forEach(function (childSnapshot) {
              categories.push(childSnapshot.val());
            });

            results.categories = categories;

            return callback(null, results);
          },
          function onAuthError(err) {
            logger.warn('firebase.getFestivalCategories.onAuthError: ', err);
            return callback(new ServiceUnavailableError('Forbidden access'));
          }
        );
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestivalCategories.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      }
    );
  };

  var getFestivalCategory = function (festivalId, categoryId, callback) {
    logger.args('getFestivalCategory: ', arguments);

    return _festivalsCategoriesRef
      .child(festivalId)
      .child('categories')
      .child(categoryId)
      .once('value',
      function onSuccess(snapshot) {

        if (!snapshot.exists()) {
          return callback(new FestivalCategoryNotFoundError('Festival category not found'));
        }

        return callback(null, snapshot.val());
      },
      function onAuthError(err) {
        logger.warn('firebase.getFestivalCategory.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      });
  };

  var deleteFestivalCategory = function deleteFestivalCategory(festivalId, categoryId, callback) {
    logger.args('deleteFestivalCategory: ', arguments);

    return _festivalsCategoriesRef
      .child(festivalId)
      .child('categories')
      .child(categoryId)
      .remove(
      function onCompleteCounter(errorCounter) {

        if (errorCounter) {
          logger.warn('firebase.deleteFestivalCategory: ', errorCounter);
          return callback(new FestivalCategoryNotFoundError('Festival category not found'));
        }

        changeFestivalCategoryCounter(festivalId, -1);

        return callback(null);
      });
  };

  var getNewsCollection = function getNewsCollection(searchRequest, callback) {
    logger.args('getNewsCollection: ', arguments);

    var festivalId = searchRequest.festival;

    var results = {
      total: 0,
      news: []
    };

    return _newsRef
      .child(festivalId)
      .child('counter')
      .once('value',
      function onSuccess(totalSnapshot) {

        if (totalSnapshot.val() === null || !totalSnapshot.exists()) {
          return callback(null, results);
        }

        results.total = totalSnapshot.val();

        var queryRef = _newsRef;

        if (~~searchRequest.limit > 0) {
          queryRef = _newsRef.limitToFirst(~~searchRequest.limit);
        }

        return queryRef
          .once('value',
          function (snapshot) {
            var news = [];

            snapshot.forEach(function (childSnapshot) {
              news.push(childSnapshot.val());
            });

            results.news = news;

            return callback(null, results);
          },
          function onAuthError(err) {
            logger.warn('firebase.getNewsCollection.onAuthError: ', err);
            return callback(new ServiceUnavailableError('Forbidden access'));
          }
        );
      },
      function onAuthError(err) {
        logger.warn('firebase.getNewsCollection.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      }
    );
  };

  var createNews = function createNews(news, callback) {
    logger.args('createNews: ', arguments);

    var id = news.id;

    return _newsRef
      .child(id)
      .set(news, function (error) {

        if (error) {
          logger.warn('Unable to add news', error);
          return callback(new ServiceUnavailableError('Unable to add news'));
        }

        changeNewsCounter(id, +1);

        return callback(null, news);
      });
  };

  var getNews = function getNews(newsId, callback) {
    logger.args('getNews: ', arguments);

    return _newsRef
      .child(newsId)
      .once('value',
      function onSuccess(snapshot) {

        if (!snapshot.exists()) {
          return callback(new NewsNotFoundError('News not found'));
        }

        return callback(null, snapshot.val());
      },
      function onAuthError(err) {
        logger.warn('firebase.getNews.onAuthError: ', err);
        return callback(new ServiceUnavailableError('Forbidden access'));
      });
  };

  var updateNews = function updateNews(newsId, newNews, callback) {
    logger.args('updateNews: ', arguments);

    return _newsRef
      .child(newsId)
      .transaction(function updateFunction(data) {
        if (data) {
          newNews = extend(data, newNews);
        }

        return newNews;
      },
      function onComplete(error, committed, snapshot) {

        if (error) {
          logger.warn('firebase.updateNews: ', error);
          return callback(new ServiceUnavailableError('Unable to update news'));
        }

        if (!committed) {
          logger.debug('firebase.updateNews: skip');
        }

        logger.debug('firebase.updateNews: ', snapshot.val());
        return callback(error, snapshot.val());
      });
  };

  var deleteNews = function deleteNews(newsId, callback) {
    logger.args('deleteNews: ', arguments);

    return _newsRef
      .child(newsId)
      .remove(
      function onCompleteCounter(errorCounter) {

        if (errorCounter) {
          logger.warn('firebase.deleteNews: ', errorCounter);
          return callback(new NewsNotFoundError('News not found'));
        }

        changeNewsCounter(newsId, -1);

        return callback(null);
      });
  };

  return {
    createFestival: createFestival,
    updateFestival: updateFestival,
    getFestivals: getFestivals,
    getFestival: getFestival,
    deleteFestival: deleteFestival,
    createFestivalEvent: createFestivalEvent,
    updateFestivalEvent: updateFestivalEvent,
    getFestivalEvents: getFestivalEvents,
    getFestivalEvent: getFestivalEvent,
    deleteFestivalEvent: deleteFestivalEvent,
    createFestivalPlace: createFestivalPlace,
    updateFestivalPlace: updateFestivalPlace,
    getFestivalPlaces: getFestivalPlaces,
    getFestivalPlace: getFestivalPlace,
    deleteFestivalPlace: deleteFestivalPlace,
    createFestivalCategory: createFestivalCategory,
    updateFestivalCategory: updateFestivalCategory,
    getFestivalCategories: getFestivalCategories,
    getFestivalCategory: getFestivalCategory,
    deleteFestivalCategory: deleteFestivalCategory,
    getNewsCollection: getNewsCollection,
    createNews: createNews,
    getNews: getNews,
    updateNews: updateNews,
    deleteNews: deleteNews
  };
};


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [sip.js](./sip.js.md) > [SessionDescriptionHandler](./sip.js.sessiondescriptionhandler.md) > [peerConnectionDelegate](./sip.js.sessiondescriptionhandler.peerconnectiondelegate.md)

## SessionDescriptionHandler.peerConnectionDelegate property

A delegate which provides access to the peer connection event handlers.

<b>Signature:</b>

```typescript
get peerConnectionDelegate(): PeerConnectionDelegate | undefined;

set peerConnectionDelegate(delegate: PeerConnectionDelegate | undefined);
```

## Remarks

Use the peerConnectionDelegate to get access to the events associated with the RTCPeerConnection. For example...

Do NOT do this...

```ts
peerConnection.onicecandidate = (event) => {
  // do something
};
```
Instead, do this...

```
peerConnection.peerConnectionDelegate = {
  onicecandidate: (event) => {
    // do something
  }
};
```
Setting the peer connection event handlers directly is not supported and may break this class. As this class depends on exclusive access to them. This delegate is intended to provide access to the RTCPeerConnection events in a fashion which is supported.


text:
AtlasDB is a **Transactional Distributed Database Layer**

[**View the full documentation ▸**](https://palantir.github.io/atlasdb/html/index.html)

## Contributing
Please see our docs on [Contributing to AtlasDB](https://palantir.github.io/atlasdb/html/miscellaneous/contributing.html)

## License
This project is made available under the [Apache 2.0 license](https://github.com/palantir/atlasdb/blob/develop/LICENSE.txt).


text:
/* Forward declarations in ResourceMgr.h (DO NOT DELETE THIS LINE) */

#include <base/common.h>
#include <ResourceMgr.h>
#include <MemoryMgr.h>
#include <res/resource.h>
#include <mman/mman.h>

using namespace Executor;

typedef GUEST<ResType> *restypeptr;

static GUEST<restypeptr> *ar = 0;
static INTEGER inserttypes(resmaphand, INTEGER, Boolean);
static INTEGER initar(INTEGER);

#define ARRN_NOTINITTED (-1)
#define ARRN_ALL (-2)

static INTEGER arrn = ARRN_NOTINITTED;

void Executor::ROMlib_resTypesChanged() /* INTERNAL */
{
    if(ar)
        EmptyHandle((Handle)ar);
    arrn = ARRN_NOTINITTED;
}

static INTEGER inserttypes(resmaphand map, INTEGER ninserted, Boolean first)
{
    typref *tr;
    INTEGER i, j;
    GUEST<ResType> *next, *check;
    GUEST<ResType> candidate;

    next = *ar + ninserted;
    if(first)
    {
        WALKTR(map, i, tr)
        *next++ = tr->rtyp;
        EWALKTR(tr)
    }
    else
    {
        WALKTR(map, i, tr)
        candidate = tr->rtyp;
        check = *ar;
        for(j = ninserted - 1; --j > -1 && *check++ != candidate;)
            ;
        if(j <= -1)
        {
            *next++ = candidate;
            ninserted++;
        }
        EWALKTR(tr)
    }
    return next - *ar;
}

static INTEGER initar(INTEGER rn)
{
    Size mostbytesneeded;
    INTEGER ninserted;
    resmaphand map;
    Boolean first;

    if(arrn != rn)
    {
        mostbytesneeded = 0;
        if(rn >= 0)
        {
            if((map = ROMlib_rntohandl(rn, (Handle *)0)))
                mostbytesneeded = NUMTMINUS1(map) + 1;
        }
        else if(rn == ARRN_ALL)
        {
            WALKMAPTOP(map)
            mostbytesneeded += NUMTMINUS1(map) + 1;
            EWALKMAP()
        }
        mostbytesneeded *= sizeof(ResType);
        if(ar)
            ReallocateHandle((Handle)ar, mostbytesneeded);
        else
        {
            TheZoneGuard guard(LM(SysZone));

            ar = (GUEST<restypeptr> *)NewHandle(mostbytesneeded);
        }
        ninserted = 0;
        if(rn >= 0)
        {
            if((map = ROMlib_rntohandl(rn, (Handle *)0)))
                ninserted = inserttypes(map, ninserted, true);
        }
        else if(rn == ARRN_ALL)
        {
            first = true;
            WALKMAPTOP(map)
            ninserted = inserttypes(map, ninserted, first);
            first = false;
            EWALKMAP()
        }
        SetHandleSize((Handle)ar, (Size)ninserted * sizeof(ResType));
        arrn = rn;
    }
    return GetHandleSize((Handle)ar) / sizeof(ResType);
}

INTEGER Executor::C_CountTypes()
{
    return initar(ARRN_ALL);
}

INTEGER Executor::C_Count1Types() /* IMIV-15 */
{
    return initar(LM(CurMap));
}

void Executor::C_GetIndType(GUEST<ResType> *typ, INTEGER indx)
{
    if(indx <= 0 || indx > initar(ARRN_ALL))
        *typ = 0;
    else
        *typ = (*ar)[indx - 1];
}

void Executor::C_Get1IndType(GUEST<ResType> *typ, INTEGER indx) /* IMIV-15 */
{
    if(indx <= 0 || indx > initar(LM(CurMap)))
        *typ = 0;
    else
        *typ = (*ar)[indx - 1];
}


text:
// QUEUE FROM . JAVA

package cat.calidos.doodles.builders;

import cat.calidos.doodles.Queue;

public class QueueFrom {

public static Queue<String> strings(String... v) {

	Queue<String> a = new Queue<String>();
	for (String i : v) {
		a.enqueue(i);
	}

	return a;

}

public static Queue<Integer> ints(Integer... v) {

	Queue<Integer> a = new Queue<Integer>();
	for (Integer i : v) {
		a.enqueue(i);
	}

	return a;

}

}