• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

igniterealtime / Smack / #2900

25 Nov 2023 06:57PM UTC coverage: 39.144% (+0.01%) from 39.13%
#2900

push

github

Flowdalic
[websocket] Do not swallow exceptions and use QName

Follow up on c4d11eae299e ("[websocket] Reduce fragility")

4 of 6 new or added lines in 1 file covered. (66.67%)

31 existing lines in 3 files now uncovered.

16382 of 41851 relevant lines covered (39.14%)

0.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

35.19
/smack-websocket/src/main/java/org/jivesoftware/smack/websocket/impl/AbstractWebSocket.java
1
/**
2
 *
3
 * Copyright 2020 Aditya Borikar, 2020-2023 Florian Schmaus
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
package org.jivesoftware.smack.websocket.impl;
18

19
import java.io.IOException;
20
import java.util.logging.Level;
21
import java.util.logging.Logger;
22

23
import javax.net.ssl.SSLSession;
24
import javax.xml.namespace.QName;
25

26
import org.jivesoftware.smack.SmackFuture;
27
import org.jivesoftware.smack.c2s.internal.ModularXmppClientToServerConnectionInternal;
28
import org.jivesoftware.smack.debugger.SmackDebugger;
29
import org.jivesoftware.smack.packet.TopLevelStreamElement;
30
import org.jivesoftware.smack.packet.XmlEnvironment;
31
import org.jivesoftware.smack.util.PacketParserUtils;
32
import org.jivesoftware.smack.websocket.WebSocketException;
33
import org.jivesoftware.smack.websocket.elements.WebSocketCloseElement;
34
import org.jivesoftware.smack.websocket.elements.WebSocketOpenElement;
35
import org.jivesoftware.smack.websocket.rce.WebSocketRemoteConnectionEndpoint;
36
import org.jivesoftware.smack.xml.XmlPullParser;
37
import org.jivesoftware.smack.xml.XmlPullParserException;
38

39
public abstract class AbstractWebSocket {
40

41
    protected static final Logger LOGGER = Logger.getLogger(AbstractWebSocket.class.getName());
1✔
42

43
    protected static final String SEC_WEBSOCKET_PROTOCOL_HEADER_FILED_NAME = "Sec-WebSocket-Protocol";
44
    protected static final String SEC_WEBSOCKET_PROTOCOL_HEADER_FILED_VALUE_XMPP = "xmpp";
45

46
    protected final SmackFuture.InternalSmackFuture<AbstractWebSocket, Exception> future = new SmackFuture.InternalSmackFuture<>();
1✔
47

48
    protected final ModularXmppClientToServerConnectionInternal connectionInternal;
49

50
    protected final WebSocketRemoteConnectionEndpoint endpoint;
51

52
    private final SmackWebSocketDebugger debugger;
53

54
    protected AbstractWebSocket(WebSocketRemoteConnectionEndpoint endpoint,
55
                    ModularXmppClientToServerConnectionInternal connectionInternal) {
1✔
56
        this.endpoint = endpoint;
1✔
57
        this.connectionInternal = connectionInternal;
1✔
58

59
        final SmackDebugger smackDebugger = connectionInternal.smackDebugger;
1✔
60
        if (smackDebugger != null) {
1✔
UNCOV
61
            debugger = new SmackWebSocketDebugger(smackDebugger);
×
62
        } else {
63
            debugger = null;
1✔
64
        }
65
    }
1✔
66

67
    public final WebSocketRemoteConnectionEndpoint getEndpoint() {
UNCOV
68
        return endpoint;
×
69
    }
70

71
    private String streamOpen;
72
    private String streamClose;
73

74
    protected final void onIncomingWebSocketElement(String element) {
UNCOV
75
        if (debugger != null) {
×
UNCOV
76
            debugger.incoming(element);
×
77
        }
78

79
        // TODO: Once smack-websocket-java15 is there, we have to re-evaluate if the async operation here is still
80
        // required, or if it should only be performed if OkHTTP is used.
81
        if (isOpenElement(element)) {
×
82
            // Transform the XMPP WebSocket <open/> element to a RFC 6120 <stream> open tag.
UNCOV
83
            streamOpen = getStreamFromOpenElement(element);
×
84
            streamClose = connectionInternal.onStreamOpen(streamOpen);
×
85
            return;
×
86
        }
87

UNCOV
88
        if (isCloseElement(element)) {
×
89
            connectionInternal.onStreamClosed();
×
UNCOV
90
            return;
×
91
        }
92

UNCOV
93
        connectionInternal.withSmackDebugger(debugger -> debugger.onIncomingElementCompleted());
×
94

95
        // TODO: Do we need to wrap the element again in the stream open to get the
96
        // correct XML scoping (just like the modular TCP connection does)? It appears
97
        // that this not really required, as onStreamOpen() will set the incomingStreamEnvironment, which is used for
98
        // parsing.
UNCOV
99
        String wrappedCompleteElement = streamOpen + element + streamClose;
×
UNCOV
100
        connectionInternal.parseAndProcessElement(wrappedCompleteElement);
×
UNCOV
101
    }
×
102

103
    static String getStreamFromOpenElement(String openElement) {
104
        String streamElement = openElement.replaceFirst("\\A<open ", "<stream:stream ")
1✔
105
                                          .replace("urn:ietf:params:xml:ns:xmpp-framing", "jabber:client")
1✔
106
                                          .replaceFirst("/>\\s*\\z", " xmlns:stream='http://etherx.jabber.org/streams'>");
1✔
107
        return streamElement;
1✔
108
    }
109

110
    static boolean isOpenElement(String text) {
111
        XmlPullParser parser;
112
        try {
113
            parser = PacketParserUtils.getParserFor(text);
1✔
114
            QName qname = parser.getQName();
1✔
115
            return qname.equals(WebSocketOpenElement.QNAME);
1✔
UNCOV
116
        } catch (XmlPullParserException | IOException e) {
×
NEW
117
            LOGGER.log(Level.WARNING, "Could not inspect \"" + text + "\" for open element", e);
×
UNCOV
118
            return false;
×
119
        }
120
    }
121

122
    static boolean isCloseElement(String text) {
123
        XmlPullParser parser;
124
        try {
125
            parser = PacketParserUtils.getParserFor(text);
1✔
126
            QName qname = parser.getQName();
1✔
127
            return qname.equals(WebSocketCloseElement.QNAME);
1✔
UNCOV
128
        } catch (XmlPullParserException | IOException e) {
×
NEW
129
            LOGGER.log(Level.WARNING, "Could not inspect \"" + text + "\" for close element", e);
×
UNCOV
130
            return false;
×
131
        }
132
    }
133

134
    protected void onWebSocketFailure(Throwable throwable) {
UNCOV
135
        WebSocketException websocketException = new WebSocketException(throwable);
×
136

137
        // If we are already connected, then we need to notify the connection that it got tear down. Otherwise we
138
        // need to notify the thread calling connect() that the connection failed.
UNCOV
139
        if (future.wasSuccessful()) {
×
UNCOV
140
            connectionInternal.notifyConnectionError(websocketException);
×
141
        } else {
UNCOV
142
            future.setException(websocketException);
×
143
        }
UNCOV
144
    }
×
145

146
    public final SmackFuture<AbstractWebSocket, Exception> getFuture() {
UNCOV
147
        return future;
×
148
    }
149

150
    public final void send(TopLevelStreamElement element) {
UNCOV
151
        XmlEnvironment outgoingStreamXmlEnvironment = connectionInternal.getOutgoingStreamXmlEnvironment();
×
UNCOV
152
        String elementString = element.toXML(outgoingStreamXmlEnvironment).toString();
×
153

154
        // TODO: We could make use of Java 11's WebSocket (is)last feature when sending
UNCOV
155
        if (debugger != null) {
×
UNCOV
156
            debugger.outgoing(elementString);
×
157
        }
158

UNCOV
159
        send(elementString);
×
UNCOV
160
    }
×
161

162
    protected abstract void send(String element);
163

164
    public abstract void disconnect(int code, String message);
165

166
    public boolean isConnectionSecure() {
UNCOV
167
        return endpoint.isSecureEndpoint();
×
168
    }
169

170
    public abstract SSLSession getSSLSession();
171

172
    @Override
173
    public final String toString() {
UNCOV
174
        return getClass().getSimpleName() + "[" + connectionInternal.connection + "]";
×
175
    }
176
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc