Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.security;
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
PropertyUserStore This class monitors a property file of the format mentioned below and notifies registered listeners of the changes to the the given file.
  username: password [,rolename ...]
 
Passwords may be clear text, obfuscated or checksummed. The class com.eclipse.Util.Password should be used to generate obfuscated passwords or password checksums. If DIGEST Authentication is used, the password must be in a recoverable format, either plain text or OBF:.
 
 public class PropertyUserStore extends AbstractLifeCycle
 {
     private static final Logger LOG = Log.getLogger(PropertyUserStore.class);
 
     private String _config;
     private Resource _configResource;
     private Scanner _scanner;
     private int _refreshInterval = 0;// default is not to reload
 
     private boolean _firstLoad = true// true if first load, false from that point on
     private final List<String_knownUsers = new ArrayList<String>();
     private final Map<StringUserIdentity_knownUserIdentities = new HashMap<StringUserIdentity>();
     private List<UserListener_listeners;
 
     /* ------------------------------------------------------------ */
     public String getConfig()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     public void setConfig(String config)
     {
          = config;
     }
     
     /* ------------------------------------------------------------ */
         public UserIdentity getUserIdentity(String userName)
         {
             return .get(userName);
         }
 
     /* ------------------------------------------------------------ */
    
returns the resource associated with the configured properties file, creating it if necessary
 
     public Resource getConfigResource() throws IOException
     {
        if ( == null)
        {
             = Resource.newResource();
        }
        return ;
    }
    /* ------------------------------------------------------------ */
    
sets the refresh interval (in seconds)
    public void setRefreshInterval(int msec)
    {
         = msec;
    }
    /* ------------------------------------------------------------ */
    
refresh interval in seconds for how often the properties file should be checked for changes
    public int getRefreshInterval()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    private void loadUsers() throws IOException
    {
        if ( == null)
            return;
        if (.isDebugEnabled())
            .debug("Load " + this + " from " + );
        Properties properties = new Properties();
        if (getConfigResource().exists())
            properties.load(getConfigResource().getInputStream());
        Set<Stringknown = new HashSet<String>();
        for (Map.Entry<ObjectObjectentry : properties.entrySet())
        {
            String username = ((String)entry.getKey()).trim();
            String credentials = ((String)entry.getValue()).trim();
            String roles = null;
            int c = credentials.indexOf(',');
            if (c > 0)
            {
                roles = credentials.substring(c + 1).trim();
                credentials = credentials.substring(0,c).trim();
            }
            if (username != null && username.length() > 0 && credentials != null && credentials.length() > 0)
            {
                String[] roleArray = .;
                if (roles != null && roles.length() > 0)
                {
                    roleArray = roles.split(",");
                }
                known.add(username);
                Credential credential = Credential.getCredential(credentials);
                
                Principal userPrincipal = new KnownUser(username,credential);
                Subject subject = new Subject();
                subject.getPrincipals().add(userPrincipal);
                subject.getPrivateCredentials().add(credential);
                if (roles != null)
                {
                    for (String role : roleArray)
                    {
                        subject.getPrincipals().add(new RolePrincipal(role));
                    }
                }
                
                subject.setReadOnly();
                
                .put(username,.newUserIdentity(subject,userPrincipal,roleArray));
                notifyUpdate(username,credential,roleArray);
            }
        }
        synchronized ()
        {
            /*
             * if its not the initial load then we want to process removed users
             */
            if (!)
            {
                Iterator<Stringusers = .iterator();
                while (users.hasNext())
                {
                    String user = users.next();
                    if (!known.contains(user))
                    {
                        .remove(user);
                        notifyRemove(user);
                    }
                }
            }
            /*
             * reset the tracked _users list to the known users we just processed
             */
            .clear();
            .addAll(known);
        }
        /*
         * set initial load to false as there should be no more initial loads
         */
         = false;
    }
    /* ------------------------------------------------------------ */
    
Depending on the value of the refresh interval, this method will either start up a scanner thread that will monitor the properties file for changes after it has initially loaded it. Otherwise the users will be loaded and there will be no active monitoring thread so changes will not be detected.

    protected void doStart() throws Exception
    {
        super.doStart();
        if (getRefreshInterval() > 0)
        {
             = new Scanner();
            .setScanInterval(getRefreshInterval());
            List<FiledirList = new ArrayList<File>(1);
            dirList.add(getConfigResource().getFile().getParentFile());
            .setScanDirs(dirList);
            .setFilenameFilter(new FilenameFilter()
            {
                public boolean accept(File dirString name)
                {
                    File f = new File(dir,name);
                    try
                    {
                        if (f.compareTo(getConfigResource().getFile()) == 0)
                        {
                            return true;
                        }
                    }
                    catch (IOException e)
                    {
                        return false;
                    }
                    return false;
                }
            });
            .addListener(new BulkListener()
            {
                public void filesChanged(List<Stringfilenamesthrows Exception
                {
                    if (filenames == null)
                        return;
                    if (filenames.isEmpty())
                        return;
                    if (filenames.size() == 1)
                    {
                        Resource r = Resource.newResource(filenames.get(0));
                        if (r.getFile().equals(.getFile()))
                            loadUsers();
                    }
                }
                public String toString()
                {
                    return "PropertyUserStore$Scanner";
                }
            });
            .setReportExistingFilesOnStartup(true);
            .setRecursive(false);
            .start();
        }
        else
        {
            loadUsers();
        }
    }
    /* ------------------------------------------------------------ */
    
    protected void doStop() throws Exception
    {
        super.doStop();
        if ( != null)
            .stop();
         = null;
    }

    
Notifies the registered listeners of potential updates to a user

Parameters:
username
credential
roleArray
    private void notifyUpdate(String usernameCredential credentialString[] roleArray)
    {
        if ( != null)
        {
            for (Iterator<UserListeneri = .iterator(); i.hasNext();)
            {
                i.next().update(username,credential,roleArray);
            }
        }
    }

    
notifies the registered listeners that a user has been removed.

Parameters:
username
    private void notifyRemove(String username)
    {
        if ( != null)
        {
            for (Iterator<UserListeneri = .iterator(); i.hasNext();)
            {
                i.next().remove(username);
            }
        }
    }

    
registers a listener to be notified of the contents of the property file
    public void registerUserListener(UserListener listener)
    {
        if ( == null)
        {
             = new ArrayList<UserListener>();
        }
        .add(listener);
    }

    
UserListener
    public interface UserListener
    {
        public void update(String usernameCredential credentialString[] roleArray);
        public void remove(String username);
    }
New to GrepCode? Check out our FAQ X