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

📄 dbdataimport.java

📁 java开发的一套非常好用的oa系统
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/**
 * $RCSfile: DbDataImport.java,v $
 * $Revision: 1.1.1.1 $
 * $Date: 2002/09/09 13:50:51 $
 *
 * New Jive  from Jdon.com.
 *
 * This software is the proprietary information of CoolServlets, Inc.
 * Use is subject to license terms.
 */

package com.jivesoftware.forum.database;

import java.io.*;
import java.text.*;
import java.util.*;
import java.util.jar.*;

//import com.jivesoftware.crimson.parser.*;

import org.xml.sax.*;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.*;
import org.apache.crimson.parser.XMLReaderImpl;

import com.jivesoftware.forum.*;

/**
 * Imports Jive data that is stored in the Jive XML format. The class can
 * handle plain XML files or compressed JAR files. All XML must strictly
 * comply with the Jive DTD.
 */
public class DbDataImport {

    public static final String XML_DATE_FORMAT = "yyyy/MM/dd HH:mm:ss.SS z";

    public static final String XML_VERSION = "1.1";

    // A SAX parser
    private XMLReader parser = null;

    // ForumFactory object -- all Jive objects come from this
    private ForumFactory forumFactory = null;

    // UserManager and GroupManager objects to create users & groups
    private UserManager userManager = null;
    private GroupManager groupManager = null;

    // The current forum being imported
    private Forum forum;
    // The current thread being imported
    private ForumThread thread;

    // Indicates if the current thread has a root message.
    private boolean threadHasRootMessage = false;

    // A simple date formatter that will convert Date objects to the Jive
    // date format. For example: 1978/01/17 21:17:33.83 CST
    private static SimpleDateFormat dateFormatter =
        new SimpleDateFormat(XML_DATE_FORMAT);

    // Load Jive permission types. We map each permission name to its int value.
    private static HashMap jivePermissions = new HashMap();
    static {
        jivePermissions.put("CREATE_MESSAGE",
            new Integer(ForumPermissions.CREATE_MESSAGE));
        jivePermissions.put("CREATE_THREAD",
            new Integer(ForumPermissions.CREATE_THREAD));
        jivePermissions.put("FORUM_ADMIN",
            new Integer(ForumPermissions.FORUM_ADMIN));
        jivePermissions.put("GROUP_ADMIN",
            new Integer(ForumPermissions.GROUP_ADMIN));
        jivePermissions.put("MODERATE_THREADS",
            new Integer(ForumPermissions.MODERATE_THREADS));
        jivePermissions.put("READ",
            new Integer(ForumPermissions.READ));
        jivePermissions.put("SYSTEM_ADMIN",
            new Integer(ForumPermissions.SYSTEM_ADMIN));
        jivePermissions.put("USER_ADMIN",
            new Integer(ForumPermissions.USER_ADMIN));
        jivePermissions.put("MODERATE_MESSAGES",
            new Integer(ForumPermissions.MODERATE_MESSAGES));
    }

    // Parsing mode definitions
    private int mode = 0;
    private final static int USERNAME      = 1;
    private final static int PASSWORD      = 2;
    private final static int EMAIL         = 3;
    private final static int NAME          = 4;
    private final static int DESCRIPTION   = 5;
    private final static int CREATION_DATE = 6;
    private final static int MODIFIED_DATE = 7;
    private final static int SUBJECT       = 8;
    private final static int BODY          = 9;

    /**
     * Parses a date string and returns a Date object. If the the date cannot
     * be parsed, a new Date is returned.
     */
    private static Date parseDate(String dateText) {
        try {
            return dateFormatter.parse(dateText);
        }
        catch (ParseException pe) {
            return new Date();
        }
    }


    /**
     * Initializes Jive data importer.
     *
     * @param dbForumFactory
     */
    public DbDataImport(DbForumFactory dbForumFactory) throws UnauthorizedException,
            Exception
    {
        this.forumFactory = dbForumFactory;
        // Get user and group managers
        this.userManager = forumFactory.getUserManager();
        this.groupManager = forumFactory.getGroupManager();
        parser = new XMLReaderImpl();
    }

    /**
     * Imports Jive data.
     *
     * @param in An InputStream object
     */
    public void doImport(Reader in) throws IOException, Exception {
        try {
            parser.setContentHandler(new JiveHandler());
            parser.parse(new InputSource(in));
        }
        catch (SAXException saxe) {
            if (saxe instanceof SAXParseException) {
                SAXParseException saxpe = (SAXParseException)saxe;
                int line = saxpe.getLineNumber();
                int col = saxpe.getColumnNumber();
                String publicID = saxpe.getPublicId();
                String message = "XML parsing exception (" + publicID +
                    ") line " + line + ":" + col;
                throw new Exception(message);
            }
        }
    }

    //
    private static void print(String msg) {
        // TODO: make message stream settable
        System.err.println(msg);
    }

    /**
     * main method (for testing purposes only)
     */
    public static void main(String args[]) {

        // Get parameters
        if (args.length < 3) {
            print("USAGE: java DbDataImport <xml_data_file> <jive_username> "
                + "<jive_password>");
            return;
        }
        String xmlDataFile = args[0];
        String username = args[1];
        String password = args[2];

        // TODO: check all params

        // Login to Jive, create a jive ForumFactory
        Authorization authToken = null;
        ForumFactory factory = null;
        try {
            authToken = AuthorizationFactory.getAuthorization(args[1], args[2]);
            print("Logged into Jive as '" + username + "'");
            // Get the underlying forum factory implementation
            factory = ForumFactory.getInstance(authToken);
        }
        catch (UnauthorizedException ue) {
            print("ERROR: Jive authorization failed. Please "
                + "verify that your username and password are correct and "
                + "that a jive.properties file exists in your classpath.");
            ue.printStackTrace();
            return;
        }

        // Start an import, keep track of the time.
        long time = 0;
        try {
            DbForumFactory dbForumFactory = (DbForumFactory)(((ForumFactoryProxy)factory).getProxiedForumFactory());
            DbDataImport importer = new DbDataImport(dbForumFactory);
            Reader in = new FileReader(new File(args[0]));
            time = System.currentTimeMillis();
            importer.doImport(in);
            time = System.currentTimeMillis() - time;
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        print("Finished import.");
        print("--------------------------------");
        print("Total time: " + ((double)time/1000.0) + " seconds");
        return;
    }

    /**
     * Setup global SAX handlers ala the Flyweight design pattern. Each of
     * these objects will be re-used again and again to parse the subsets of
     * the XML document that they know how to handle. The only handlers that are
     * a bit tricky are MessageHandler and MessageListHandler because they can
     * be nested in the XML document. Therefore, those classes use an internal
     * stacks to remember where to pass back the flow of control after ending.
     */
    private ForumHandler forumHandler = new ForumHandler();
    private ForumListHandler forumListHandler = new ForumListHandler();
    private GroupHandler groupHandler = new GroupHandler();
    private GroupListHandler groupListHandler = new GroupListHandler();
    private GroupPermissionListHandler groupPermissionListHandler
        = new GroupPermissionListHandler();
    private MessageHandler messageHandler = new MessageHandler();
    private MessageListHandler messageListHandler = new MessageListHandler();
    private PermissionListHandler permissionListHandler
        = new PermissionListHandler();
    private PropertyListHandler propertyListHandler = new PropertyListHandler();
    private ThreadHandler threadHandler = new ThreadHandler();
    private ThreadListHandler threadListHandler = new ThreadListHandler();
    private UserHandler userHandler = new UserHandler();
    private UserListHandler userListHandler = new UserListHandler();
    private UserPermissionListHandler userPermissionListHandler
        = new UserPermissionListHandler();

    /**
     *
     */
    private final class JiveHandler extends DefaultHandler {

        public void startElement(String uri, String localName, String tag,
                Attributes attribs)
                throws SAXParseException
        {
            if (localName.equals("Jive")) {
                // Check attributes here such as the Jive XML version, etc.
            }
            else if (localName.equals("UserList")) {
                userListHandler.setParentHandler(this);
                parser.setContentHandler(userListHandler);
            }
            else if (localName.equals("GroupList")) {
                groupListHandler.setParentHandler(this);
                parser.setContentHandler(groupListHandler);
            }
            else if (localName.equals("ForumList")) {
                forumListHandler.setParentHandler(this);
                parser.setContentHandler(forumListHandler);
            }
            else if (localName.equals("UserPermissionList")) {
                userPermissionListHandler.setParentHandler(this);
                parser.setContentHandler(userPermissionListHandler);
            }
            else if (localName.equals("GroupPermissionList")) {
            }
        }
    }

    /**
     * Class to handle parsing of
     */
    private class UserListHandler extends DefaultHandler {

        private ContentHandler parentHandler;

        /**
         * Sets the parentHandler of the handler. Control will be passed back
         * to the parent when this handler is done parsing the XML it knows
         * how to handle.
         */
        public void setParentHandler(DefaultHandler parentHandler) {
            this.parentHandler = parentHandler;
        }

        public void startElement(String uri, String localName, String tag,
                Attributes attribs)
                throws SAXParseException
        {
            if (localName.equals("User")) {
                userHandler.setParentHandler(this);
                parser.setContentHandler(userHandler);
            }
        }
        public void endElement(String uri, String localName, String tag)
                throws SAXParseException
        {
            if (localName.equals("UserList")) {
                // Let parent resume handling SAX events
                parser.setContentHandler(parentHandler);
            }
        }
    }

    /**
     *
     */
    private class UserHandler extends DefaultHandler implements PropertyStore {

        private User newUser;

        private boolean isUsernameSet = false;
        private boolean isPasswordSet = false;
        private boolean isEmailSet = false;

        private StringBuffer username = new StringBuffer();
        private StringBuffer password = new StringBuffer();
        private StringBuffer email = new StringBuffer();
        private StringBuffer name = new StringBuffer();
        private StringBuffer creationDate = new StringBuffer();
        private StringBuffer modifiedDate = new StringBuffer();
        private boolean nameVisible = false;
        private boolean emailVisible = false;
        private Map properties = null;

        private boolean doCreateUser = false;
        private boolean userCreated = false;

        private ContentHandler parentHandler;

        /**
         * Sets the parentHandler of the handler. Control will be passed back
         * to the parent when this handler is done parsing the XML it knows
         * how to handle.
         */
        public void setParentHandler(DefaultHandler parentHandler) {
            this.parentHandler = parentHandler;

            //reset data
            newUser = null;
            isUsernameSet = false;
            isPasswordSet = false;
            isEmailSet = false;
            username.setLength(0);
            password.setLength(0);
            email.setLength(0);
            name.setLength(0);
            creationDate.setLength(0);
            modifiedDate.setLength(0);
            nameVisible = false;
            emailVisible = false;
            properties = new HashMap();

⌨️ 快捷键说明

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