001/**
002 *
003 * Copyright 2020 Aditya Borikar, 2021 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.websocket.impl;
018
019import java.io.IOException;
020import java.util.logging.Level;
021import java.util.logging.Logger;
022
023import org.jivesoftware.smack.debugger.SmackDebugger;
024
025import org.jxmpp.xml.splitter.XmlPrettyPrinter;
026import org.jxmpp.xml.splitter.XmppXmlSplitter;
027
028public class SmackWebSocketDebugger {
029
030    private static final Logger LOGGER = Logger.getLogger(SmackWebSocketDebugger.class.getName());
031
032    private final SmackDebugger debugger;
033    private final XmppXmlSplitter incomingXmlSplitter;
034    private final XmppXmlSplitter outgoingXmlSplitter;
035
036    SmackWebSocketDebugger(SmackDebugger smackDebugger) {
037        this.debugger = smackDebugger;
038
039        XmlPrettyPrinter incomingTextPrinter = XmlPrettyPrinter.builder()
040                        .setPrettyWriter(sb -> debugger.incomingStreamSink(sb))
041                        .setTabWidth(4)
042                        .build();
043        incomingXmlSplitter = new XmppXmlSplitter(incomingTextPrinter);
044
045        XmlPrettyPrinter outgoingTextPrinter = XmlPrettyPrinter.builder()
046                        .setPrettyWriter(sb -> debugger.outgoingStreamSink(sb))
047                        .setTabWidth(4)
048                        .build();
049        outgoingXmlSplitter = new XmppXmlSplitter(outgoingTextPrinter);
050    }
051
052    void incoming(String text) {
053        try {
054            incomingXmlSplitter.write(text);
055        } catch (IOException e) {
056            // Connections shouldn't be terminated due to exceptions encountered during debugging. hence only log them.
057            LOGGER.log(Level.WARNING, "IOException encountered while parsing received text: " + text, e);
058        }
059    }
060
061    void outgoing(String text) {
062        try {
063            outgoingXmlSplitter.write(text);
064        } catch (IOException e) {
065            // Connections shouldn't be terminated due to exceptions encountered during debugging, hence only log them.
066            LOGGER.log(Level.WARNING, "IOException encountered while parsing outgoing text: " + text, e);
067        }
068    }
069}