aboutsummaryrefslogtreecommitdiff
path: root/juick-server/src/main/java/com/juick/server/xmpp/router/Stream.java
blob: 2154edf6cc868a84ca2f3c1df5d3efefa33c8443 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
 * Juick
 * Copyright (C) 2008-2011, Ugnich Anton
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.juick.server.xmpp.router;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import rocks.xmpp.addr.Jid;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.UUID;

/**
 *
 * @author Ugnich Anton
 */
public abstract class Stream {

    public boolean isLoggedIn() {
        return loggedIn;
    }

    public void setLoggedIn(boolean loggedIn) {
        this.loggedIn = loggedIn;
    }

    public Jid from;
    public Jid to;
    private InputStream is;
    private OutputStream os;
    private XmlPullParserFactory factory;
    protected XmlPullParser parser;
    private OutputStreamWriter writer;
    StreamHandler streamHandler;
    private boolean loggedIn;
    private Instant created;
    private Instant updated;
    String streamId;
    private boolean secured;

    public Stream(final Jid from, final Jid to, final InputStream is, final OutputStream os) throws XmlPullParserException {
        this.from = from;
        this.to = to;
        this.is = is;
        this.os = os;
        factory = XmlPullParserFactory.newInstance();
        created = updated = Instant.now();
        streamId = UUID.randomUUID().toString();
    }

    public void restartStream() throws XmlPullParserException {
        parser = factory.newPullParser();
        parser.setInput(new InputStreamReader(is, StandardCharsets.UTF_8));
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        writer = new OutputStreamWriter(os, StandardCharsets.UTF_8);
    }

    public void connect() {
        try {
            restartStream();
            handshake();
            parse();
        } catch (XmlPullParserException e) {
            StreamError invalidXmlError = new StreamError("invalid-xml");
            send(invalidXmlError.toString());
            connectionFailed(new Exception(invalidXmlError.getCondition()));
        } catch (IOException e) {
            connectionFailed(e);
        }
    }

    public void setHandler(final StreamHandler streamHandler) {
        this.streamHandler = streamHandler;
    }

    public abstract void handshake() throws XmlPullParserException, IOException;

    public void logoff() {
        setLoggedIn(false);
        try {
            writer.flush();
            writer.close();
            //TODO close parser
        } catch (final Exception e) {
            connectionFailed(e);
        }
    }

    public void send(final String str) {
        try {
            updated = Instant.now();
            writer.write(str);
            writer.flush();
        } catch (final Exception e) {
            connectionFailed(e);
        }
    }

    private void parse() throws IOException, XmlPullParserException {
        while (parser.next() != XmlPullParser.END_DOCUMENT) {
            if (parser.getEventType() == XmlPullParser.IGNORABLE_WHITESPACE) {
                setUpdated();
            }
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            setUpdated();
            final String tag = parser.getName();
            switch (tag) {
                case "message":
                case "presence":
                case "iq":
                    streamHandler.stanzaReceived(XmlUtils.parseToString(parser, false));
                    break;
                case "error":
                    StreamError error = StreamError.parse(parser);
                    connectionFailed(new Exception(error.getCondition()));
                    return;
                default:
                    XmlUtils.skip(parser);
                    break;
            }
        }
    }

    /**
     * This method is used to be called on a parser or a connection error.
     * It tries to close the XML-Reader and XML-Writer one last time.
     */
    private void connectionFailed(final Exception ex) {
        if (isLoggedIn()) {
            try {
                writer.close();
                //TODO close parser
            } catch (Exception e) {
            }
        }
        if (streamHandler != null) {
            streamHandler.fail(ex);
        }
    }

    public Instant getCreated() {
        return created;
    }

    public Instant getUpdated() {
        return updated;
    }
    public String getStreamId() {
        return streamId;
    }

    public boolean isSecured() {
        return secured;
    }

    public void setSecured(boolean secured) {
        this.secured = secured;
    }

    public void setUpdated() {
        this.updated = Instant.now();
    }

    public InputStream getInputStream() {
        return is;
    }

    public void setInputStream(InputStream is) {
        this.is = is;
    }

    public OutputStream getOutputStream() {
        return os;
    }

    public void setOutputStream(OutputStream os) {
        this.os = os;
    }
}