Example usage for org.apache.commons.io FileUtils copyURLToFile

List of usage examples for org.apache.commons.io FileUtils copyURLToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyURLToFile.

Prototype

public static void copyURLToFile(URL source, File destination) throws IOException 

Source Link

Document

Copies bytes from the URL source to a file destination.

Usage

From source file:org.geoserver.script.wfs.WfsTxHookTest.java

File copyOverFile(String basename) throws Exception {
    File wfsTx = scriptMgr.getWfsTxRoot();
    File f = new File(wfsTx, basename + "." + getExtension());

    FileUtils.copyURLToFile(getClass().getResource(f.getName()), f);
    return f;/*from  ww w . ja va2 s.  co m*/
}

From source file:org.geoserver.script.wps.ScriptProcessTest.java

File copyScriptIfExists(String baseName) throws IOException {
    File wps = scriptMgr.getWpsRoot();
    File script = new File(wps, baseName + "." + getExtension());

    URL u = getClass().getResource(script.getName());
    if (u != null) {
        FileUtils.copyURLToFile(u, script);
        return script;
    }/*from  w  w w.  j av a 2s.  co m*/
    return null;
}

From source file:org.geoserver.script.wps.ScriptProcessTestSupport.java

protected File copyScriptIfExists(String baseName) throws IOException {
    File wps = scriptMgr.getWpsRoot();
    File directory;/*  w  w  w.  j a v a  2s  . c  o m*/
    if (getNamespace().equals(getExtension())) {
        directory = wps;
    } else {
        directory = new File(wps, getNamespace());
    }
    File script = new File(directory, baseName + "." + getExtension());

    URL u = getClass().getResource(script.getName());
    if (u != null) {
        FileUtils.copyURLToFile(u, script);
        return script;
    }
    return null;
}

From source file:org.geoserver.security.AbstractSecurityServiceTest.java

public static File unpackTestDataDir() throws Exception {
    URL url = AbstractSecurityServiceTest.class.getResource("/data_dir/default");
    if (!"file".equals(url.getProtocol())) {
        //means a dependency is using this directory via a jarfile, copy out manually
        File dataDir = File.createTempFile("data", "live", new File("./target"));
        dataDir.delete();//from ww  w.j a v a2 s  .com
        dataDir.mkdirs();

        //TODO: instead of harcoding files, dynamically read all subentries from the jar
        // and copy them out
        FileUtils.copyURLToFile(AbstractSecurityServiceTest.class.getResource("/data_dir/default/dummy.txt"),
                new File(dataDir, "dummy.txt"));
        return dataDir;
    }

    return DataUtilities.urlToFile(url);
}

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * converts an 2.1.x security configuration to 2.2.x
 * //w w  w .  j  a  v  a2s.  c om
 * @return <code>true</code> if migration has taken place  
 * @throws Exception
 */
boolean migrateFrom21() throws Exception {

    if (getRoleRoot(false) != null) {
        File oldUserFile = new File(getSecurityRoot(), "users.properties.old");
        if (oldUserFile.exists()) {
            LOGGER.warning(oldUserFile.getCanonicalPath() + " could be removed manually");
        }
        return false; // already migrated
    }

    LOGGER.info("Start security migration");

    //create required directories
    getRoleRoot();
    getUserGroupRoot();
    getAuthRoot();
    getPasswordPolicyRoot();
    getFilterRoot();
    getMasterPasswordProviderRoot();

    //master password configuration
    MasterPasswordProviderConfig mpProviderConfig = loadMasterPassswordProviderConfig("default");
    if (mpProviderConfig == null) {
        mpProviderConfig = new URLMasterPasswordProviderConfig();
        mpProviderConfig.setName("default");
        mpProviderConfig.setClassName(URLMasterPasswordProvider.class.getCanonicalName());
        mpProviderConfig.setReadOnly(false);

        ((URLMasterPasswordProviderConfig) mpProviderConfig).setURL(new URL("file:passwd"));
        ((URLMasterPasswordProviderConfig) mpProviderConfig).setEncrypting(true);
        saveMasterPasswordProviderConfig(mpProviderConfig, false);

        //save out the default master password
        MasterPasswordProvider mpProvider = loadMasterPasswordProvider(mpProviderConfig.getName());
        File propFile = new File(getSecurityRoot(), "users.properties");
        Properties userprops = null;
        if (propFile.exists())
            userprops = Util.loadPropertyFile(propFile);
        mpProvider.setMasterPassword(extractMasterPasswordForMigration(userprops));
    }

    MasterPasswordConfig mpConfig = new MasterPasswordConfig();
    mpConfig.setProviderName(mpProviderConfig.getName());
    saveMasterPasswordConfig(mpConfig);

    // check for services.properties, create if necessary
    File serviceFile = new File(getSecurityRoot(), "services.properties");
    if (serviceFile.exists() == false) {
        FileUtils.copyURLToFile(Util.class.getResource("serviceTemplate.properties"), serviceFile);
    }

    long checkInterval = 10000; // 10 secs

    //check for the default user group service, create if necessary
    GeoServerUserGroupService userGroupService = loadUserGroupService(XMLUserGroupService.DEFAULT_NAME);

    KeyStoreProvider keyStoreProvider = getKeyStoreProvider();
    keyStoreProvider.reloadKeyStore();
    keyStoreProvider.setUserGroupKey(XMLUserGroupService.DEFAULT_NAME,
            randomPasswdProvider.getRandomPassword(32));
    keyStoreProvider.storeKeyStore();

    PasswordValidator validator = loadPasswordValidator(PasswordValidator.DEFAULT_NAME);
    if (validator == null) {
        // Policy allows any password except null, this is the default
        // at before migration
        PasswordPolicyConfig pwpconfig = new PasswordPolicyConfig();
        pwpconfig.setName(PasswordValidator.DEFAULT_NAME);
        pwpconfig.setClassName(PasswordValidatorImpl.class.getName());
        pwpconfig.setMinLength(0);
        savePasswordPolicy(pwpconfig);
        validator = loadPasswordValidator(PasswordValidator.DEFAULT_NAME);
    }

    validator = loadPasswordValidator(PasswordValidator.MASTERPASSWORD_NAME);
    if (validator == null) {
        // Policy requires a minimum of 8 chars for the master password            
        PasswordPolicyConfig pwpconfig = new PasswordPolicyConfig();
        pwpconfig.setName(PasswordValidator.MASTERPASSWORD_NAME);
        pwpconfig.setClassName(PasswordValidatorImpl.class.getName());
        pwpconfig.setMinLength(8);
        savePasswordPolicy(pwpconfig);
        validator = loadPasswordValidator(PasswordValidator.MASTERPASSWORD_NAME);
    }

    if (userGroupService == null) {
        XMLUserGroupServiceConfig ugConfig = new XMLUserGroupServiceConfig();
        ugConfig.setName(XMLUserGroupService.DEFAULT_NAME);
        ugConfig.setClassName(XMLUserGroupService.class.getName());
        ugConfig.setCheckInterval(checkInterval);
        ugConfig.setFileName(XMLConstants.FILE_UR);
        ugConfig.setValidating(true);
        // start with weak encryption, plain passwords can be restored
        ugConfig.setPasswordEncoderName(
                loadPasswordEncoder(GeoServerPBEPasswordEncoder.class, null, false).getName());
        ugConfig.setPasswordPolicyName(PasswordValidator.DEFAULT_NAME);
        saveUserGroupService(ugConfig);
        userGroupService = loadUserGroupService(XMLUserGroupService.DEFAULT_NAME);
    }

    //check for the default role service, create if necessary
    GeoServerRoleService roleService = loadRoleService(XMLRoleService.DEFAULT_NAME);

    if (roleService == null) {
        XMLRoleServiceConfig gaConfig = new XMLRoleServiceConfig();
        gaConfig.setName(XMLRoleService.DEFAULT_NAME);
        gaConfig.setClassName(XMLRoleService.class.getName());
        gaConfig.setCheckInterval(checkInterval);
        gaConfig.setFileName(XMLConstants.FILE_RR);
        gaConfig.setValidating(true);
        gaConfig.setAdminRoleName(XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE);
        gaConfig.setGroupAdminRoleName(XMLRoleService.DEFAULT_LOCAL_GROUP_ADMIN_ROLE);
        saveRoleService(gaConfig);
        roleService = loadRoleService(XMLRoleService.DEFAULT_NAME);
    }

    String filterName = GeoServerSecurityFilterChain.BASIC_AUTH_FILTER;
    GeoServerSecurityFilter filter = loadFilter(filterName);
    if (filter == null) {
        BasicAuthenticationFilterConfig bfConfig = new BasicAuthenticationFilterConfig();
        bfConfig.setName(filterName);
        bfConfig.setClassName(GeoServerBasicAuthenticationFilter.class.getName());
        bfConfig.setUseRememberMe(true);
        saveFilter(bfConfig);
    }
    /*filterName = GeoServerSecurityFilterChain.BASIC_AUTH_NO_REMEMBER_ME_FILTER;
    filter = loadFilter(filterName);                  
    if (filter==null) {
    BasicAuthenticationFilterConfig bfConfig = new BasicAuthenticationFilterConfig();
    bfConfig.setClassName(GeoServerBasicAuthenticationFilter.class.getName());
    bfConfig.setName(filterName);
    bfConfig.setUseRememberMe(false);
    saveFilter(bfConfig);
    }*/
    filterName = GeoServerSecurityFilterChain.FORM_LOGIN_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        UsernamePasswordAuthenticationFilterConfig upConfig = new UsernamePasswordAuthenticationFilterConfig();
        upConfig.setClassName(GeoServerUserNamePasswordAuthenticationFilter.class.getName());
        upConfig.setName(filterName);
        upConfig.setUsernameParameterName(UsernamePasswordAuthenticationFilterConfig.DEFAULT_USERNAME_PARAM);
        upConfig.setPasswordParameterName(UsernamePasswordAuthenticationFilterConfig.DEFAULT_PASSWORD_PARAM);
        saveFilter(upConfig);
    }
    filterName = GeoServerSecurityFilterChain.SECURITY_CONTEXT_ASC_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityContextPersistenceFilterConfig pConfig = new SecurityContextPersistenceFilterConfig();
        pConfig.setClassName(GeoServerSecurityContextPersistenceFilter.class.getName());
        pConfig.setName(filterName);
        pConfig.setAllowSessionCreation(true);
        saveFilter(pConfig);
    }
    filterName = GeoServerSecurityFilterChain.SECURITY_CONTEXT_NO_ASC_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityContextPersistenceFilterConfig pConfig = new SecurityContextPersistenceFilterConfig();
        pConfig.setClassName(GeoServerSecurityContextPersistenceFilter.class.getName());
        pConfig.setName(filterName);
        pConfig.setAllowSessionCreation(false);
        saveFilter(pConfig);
    }
    filterName = GeoServerSecurityFilterChain.ANONYMOUS_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        AnonymousAuthenticationFilterConfig aConfig = new AnonymousAuthenticationFilterConfig();
        aConfig.setClassName(GeoServerAnonymousAuthenticationFilter.class.getName());
        aConfig.setName(filterName);
        saveFilter(aConfig);
    }
    filterName = GeoServerSecurityFilterChain.REMEMBER_ME_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        RememberMeAuthenticationFilterConfig rConfig = new RememberMeAuthenticationFilterConfig();
        rConfig.setClassName(GeoServerRememberMeAuthenticationFilter.class.getName());
        rConfig.setName(filterName);
        saveFilter(rConfig);
    }
    filterName = GeoServerSecurityFilterChain.FILTER_SECURITY_INTERCEPTOR;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityInterceptorFilterConfig siConfig = new SecurityInterceptorFilterConfig();
        siConfig.setClassName(GeoServerSecurityInterceptorFilter.class.getName());
        siConfig.setName(filterName);
        siConfig.setAllowIfAllAbstainDecisions(false);
        siConfig.setSecurityMetadataSource("geoserverMetadataSource");
        saveFilter(siConfig);
    }
    filterName = GeoServerSecurityFilterChain.FILTER_SECURITY_REST_INTERCEPTOR;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityInterceptorFilterConfig siConfig = new SecurityInterceptorFilterConfig();
        siConfig.setClassName(GeoServerSecurityInterceptorFilter.class.getName());
        siConfig.setName(filterName);
        siConfig.setAllowIfAllAbstainDecisions(false);
        siConfig.setSecurityMetadataSource("restFilterDefinitionMap");
        saveFilter(siConfig);
    }
    filterName = GeoServerSecurityFilterChain.FORM_LOGOUT_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        LogoutFilterConfig loConfig = new LogoutFilterConfig();
        loConfig.setClassName(GeoServerLogoutFilter.class.getName());
        loConfig.setName(filterName);
        saveFilter(loConfig);
    }
    filterName = GeoServerSecurityFilterChain.DYNAMIC_EXCEPTION_TRANSLATION_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        ExceptionTranslationFilterConfig bfConfig = new ExceptionTranslationFilterConfig();
        bfConfig.setClassName(GeoServerExceptionTranslationFilter.class.getName());
        bfConfig.setName(filterName);
        bfConfig.setAuthenticationFilterName(null);
        bfConfig.setAccessDeniedErrorPage("/accessDenied.jsp");
        saveFilter(bfConfig);
    }
    filterName = GeoServerSecurityFilterChain.GUI_EXCEPTION_TRANSLATION_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        ExceptionTranslationFilterConfig bfConfig = new ExceptionTranslationFilterConfig();
        bfConfig.setClassName(GeoServerExceptionTranslationFilter.class.getName());
        bfConfig.setName(filterName);
        bfConfig.setAuthenticationFilterName(GeoServerSecurityFilterChain.FORM_LOGIN_FILTER);
        bfConfig.setAccessDeniedErrorPage("/accessDenied.jsp");
        saveFilter(bfConfig);
    }

    //check for the default auth provider, create if necessary
    GeoServerAuthenticationProvider authProvider = (GeoServerAuthenticationProvider) loadAuthenticationProvider(
            GeoServerAuthenticationProvider.DEFAULT_NAME);
    if (authProvider == null) {
        UsernamePasswordAuthenticationProviderConfig upAuthConfig = new UsernamePasswordAuthenticationProviderConfig();
        upAuthConfig.setName(GeoServerAuthenticationProvider.DEFAULT_NAME);
        upAuthConfig.setClassName(UsernamePasswordAuthenticationProvider.class.getName());
        upAuthConfig.setUserGroupServiceName(userGroupService.getName());

        saveAuthenticationProvider(upAuthConfig);
        authProvider = loadAuthenticationProvider(GeoServerAuthenticationProvider.DEFAULT_NAME);
    }

    //save the top level config
    SecurityManagerConfig config = new SecurityManagerConfig();
    config.setRoleServiceName(roleService.getName());
    config.getAuthProviderNames().add(authProvider.getName());
    config.setEncryptingUrlParams(false);

    // start with weak encryption
    config.setConfigPasswordEncrypterName(
            loadPasswordEncoder(GeoServerPBEPasswordEncoder.class, true, false).getName());

    // setup the default remember me service
    RememberMeServicesConfig rememberMeConfig = new RememberMeServicesConfig();
    rememberMeConfig.setClassName(GeoServerTokenBasedRememberMeServices.class.getName());
    config.setRememberMeService(rememberMeConfig);

    config.setFilterChain(GeoServerSecurityFilterChain.createInitialChain());
    saveSecurityConfig(config);

    //TODO: just call initializeFrom
    userGroupService.setSecurityManager(this);
    roleService.setSecurityManager(this);

    //populate the user group and role service
    GeoServerUserGroupStore userGroupStore = userGroupService.createStore();
    GeoServerRoleStore roleStore = roleService.createStore();

    //migrate from users.properties
    File usersFile = new File(getSecurityRoot(), "users.properties");
    if (usersFile.exists()) {
        //load user.properties populate the services 
        Properties props = Util.loadPropertyFile(usersFile);

        UserAttributeEditor configAttribEd = new UserAttributeEditor();

        for (Iterator<Object> iter = props.keySet().iterator(); iter.hasNext();) {
            // the attribute editors parses the list of strings into password, username and enabled
            // flag
            String username = (String) iter.next();
            configAttribEd.setAsText(props.getProperty(username));

            // if the parsing succeeded turn that into a user object
            UserAttribute attr = (UserAttribute) configAttribEd.getValue();
            if (attr != null) {
                GeoServerUser user = userGroupStore.createUserObject(username, attr.getPassword(),
                        attr.isEnabled());
                userGroupStore.addUser(user);

                for (GrantedAuthority auth : attr.getAuthorities()) {
                    String roleName = GeoServerRole.ADMIN_ROLE.getAuthority().equals(auth.getAuthority())
                            ? XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE
                            : auth.getAuthority();
                    GeoServerRole role = roleStore.getRoleByName(roleName);
                    if (role == null) {
                        role = roleStore.createRoleObject(roleName);
                        roleStore.addRole(role);
                    }
                    roleStore.associateRoleToUser(role, username);
                }
            }
        }
    } else {
        // no user.properties, populate with default user and roles
        if (userGroupService.getUserByUsername(GeoServerUser.ADMIN_USERNAME) == null) {
            userGroupStore.addUser(GeoServerUser.createDefaultAdmin());
            GeoServerRole localAdminRole = roleStore.createRoleObject(XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE);
            roleStore.addRole(localAdminRole);
            roleStore.associateRoleToUser(localAdminRole, GeoServerUser.ADMIN_USERNAME);
        }
    }

    //add the local group administrator role
    if (roleStore.getRoleByName(XMLRoleService.DEFAULT_LOCAL_GROUP_ADMIN_ROLE) == null) {
        roleStore.addRole(roleStore.createRoleObject(XMLRoleService.DEFAULT_LOCAL_GROUP_ADMIN_ROLE));
    }

    // replace all occurrences of ROLE_ADMINISTRATOR  in the property files
    // TODO Justin, a little bit brute force, is this ok ?
    for (String filename : new String[] { "services.properties", "layers.properties", "rest.properties" }) {
        File file = new File(getSecurityRoot(), filename);
        if (file.exists() == false)
            continue;
        List<String> lines = new ArrayList<String>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null)
            lines.add(line.replace(GeoServerRole.ADMIN_ROLE.getAuthority(),
                    XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE));
        reader.close();
        PrintWriter writer = new PrintWriter(new FileWriter(file));
        for (String s : lines) {
            writer.println(s);
        }
        writer.close();
    }

    // check for roles in services.properties but not in user.properties 
    serviceFile = new File(getSecurityRoot(), "services.properties");
    if (serviceFile.exists()) {
        Properties props = Util.loadPropertyFile(serviceFile);
        for (Entry<Object, Object> entry : props.entrySet()) {
            StringTokenizer tokenizer = new StringTokenizer((String) entry.getValue(), ",");
            while (tokenizer.hasMoreTokens()) {
                String roleName = tokenizer.nextToken().trim();
                if (roleName.length() > 0) {
                    if (roleStore.getRoleByName(roleName) == null)
                        roleStore.addRole(roleStore.createRoleObject(roleName));
                }
            }
        }
    }

    // check for  roles in data.properties but not in user.properties
    File dataFile = new File(getSecurityRoot(), "layers.properties");
    if (dataFile.exists()) {
        Properties props = Util.loadPropertyFile(dataFile);
        for (Entry<Object, Object> entry : props.entrySet()) {
            if ("mode".equals(entry.getKey().toString()))
                continue; // skip mode directive
            StringTokenizer tokenizer = new StringTokenizer((String) entry.getValue(), ",");
            while (tokenizer.hasMoreTokens()) {
                String roleName = tokenizer.nextToken().trim();
                if (roleName.length() > 0 && roleName.equals("*") == false) {
                    if (roleStore.getRoleByName(roleName) == null)
                        roleStore.addRole(roleStore.createRoleObject(roleName));
                }
            }
        }
    }

    //persist the changes
    roleStore.store();
    userGroupStore.store();

    // first part of migration finished, rename old file
    if (usersFile.exists()) {
        File oldUserFile = new File(usersFile.getCanonicalPath() + ".old");
        usersFile.renameTo(oldUserFile);
        LOGGER.info("Renamed " + usersFile.getCanonicalPath() + " to " + oldUserFile.getCanonicalPath());
    }

    LOGGER.info("End security migration");
    return true;
}

From source file:org.geoserver.security.impl.AbstractSecurityServiceTest.java

public static File unpackTestDataDir() throws Exception {
    URL url = AbstractSecurityServiceTest.class.getResource("/datadir");
    if (!"file".equals(url.getProtocol())) {
        //means a dependency is using this directory via a jarfile, copy out manually
        File dataDir = File.createTempFile("data", "live", new File("./target"));
        dataDir.delete();/*ww  w.  ja  v a  2s.co  m*/
        dataDir.mkdirs();

        //TODO: instead of harcoding files, dynamically read all subentries from the jar
        // and copy them out
        FileUtils.copyURLToFile(AbstractSecurityServiceTest.class.getResource("/datadir/dummy.txt"),
                new File(dataDir, "dummy.txt"));
        return dataDir;
    }

    return DataUtilities.urlToFile(url);
}

From source file:org.geoserver.security.jdbc.AbstractJDBCService.java

/**
 * Check for the existence of the file, if the
 * file exists do nothing.//from   w w w.  ja v  a  2s. c om
 * 
 * If the file does not exist, check for a template
 * file contained in the jar with the same name, 
 * if found, use it.
 * 
 * If no template was found, use the default template
 * 
 * 
 * @param fileName, target location
 * @param namedRoot, parent dir if fileName is relative
 * @param defaultResource, the standard template
 * @throws IOException
 * @return the file to use
 */
protected File checkORCreateJDBCPropertyFile(String fileName, File namedRoot, String defaultResource)
        throws IOException {

    fileName = fileName != null ? fileName : defaultResource;
    File file = new File(fileName);
    if (file.isAbsolute() == false)
        file = new File(namedRoot, fileName);

    if (file.exists())
        return file; // we are happy

    // try to find a template with the same name
    URL url = this.getClass().getResource(fileName);
    if (url != null)
        FileUtils.copyURLToFile(url, file);
    else // use the default template
        FileUtils.copyURLToFile(getClass().getResource(defaultResource), file);

    return file;

}

From source file:org.geoserver.security.xml.XMLRoleService.java

@Override
public void initializeFromConfig(SecurityNamedServiceConfig config) throws IOException {

    super.initializeFromConfig(config);
    validatingXMLSchema = false;//from w  w w.j  a v a  2  s. c o m

    if (config instanceof XMLSecurityServiceConfig) {
        validatingXMLSchema = ((XMLSecurityServiceConfig) config).isValidating();

        // copy schema file 
        File xsdFile = new File(getConfigRoot(), XMLConstants.FILE_RR_SCHEMA);
        if (xsdFile.exists() == false) {
            FileUtils.copyURLToFile(getClass().getResource(XMLConstants.FILE_RR_SCHEMA), xsdFile);
        }
    }

    if (config instanceof FileBasedSecurityServiceConfig) {
        String fileName = ((FileBasedSecurityServiceConfig) config).getFileName();
        roleFile = new File(fileName);
        if (roleFile.isAbsolute() == false) {
            roleFile = new File(getConfigRoot(), fileName);
        }
        if (roleFile.exists() == false) {
            FileUtils.copyURLToFile(getClass().getResource("rolesTemplate.xml"), roleFile);
        }
    } else {
        throw new IOException("Cannot initialize from " + config.getClass().getName());
    }
    // load the data
    deserialize();
}

From source file:org.geoserver.security.xml.XMLRoleServiceTest.java

@Test
public void testLocking() throws Exception {
    File xmlFile = File.createTempFile("roles", ".xml");
    FileUtils.copyURLToFile(getClass().getResource("rolesTemplate.xml"), xmlFile);
    GeoServerRoleService service1 = createRoleService("locking1", xmlFile.getCanonicalPath());
    GeoServerRoleService service2 = createRoleService("locking2", xmlFile.getCanonicalPath());
    GeoServerRoleStore store1 = createStore(service1);
    GeoServerRoleStore store2 = createStore(service2);

    GeoServerRole role_test1 = store1.createRoleObject("ROLE_TEST");
    GeoServerRole role_test2 = store2.createRoleObject("ROLE_TEST");

    // obtain a lock
    store1.addRole(role_test1);//from   w  w w  .  j ava 2s . c  o m
    boolean fail;
    String failMessage = "Concurrent lock not allowed";
    fail = true;
    try {
        store2.clear();
    } catch (IOException ex) {
        fail = false;
    }
    if (fail)
        Assert.fail(failMessage);

    // release lock
    store1.load();
    // get lock
    store2.addRole(role_test1);

    fail = true;
    try {
        store1.clear();
    } catch (IOException ex) {
        fail = false;
    }
    if (fail)
        Assert.fail(failMessage);

    // release lock
    store2.store();
    store1.clear();
    store1.store();

    //// end of part one, now check all modifying methods

    // obtain a lock
    store1.addRole(role_test1);

    fail = true;
    try {
        store2.associateRoleToGroup(role_test2, "agroup");
    } catch (IOException ex) {
        try {
            store2.disAssociateRoleFromGroup(role_test2, "agroup");
        } catch (IOException e) {
            fail = false;
        }
    }
    if (fail)
        Assert.fail(failMessage);

    fail = true;
    try {
        store2.associateRoleToUser(role_test2, "auser");
    } catch (IOException ex) {
        try {
            store2.disAssociateRoleFromUser(role_test2, "auser");
        } catch (IOException e) {
            fail = false;
        }
    }
    if (fail)
        Assert.fail(failMessage);

    fail = true;
    try {
        store2.updateRole(role_test2);
    } catch (IOException ex) {
        try {
            store2.removeRole(role_test2);
        } catch (IOException ex1) {
            try {
                store2.addRole(role_test2);
            } catch (IOException ex2) {
                fail = false;
            }
        }
    }
    if (fail)
        Assert.fail(failMessage);

    fail = true;
    try {
        store2.clear();
    } catch (IOException ex) {
        try {
            store2.store();
        } catch (IOException e) {
            fail = false;
        }
    }
    if (fail)
        Assert.fail(failMessage);

    fail = true;
    try {
        store2.setParentRole(role_test1, null);
    } catch (IOException ex) {
        fail = false;
    }
    if (fail)
        Assert.fail(failMessage);

}

From source file:org.geoserver.security.xml.XMLRoleServiceTest.java

@Test
public void testDynamicReload() throws Exception {
    File xmlFile = File.createTempFile("roles", ".xml");
    FileUtils.copyURLToFile(getClass().getResource("rolesTemplate.xml"), xmlFile);
    GeoServerRoleService service1 = createRoleService("reload1", xmlFile.getCanonicalPath());
    GeoServerRoleService service2 = createRoleService("reload2", xmlFile.getCanonicalPath());

    GeoServerRoleStore store1 = createStore(service1);

    GeoServerRole role_test1 = store1.createRoleObject("ROLE_TEST1");

    checkEmpty(service1);/*from   ww  w  .java  2  s .co  m*/
    checkEmpty(service2);

    // prepare for syncing

    RoleLoadedListener listener = new RoleLoadedListener() {

        @Override
        public void rolesChanged(RoleLoadedEvent event) {
            synchronized (this) {
                this.notifyAll();
            }

        }
    };
    service2.registerRoleLoadedListener(listener);

    // modifiy store1
    store1.addRole(role_test1);
    store1.store();
    assertTrue(service1.getRoles().size() == 1);

    // increment lastmodified adding a second manually, the test is too fast
    xmlFile.setLastModified(xmlFile.lastModified() + 1000);

    // wait for the listener to unlock when 
    // service 2 triggers a load event
    synchronized (listener) {
        listener.wait();
    }

    // here comes the magic !!!
    assertTrue(service2.getRoles().size() == 1);

}