1
1
package com.vaadin.plugin.copilot.service
2
2
3
+ import com.intellij.openapi.diagnostic.Logger
3
4
import com.intellij.openapi.project.Project
5
+ import com.vaadin.plugin.copilot.CopilotPluginUtil
4
6
import io.ktor.util.network.*
7
+ import java.io.ByteArrayOutputStream
5
8
import java.io.IOException
6
9
import java.nio.ByteBuffer
7
10
import java.nio.channels.SelectionKey
@@ -13,6 +16,8 @@ import java.util.*
13
16
// Server implementation based on https://github.com/teocci/NioSocketCodeSample/tree/master
14
17
class CopilotServerServiceImpl (private val project : Project ): CopilotServerService {
15
18
19
+ private val LOG : Logger = Logger .getInstance(CopilotPluginUtil ::class .java)
20
+
16
21
private val timeout: Long = 500
17
22
18
23
private var serverChannel: ServerSocketChannel ? = null
@@ -47,7 +52,7 @@ class CopilotServerServiceImpl(private val project: Project): CopilotServerServi
47
52
serverChannel!! .register(selector, SelectionKey .OP_ACCEPT )
48
53
serverRunning = true
49
54
} catch (e: IOException ) {
50
- e.printStackTrace( )
55
+ LOG .error(e )
51
56
}
52
57
}
53
58
@@ -79,7 +84,7 @@ class CopilotServerServiceImpl(private val project: Project): CopilotServerServi
79
84
}
80
85
}
81
86
} catch (e: IOException ) {
82
- e.printStackTrace( )
87
+ LOG .error(e )
83
88
} finally {
84
89
closeConnection()
85
90
}
@@ -92,7 +97,7 @@ class CopilotServerServiceImpl(private val project: Project): CopilotServerServi
92
97
serverChannel!! .socket().close()
93
98
serverChannel!! .close()
94
99
} catch (e: IOException ) {
95
- e.printStackTrace( )
100
+ LOG .error(e )
96
101
}
97
102
}
98
103
}
@@ -109,28 +114,27 @@ class CopilotServerServiceImpl(private val project: Project): CopilotServerServi
109
114
private fun read (key : SelectionKey ): ByteArray? {
110
115
val channel = key.channel() as SocketChannel
111
116
val readBuffer = ByteBuffer .allocate(4096 )
112
- readBuffer.clear()
113
-
114
- val read: Int
117
+ val baos = ByteArrayOutputStream ()
118
+ var read: Int
115
119
try {
116
- read = channel.read(readBuffer)
120
+ while (true ) {
121
+ readBuffer.clear()
122
+ read = channel.read(readBuffer)
123
+ if (read == - 1 ) {
124
+ channel.close()
125
+ key.cancel()
126
+ break
127
+ }
128
+ baos.write(readBuffer.array(), 0 , read)
129
+ }
117
130
} catch (e: IOException ) {
118
- e.printStackTrace( )
131
+ LOG .error(e )
119
132
key.cancel()
120
133
channel.close()
121
134
return null
122
135
}
123
136
124
- if (read == - 1 ) {
125
- channel.close()
126
- key.cancel()
127
- return null
128
- }
129
- // IMPORTANT - don't forget the flip() the buffer. It is like a reset without clearing it.
130
- readBuffer.flip()
131
- val data = ByteArray (4096 )
132
- readBuffer[data, 0 , read]
133
- return data
137
+ return baos.toByteArray()
134
138
}
135
139
136
140
}
0 commit comments