⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmluserdatabase.java

📁 jspwiki source code,jspwiki source code
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*     JSPWiki - a JSP-based WikiWiki clone.    Licensed to the Apache Software Foundation (ASF) under one    or more contributor license agreements.  See the NOTICE file    distributed with this work for additional information    regarding copyright ownership.  The ASF licenses this file    to you under the Apache License, Version 2.0 (the    "License"); you may not use this file except in compliance    with the License.  You may obtain a copy of the License at       http://www.apache.org/licenses/LICENSE-2.0    Unless required by applicable law or agreed to in writing,    software distributed under the License is distributed on an    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY    KIND, either express or implied.  See the License for the    specific language governing permissions and limitations    under the License.   */package com.ecyrd.jspwiki.auth.user;import java.io.*;import java.security.Principal;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.*;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.*;import org.xml.sax.SAXException;import com.ecyrd.jspwiki.NoRequiredPropertyException;import com.ecyrd.jspwiki.WikiEngine;import com.ecyrd.jspwiki.auth.NoSuchPrincipalException;import com.ecyrd.jspwiki.auth.WikiPrincipal;import com.ecyrd.jspwiki.auth.WikiSecurityException;import com.ecyrd.jspwiki.util.Serializer;/** * <p>Manages {@link DefaultUserProfile} objects using XML files for persistence. * Passwords are hashed using SHA1. User entries are simple <code>&lt;user&gt;</code> * elements under the root. User profile properties are attributes of the * element. For example:</p> * <blockquote><code> * &lt;users&gt;<br/> * &nbsp;&nbsp;&lt;user loginName="janne" fullName="Janne Jalkanen"<br/>  * &nbsp;&nbsp;&nbsp;&nbsp;wikiName="JanneJalkanen" email="janne@ecyrd.com"<br/> * &nbsp;&nbsp;&nbsp;&nbsp;password="{SHA}457b08e825da547c3b77fbc1ff906a1d00a7daee"/&gt;<br/> * &lt;/users&gt; * </code></blockquote>  * <p>In this example, the un-hashed password is <code>myP@5sw0rd</code>. Passwords are hashed without salt.</p> * @author Andrew Jaquith * @since 2.3 */// FIXME: If the DB is shared across multiple systems, it's possible to lose accounts//        if two people add new accounts right after each other from different wikis.public class XMLUserDatabase extends AbstractUserDatabase{    /**     * The jspwiki.properties property specifying the file system location of     * the user database.     */    public static final String  PROP_USERDATABASE = "jspwiki.xmlUserDatabaseFile";        private static final String DEFAULT_USERDATABASE = "userdatabase.xml";    private static final String ATTRIBUTES_TAG = "attributes";        private static final String CREATED           = "created";        private static final String EMAIL             = "email";    private static final String FULL_NAME         = "fullName";    private static final String LOGIN_NAME        = "loginName";    private static final String LAST_MODIFIED     = "lastModified";        private static final String LOCK_EXPIRY    = "lockExpiry";    private static final String PASSWORD          = "password";    private static final String UID = "uid";    private static final String USER_TAG          = "user";    private static final String WIKI_NAME         = "wikiName";    private Document            c_dom             = null;    private DateFormat          c_defaultFormat   = DateFormat.getDateTimeInstance();    private DateFormat          c_format          = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss:SSS z");        private File                c_file            = null;    /**     * Looks up and deletes the first {@link UserProfile} in the user database     * that matches a profile having a given login name. If the user database     * does not contain a user with a matching attribute, throws a     * {@link NoSuchPrincipalException}.     * @param loginName the login name of the user profile that shall be deleted     */    public synchronized void deleteByLoginName( String loginName ) throws NoSuchPrincipalException, WikiSecurityException    {        if ( c_dom == null )        {            throw new WikiSecurityException( "FATAL: database does not exist" );        }                    NodeList users = c_dom.getDocumentElement().getElementsByTagName( USER_TAG );        for( int i = 0; i < users.getLength(); i++ )        {            Element user = (Element) users.item( i );            if ( user.getAttribute( LOGIN_NAME ).equals( loginName ) )            {                c_dom.getDocumentElement().removeChild(user);                                // Commit to disk                saveDOM();                return;            }        }        throw new NoSuchPrincipalException( "Not in database: " + loginName );    }            /**     * Looks up and returns the first {@link UserProfile}in the user database     * that matches a profile having a given e-mail address. If the user     * database does not contain a user with a matching attribute, throws a     * {@link NoSuchPrincipalException}.     * @param index the e-mail address of the desired user profile     * @return the user profile     * @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByEmail(String)     */    public UserProfile findByEmail( String index ) throws NoSuchPrincipalException    {        UserProfile profile = findByAttribute( EMAIL, index );        if ( profile != null )        {            return profile;        }        throw new NoSuchPrincipalException( "Not in database: " + index );    }    /**     * Looks up and returns the first {@link UserProfile}in the user database     * that matches a profile having a given full name. If the user database     * does not contain a user with a matching attribute, throws a     * {@link NoSuchPrincipalException}.     * @param index the fill name of the desired user profile     * @return the user profile     * @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByFullName(java.lang.String)     */    public UserProfile findByFullName( String index ) throws NoSuchPrincipalException    {        UserProfile profile = findByAttribute( FULL_NAME, index );        if ( profile != null )        {            return profile;        }        throw new NoSuchPrincipalException( "Not in database: " + index );    }    /**     * Looks up and returns the first {@link UserProfile}in the user database     * that matches a profile having a given login name. If the user database     * does not contain a user with a matching attribute, throws a     * {@link NoSuchPrincipalException}.     * @param index the login name of the desired user profile     * @return the user profile     * @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByLoginName(java.lang.String)     */    public UserProfile findByLoginName( String index ) throws NoSuchPrincipalException    {        UserProfile profile = findByAttribute( LOGIN_NAME, index );        if ( profile != null )        {            return profile;        }        throw new NoSuchPrincipalException( "Not in database: " + index );    }    /**     * {@inheritDoc}     */    public UserProfile findByUid( String uid ) throws NoSuchPrincipalException    {        UserProfile profile = findByAttribute( UID, uid );        if ( profile != null )        {            return profile;        }        throw new NoSuchPrincipalException( "Not in database: " + uid );    }    /**     * Looks up and returns the first {@link UserProfile}in the user database     * that matches a profile having a given wiki name. If the user database     * does not contain a user with a matching attribute, throws a     * {@link NoSuchPrincipalException}.     * @param index the wiki name of the desired user profile     * @return the user profile     * @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByWikiName(java.lang.String)     */    public UserProfile findByWikiName( String index ) throws NoSuchPrincipalException    {        UserProfile profile = findByAttribute( WIKI_NAME, index );        if ( profile != null )        {            return profile;        }        throw new NoSuchPrincipalException( "Not in database: " + index );    }    /**     * Returns all WikiNames that are stored in the UserDatabase     * as an array of WikiPrincipal objects. If the database does not     * contain any profiles, this method will return a zero-length     * array.     * @return the WikiNames     * @throws WikiSecurityException In case things fail.     */    public Principal[] getWikiNames() throws WikiSecurityException    {        if ( c_dom == null )        {            throw new IllegalStateException( "FATAL: database does not exist" );        }        SortedSet<Principal> principals = new TreeSet<Principal>();        NodeList users = c_dom.getElementsByTagName( USER_TAG );        for( int i = 0; i < users.getLength(); i++ )        {            Element user = (Element) users.item( i );            String wikiName = user.getAttribute( WIKI_NAME );            if ( wikiName == null )            {                log.warn( "Detected null wiki name in XMLUserDataBase. Check your user database." );            }            else            {                Principal principal = new WikiPrincipal( wikiName, WikiPrincipal.WIKI_NAME );                principals.add( principal );            }        }        return principals.toArray( new Principal[principals.size()] );    }        /**     * Initializes the user database based on values from a Properties object.     * The properties object must contain a file path to the XML database file     * whose key is {@link #PROP_USERDATABASE}.     * @see com.ecyrd.jspwiki.auth.user.UserDatabase#initialize(com.ecyrd.jspwiki.WikiEngine,     *      java.util.Properties)     * @throws NoRequiredPropertyException if the user database cannot be located, parsed, or opened     */    public void initialize( WikiEngine engine, Properties props ) throws NoRequiredPropertyException    {        File defaultFile = null;        if( engine.getRootPath() == null )        {            log.warn( "Cannot identify JSPWiki root path"  );            defaultFile = new File( "WEB-INF/" + DEFAULT_USERDATABASE ).getAbsoluteFile();        }        else        {            defaultFile = new File( engine.getRootPath() + "/WEB-INF/" + DEFAULT_USERDATABASE );        }        // Get database file location        String file = props.getProperty( PROP_USERDATABASE );        if( file == null )        {            log.warn( "XML user database property " + PROP_USERDATABASE + " not found; trying " + defaultFile  );            c_file = defaultFile;        }        else         {            c_file = new File( file );        }        log.info("XML user database at "+c_file.getAbsolutePath());                buildDOM();        sanitizeDOM();    }        private void buildDOM()    {        // Read DOM        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        factory.setValidating( false );        factory.setExpandEntityReferences( false );        factory.setIgnoringComments( true );        factory.setNamespaceAware( false );        try        {            c_dom = factory.newDocumentBuilder().parse( c_file );            log.debug( "Database successfully initialized" );            c_lastModified = c_file.lastModified();            c_lastCheck    = System.currentTimeMillis();        }        catch( ParserConfigurationException e )        {            log.error( "Configuration error: " + e.getMessage() );        }        catch( SAXException e )        {            log.error( "SAX error: " + e.getMessage() );        }        catch( FileNotFoundException e )        {            log.info("User database not found; creating from scratch...");        }        catch( IOException e )        {            log.error( "IO error: " + e.getMessage() );        }        if ( c_dom == null )        {            try            {                //                //  Create the DOM from scratch                //                c_dom = factory.newDocumentBuilder().newDocument();                c_dom.appendChild( c_dom.createElement( "users") );            }            catch( ParserConfigurationException e )            {                log.fatal( "Could not create in-memory DOM" );            }        }    }        private void saveDOM() throws WikiSecurityException    {        if ( c_dom == null )        {            log.fatal( "User database doesn't exist in memory." );        }        File newFile = new File( c_file.getAbsolutePath() + ".new" );        try        {            BufferedWriter io = new BufferedWriter( new OutputStreamWriter (                     new FileOutputStream( newFile ), "UTF-8" ) );                        // Write the file header and document root            io.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");            io.write("<users>\n");                        // Write each profile as a <user> node            Element root = c_dom.getDocumentElement();            NodeList nodes = root.getElementsByTagName( USER_TAG );              for( int i = 0; i < nodes.getLength(); i++ )            {                Element user = (Element)nodes.item( i );                io.write( "    <" + USER_TAG + " ");                io.write( UID );                io.write( "=\"" + user.getAttribute( UID ) + "\" " );                io.write( LOGIN_NAME );                io.write( "=\"" + user.getAttribute( LOGIN_NAME ) + "\" " );                io.write( WIKI_NAME );                io.write( "=\"" + user.getAttribute( WIKI_NAME ) + "\" " );                io.write( FULL_NAME );                io.write( "=\"" + user.getAttribute( FULL_NAME ) + "\" " );                io.write( EMAIL );                io.write( "=\"" + user.getAttribute( EMAIL ) + "\" " );                io.write( PASSWORD );                io.write( "=\"" + user.getAttribute( PASSWORD ) + "\" " );                io.write( CREATED );                io.write( "=\"" + user.getAttribute( CREATED ) + "\" " );                io.write( LAST_MODIFIED );                io.write( "=\"" + user.getAttribute( LAST_MODIFIED ) + "\" " );                io.write( LOCK_EXPIRY );                io.write( "=\"" + user.getAttribute( LOCK_EXPIRY ) + "\" " );                io.write( ">" );                NodeList attributes = user.getElementsByTagName( ATTRIBUTES_TAG );                for ( int j = 0; j < attributes.getLength(); j++ )                {                    Element attribute = (Element)attributes.item( j );                    String value = extractText( attribute );                    io.write( "\n        <" + ATTRIBUTES_TAG + ">" );                    io.write( value );                    io.write( "</" + ATTRIBUTES_TAG + ">" );                }                io.write("\n    </" +USER_TAG + ">\n");            }            io.write("</users>");            io.close();        }        catch ( IOException e )

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -