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

📄 chatsearchmanager.java

📁 openfire 服务器源码下载
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
                String startTime = result.getString(3);
                String chatNotes = new ChatNotes().getNotes(sessionID);
                ChatInformation chatInfo = new ChatInformation(sessionID, transcript, startTime, chatNotes);

                if (chatInfo.getTranscript() != null) {
                    addAgentHistoryToChatInformation(chatInfo);

                    // Add the ChatInformation to the index
                    addTranscriptToIndex(chatInfo, writer);
                    lastDate = chatInfo.getCreationDate();
                }
            }
        }
        catch (Exception ex) {
            ComponentManagerFactory.getComponentManager().getLog().error(ex);
            // Reset the lastDate if an error happened
            lastDate = null;
        }
        finally {
            try {
                if (result != null) {
                    result.close();
                }
            }
            catch (SQLException e) {
                ComponentManagerFactory.getComponentManager().getLog().error(e);
            }

            DbConnectionManager.closeConnection(pstmt, con);
        }
        writer.optimize();
        writer.close();
        if (lastDate != null) {
            closeSearcherReader();
            // Reset the filters cache
            cachedFilters.clear();
            // Update the last updated and optimized dates
            lastOptimization = new Date();
            lastUpdated = lastDate;
            lastExecution = new Date();
            pendingTranscripts.set(0);
            // Save the last updated and optimized dates to the database
            saveDates();
        }
    }

    private void addAgentHistoryToChatInformation(ChatInformation chatInfo) {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet result = null;
        try {
            // Add the agents involved in the chat to the ChatInformation
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(AGENTS_IN_SESSION);
            pstmt.setString(1, chatInfo.getSessionID());
            result = pstmt.executeQuery();
            while (result.next()) {
                chatInfo.getAgentJIDs().add(result.getString(1));
            }
        }
        catch (SQLException e) {
            ComponentManagerFactory.getComponentManager().getLog().error(e);
        }
        finally {
            if (result != null) {
                try {
                    result.close();
                }
                catch (SQLException e) {
                    ComponentManagerFactory.getComponentManager().getLog().error(e);
                }
            }

            DbConnectionManager.closeConnection(pstmt, con);
        }

    }

    /**
     * Update the dates of this indexer in the database
     */
    private void saveDates() {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(UPDATE_DATES);
            pstmt.setString(1, StringUtils.dateToMillis(lastUpdated));
            pstmt.setString(2, StringUtils.dateToMillis(lastOptimization));
            pstmt.setLong(3, workgroup.getID());
            boolean updated = pstmt.executeUpdate() > 0;

            // If the row was not updated (because it doesn't exist) then insert a new row
            if (!updated) {
                pstmt.close();
                pstmt = con.prepareStatement(INSERT_DATES);
                pstmt.setLong(1, workgroup.getID());
                pstmt.setString(2, StringUtils.dateToMillis(lastUpdated));
                pstmt.setString(3, StringUtils.dateToMillis(lastOptimization));
                pstmt.executeUpdate();
            }
        }
        catch (Exception ex) {
            ComponentManagerFactory.getComponentManager().getLog().error(ex);
        }
        finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            }
            catch (Exception e) {
                ComponentManagerFactory.getComponentManager().getLog().error(e);
            }
            try {
                if (con != null) {
                    con.close();
                }
            }
            catch (Exception e) {
                ComponentManagerFactory.getComponentManager().getLog().error(e);
            }
        }
    }

    /**
     * Update the dates of this indexer in the database
     */
    private void deleteDates() {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_DATES);
            pstmt.setLong(1, workgroup.getID());
            pstmt.executeUpdate();
        }
        catch (Exception ex) {
            ComponentManagerFactory.getComponentManager().getLog().error(ex);
        }
        finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            }
            catch (Exception e) {
                ComponentManagerFactory.getComponentManager().getLog().error(e);
            }
            try {
                if (con != null) {
                    con.close();
                }
            }
            catch (Exception e) {
                ComponentManagerFactory.getComponentManager().getLog().error(e);
            }
        }
    }

    private void addTranscriptToIndex(ChatInformation chat, IndexWriter writer) throws IOException {
        // Flag that indicates if the transcript includes one or more messages. If no message was
        // found then nothing will be added to the index
        boolean hasMessages = false;
        Document document = new Document();

        for (Iterator elements = chat.getTranscript().elementIterator(); elements.hasNext();) {
            Element element = (Element)elements.next();
            // Only add Messages to the index (Presences are discarded)
            if ("message".equals(element.getName())) {
                // TODO Index XHTML bodies?
                String body = element.elementTextTrim("body");
                String from = element.attributeValue("from");
                String to = element.attributeValue("to");

                String fromNickname = new JID(from).getResource();
                String toNickname = new JID(to).getResource();

                final StringBuilder builder = new StringBuilder();
                builder.append(body);
                builder.append(" ");
                builder.append(fromNickname);
                builder.append(" ");
                builder.append(toNickname);

                if (body != null) {
                    if (chat.getNotes() != null) {
                        builder.append(" ");
                        builder.append(chat.getNotes());
                    }

                    if (chat.getAgentJIDs() != null) {
                        for (String jid : chat.getAgentJIDs()) {
                            builder.append(" ");
                            builder.append(jid);
                        }
                    }
                    document.add(new Field("body", builder.toString(), Field.Store.NO,
                            Field.Index.TOKENIZED));
                    // Indicate that a message was found
                    hasMessages = true;
                }
            }
        }
        if (hasMessages) {
            // Add the sessionID that indentifies the chat session to the document
            document.add (new Field("sessionID", String.valueOf(chat.getSessionID()),
                    Field.Store.YES, Field.Index.UN_TOKENIZED));
            // Add the JID of the agents involved in the chat to the document
            for (String agentJID : chat.getAgentJIDs()) {
                document.add(new Field("agentJID", agentJID,
                        Field.Store.YES, Field.Index.UN_TOKENIZED));
            }
            // Add the date when the chat started to the document
            long date = chat.getCreationDate().getTime();
            document.add(new Field("creationDate",  DateTools.timeToString(date, 
                    DateTools.Resolution.DAY), Field.Store.YES, Field.Index.UN_TOKENIZED));

            writer.addDocument(document);
        }
    }

    /**
     * Returns a Lucene IndexWriter. The create param indicates whether an
     * existing index should be used if it's found there.
     */
    private IndexWriter getWriter(boolean create) throws IOException {
        IndexWriter writer = new IndexWriter(searchDirectory, indexerAnalyzer, create);
        return writer;
    }

    // ###############################################################################
    // WorkgroupEventListener implemented methods
    // ###############################################################################
    public void workgroupCreated(Workgroup workgroup) {
        //Do nothing
    }

    public void workgroupDeleting(Workgroup workgroup) {
        //Do nothing
    }

    public void workgroupDeleted(Workgroup workgroup) {
        // Do nothing if the notification is related to other workgroup
        if (this.workgroup != workgroup) {
            return;
        }
        delete();
    }

    public void workgroupOpened(Workgroup workgroup) {
        //Do nothing
    }

    public void workgroupClosed(Workgroup workgroup) {
        //Do nothing
    }

    public void agentJoined(Workgroup workgroup, AgentSession agentSession) {
        //Do nothing
    }

    public void agentDeparted(Workgroup workgroup, AgentSession agentSession) {
        //Do nothing
    }

    public void chatSupportStarted(Workgroup workgroup, String sessionID) {
        //Do nothing
    }

    public void chatSupportFinished(Workgroup workgroup, String sessionID) {
        // Do nothing if the notification is related to other workgroup
        if (this.workgroup != workgroup) {
            return;
        }
        // Update the number of generated transcripts since the last update process was executed
        // If the maximum number of pending transcripts has been reached then force an update of
        // the index
        if (getMaxPendingTranscripts() > 0 &&
                pendingTranscripts.incrementAndGet() == getMaxPendingTranscripts())
        {
            // Update in another thread
            TaskEngine.getInstance().submit(new Runnable() {
                public void run() {
                    try {
                        updateIndex(true);
                    }
                    catch (IOException e) {
                        ComponentManagerFactory.getComponentManager().getLog().error(e);
                    }
                }
            });
        }
    }

    public void agentJoinedChatSupport(Workgroup workgroup, String sessionID,
                                       AgentSession agentSession) {
        //Do nothing
    }

    public void agentLeftChatSupport(Workgroup workgroup, String sessionID,
                                     AgentSession agentSession) {
        //Do nothing
    }

    /**
     * Class that holds information about a chat. Having this class avoids having to pass
     * all the chat information as parameters across the methods.
     */
    class ChatInformation {

        private String sessionID;
        private Date creationDate;
        private Element transcript;
        private List<String> agentJIDs;
        private String notes;

        public ChatInformation(String sessionID, String transcriptXML, String startTime, String notes) {
            this.sessionID = sessionID;
            try {
                this.transcript = DocumentHelper.parseText(transcriptXML).getRootElement();
            }
            catch (DocumentException e) {
                Log log = ComponentManagerFactory.getComponentManager().getLog();
                log.error("Error retrieving chat information of session: " + sessionID, e);
                log.debug("Error retrieving chat information of session: " + sessionID +
                        " and transcript: " + transcriptXML, e);
            }
            this.creationDate = new Date(Long.parseLong(startTime));
            agentJIDs = new ArrayList<String>();

            this.notes = notes;
        }

        public String getSessionID() {
            return sessionID;
        }

        public Date getCreationDate() {
            return creationDate;
        }

        public Element getTranscript() {
            return transcript;
        }

        public List<String> getAgentJIDs() {
            return agentJIDs;
        }

        public String getNotes() {
            return notes;
        }
    }
}

⌨️ 快捷键说明

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