summaryrefslogtreecommitdiff
path: root/src/main/java/com/lumaserv/bgp/BGPSession.java
blob: 669010bcc36c15155b2867285323aacb1bb30b16 (plain)
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
package com.lumaserv.bgp;

import com.lumaserv.bgp.protocol.BGPPacket;
import com.lumaserv.bgp.protocol.message.BGPUpdate;
import lombok.Getter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

public class BGPSession implements Runnable {

    @Getter
    final BGPSessionConfiguration configuration;
    final InputStream inputStream;
    final OutputStream outputStream;
    @Getter
    boolean closed;

    public BGPSession(Socket socket, BGPSessionConfiguration configuration) throws IOException {
        this.configuration = configuration;
        this.inputStream = socket.getInputStream();
        this.outputStream = socket.getOutputStream();
    }

    public void keepAlive() {
        try {
            outputStream.write(new BGPPacket().setType(BGPPacket.Type.KEEPALIVE).setMessage(new byte[0]).build());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handle(BGPPacket packet) {
        switch (packet.getType()) {
            case NOTIFICATION:
                closed = true;
                configuration.getListener().onClose(this);
                break;
            case KEEPALIVE:
                keepAlive();
                break;
            case UPDATE: {
                configuration.getListener().onUpdate(this, new BGPUpdate(packet.getMessage()));
                break;
            }
        }
    }

    public void run() {
        try {
            while (!closed) {
                try {
                    handle(BGPPacket.read(inputStream));
                } catch (SocketException ignored) {
                    closed = true;
                    configuration.getListener().onClose(this);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}