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

📄 auditorimpl.java

📁 基于Jabber协议的即时消息服务器
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        }
    }

    /**
     * Deletes old audit files that exceeded the max number of days limit.
     */
    private void ensureMaxDays() {
        if (maxDays == -1) {
            // Do nothing since we don't have any limit
            return;
        }

        // Set limit date after which we need to delete old audit files
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, maxDays * -1);

        final String oldestFile =
                "jive.audit-" + dateFormat.format(calendar.getTime()) + "-000.log";

        // Get list of audit files to delete
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.startsWith("jive.audit-") && name.endsWith(".log") &&
                        name.compareTo(oldestFile) < 0;
            }
        };
        File[] files = baseFolder.listFiles(filter);
        // Delete old audit files
        for (File fileToDelete : files) {
            if (fileToDelete.equals(currentAuditFile)) {
                // Close current file
                close();
            }
            fileToDelete.delete();
        }
    }

    private void createAuditFile(Date auditDate) throws IOException {
        close();
        if (currentDateLimit == null || auditDate.after(currentDateLimit)) {
            // Set limit date after which we need to rollover the audit file (based on the date)
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(auditDate);
            calendar.set(Calendar.HOUR, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            currentDateLimit = calendar.getTime();
        }

        final String filePrefix = "jive.audit-" + dateFormat.format(auditDate) + "-";
        // Get list of existing audit files
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.startsWith(filePrefix) && name.endsWith(".log");
            }
        };
        File[] files = baseFolder.listFiles(filter);
        if (files.length == 0) {
            // This is the first audit file for the day
            currentAuditFile = new File(logDir, filePrefix + "000.log");
        }
        else {
            // Search the last index used for the day
            File lastFile = files[files.length - 1];
            StringTokenizer tokenizer = new StringTokenizer(lastFile.getName(), "-.");
            // Skip "jive"
            tokenizer.nextToken();
            // Skip "audit"
            tokenizer.nextToken();
            // Skip "date"
            tokenizer.nextToken();
            int index = Integer.parseInt(tokenizer.nextToken()) + 1;
            if (index > 999) {
                Log.warn("Failed to created audit file. Max limit of 999 files has been reached " +
                        "for the date: " + dateFormat.format(auditDate));
                return;
            }
            currentAuditFile = new File(logDir,
                    filePrefix + StringUtils.zeroPadString(Integer.toString(index), 3) + ".log");
        }


        // Find the next available log file name
        /*for (int i = 0; i < 1000; i++) {
            currentAuditFile = new File(logDir,
                    filePrefix + StringUtils.zeroPadString(Integer.toString(i), 3) + ".log");
            if (!currentAuditFile.exists()) {
                break;
            }
        }

        if (currentAuditFile == null) {
            Log.warn("Audit log not create since there are more than 999 files for the date: " +
                    dateFormat.format(auditDate));
            return;
        }*/

        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(currentAuditFile), "UTF-8"));
        writer.write("<jive xmlns=\"http://www.jivesoftware.org\">");
        xmlWriter = new org.jivesoftware.util.XMLWriter(writer);
    }

    /**
     * Saves the queued entries to an XML file and checks that very old files are deleted.
     */
    private class SaveQueuedPacketsTask extends TimerTask {
        public void run() {
            try {
                // Ensure that saved audit logs are not too old
                ensureMaxDays();
                // Save queued packets to the audit logs
                saveQueuedPackets();
            }
            catch (Throwable e) {
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        }
    }

    private void saveQueuedPackets() {
        List<AuditPacket> packets = new ArrayList<AuditPacket>(logQueue.size());
        logQueue.drainTo(packets);
        for (AuditPacket auditPacket : packets) {
            try {
                prepareAuditFile(auditPacket.getCreationDate());
                Element element = auditPacket.getElement();
                // Protect against null elements.
                if (element != null) {
                    xmlWriter.write(element);
                }
            }
            catch (IOException e) {
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                // Add again the entry to the queue to save it later
                if (xmlWriter != null) {
                    logQueue.add(auditPacket);
                }
            }
        }
        try {
            if (xmlWriter != null) {
                xmlWriter.flush();
            }
        }
        catch (IOException ioe) {
            Log.error(ioe);
        }
    }

    /**
     * Wrapper on a Packet with information about the packet's status at the moment
     * when the message was queued.<p>
     *
     * The idea is to wrap every packet that is needed to be audited and then add the
     * wrapper to a queue that will be later processed (i.e. saved to the XML file).
     */
    private static class AuditPacket {

        private static DocumentFactory docFactory = DocumentFactory.getInstance();

        private Element element;
        private Date creationDate;

        public AuditPacket(Packet packet, Session session) {
            element = docFactory.createElement("packet", "http://www.jivesoftware.org");
            creationDate = new Date();
            if (session.getStreamID() != null) {
                element.addAttribute("streamID", session.getStreamID().toString());
            }
            switch (session.getStatus()) {
                case Session.STATUS_AUTHENTICATED:
                    element.addAttribute("status", "auth");
                    break;
                case Session.STATUS_CLOSED:
                    element.addAttribute("status", "closed");
                    break;
                case Session.STATUS_CONNECTED:
                    element.addAttribute("status", "connected");
                    // This is a workaround. Since we don't want to have an incorrect FROM attribute
                    // value we need to clean up the FROM attribute. The FROM attribute will contain
                    // an incorrect value since we are setting a fake JID until the user actually
                    // authenticates with the server.
                    packet.setFrom((String) null);
                    break;
                case Session.STATUS_STREAMING:
                    element.addAttribute("status", "stream");
                    break;
                default:
                    element.addAttribute("status", "unknown");
                    break;
            }
            element.addAttribute("timestamp", JiveGlobals.formatDateTime(creationDate));
            element.add(packet.getElement());
        }

        /**
         * Returns the Element associated with this audit packet.
         *
         * @return the Element.
         */
        public Element getElement() {
            return element;
        }

        /**
         * Returns the date when the packet was audited. This is the time when the
         * packet was queued to be saved.
         *
         * @return the date when the packet was audited.
         */
        public Date getCreationDate() {
            return creationDate;
        }
    }
}

⌨️ 快捷键说明

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