Skip to content

Commit 6266b79

Browse files
committed
TS-38628 Resolve cucumber test issue and various refactorings
1 parent 61cb789 commit 6266b79

File tree

18 files changed

+144
-225
lines changed

18 files changed

+144
-225
lines changed

report-generator/src/main/java/com/teamscale/report/jacoco/OpenAnalyzer.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@
5454
* {@link Analyzer} requires a {@link ExecutionDataStore} instance that holds
5555
* the execution data for the classes to analyze. The {@link Analyzer} offers
5656
* several methods to analyze classes from a variety of sources.
57+
* <p>
58+
* CAUTION: Do not convert to Kotlin. This class has to stay in Java for future maintenance reasons!
5759
*/
5860
public class OpenAnalyzer {
5961

report-generator/src/main/java/org/jacoco/core/internal/analysis/CachingInstructionsBuilder.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
* <p>
3030
* When updating JaCoCo make a diff of the previous {@link org.jacoco.core.internal.analysis.InstructionsBuilder}
3131
* implementation and the new implementation and update this class accordingly.
32+
* <p>
33+
* CAUTION: Do not convert to Kotlin. This class has to stay in Java for future maintenance reasons!
3234
*/
3335
public class CachingInstructionsBuilder extends InstructionsBuilder {
3436

teamscale-client/src/main/kotlin/com/teamscale/client/AntPatternUtils.kt

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,14 +149,12 @@ object AntPatternUtils {
149149
* Returns whether the given position exists in the string and equals the given character, and the given character
150150
* is either at the end or right before a slash.
151151
*/
152-
private fun isCharAtBeforeSlashOrEnd(s: String, position: Int, character: Char): Boolean {
153-
return isCharAt(s, position, character) && (position + 1 == s.length || isCharAt(s, position + 1, '/'))
154-
}
152+
private fun isCharAtBeforeSlashOrEnd(s: String, position: Int, character: Char) =
153+
isCharAt(s, position, character) && (position + 1 == s.length || isCharAt(s, position + 1, '/'))
155154

156155
/**
157156
* Returns whether the given position exists in the string and equals the given character.
158157
*/
159-
private fun isCharAt(s: String, position: Int, character: Char): Boolean {
160-
return position < s.length && s[position] == character
161-
}
158+
private fun isCharAt(s: String, position: Int, character: Char) =
159+
position < s.length && s[position] == character
162160
}

teamscale-client/src/main/kotlin/com/teamscale/client/ClusteredTestDetails.kt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,7 @@ class ClusteredTestDetails @JsonCreator constructor(
4040
fun createWithTestData(
4141
uniformPath: String, sourcePath: String, testData: TestData,
4242
clusterId: String, partition: String
43-
): ClusteredTestDetails {
44-
return ClusteredTestDetails(uniformPath, sourcePath, testData.hash, clusterId, partition)
45-
}
43+
) = ClusteredTestDetails(uniformPath, sourcePath, testData.hash, clusterId, partition)
4644
}
4745
}
4846

teamscale-client/src/main/kotlin/com/teamscale/client/CommitDescriptor.kt

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import java.io.Serializable
44
import java.util.*
55

66
/** Holds the branch and timestamp of a commit. */
7-
class CommitDescriptor
8-
/** Constructor. */(
7+
data class CommitDescriptor(
98
/** Branch name of the commit. */
109
@JvmField val branchName: String,
1110
/**
@@ -18,25 +17,7 @@ class CommitDescriptor
1817
constructor(branchName: String, timestamp: Long) : this(branchName, timestamp.toString())
1918

2019
/** Returns a string representation of the commit in a Teamscale REST API compatible format. */
21-
override fun toString(): String {
22-
return "$branchName:$timestamp"
23-
}
24-
25-
override fun equals(o: Any?): Boolean {
26-
if (this === o) {
27-
return true
28-
}
29-
if (o == null || javaClass != o.javaClass) {
30-
return false
31-
}
32-
val that = o as CommitDescriptor
33-
return branchName == that.branchName &&
34-
timestamp == that.timestamp
35-
}
36-
37-
override fun hashCode(): Int {
38-
return Objects.hash(branchName, timestamp)
39-
}
20+
override fun toString() = "$branchName:$timestamp"
4021

4122
companion object {
4223
/** Parses the given commit descriptor string. */

teamscale-client/src/main/kotlin/com/teamscale/client/EReportFormat.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ enum class EReportFormat(
158158
/**
159159
* Coverage report generated with the Lauterbach Trace32 tool. See section for
160160
* [Supported
161-
* Upload Formats and Samples](https://docs.teamscale.com/reference/upload-formats-and-samples/) in the user guide for more information about
161+
* Upload Formats and Samples](https://docs.teamscale.com/reference/upload-formats-and-samples/) in the user guide for more information about
162162
* the Lauterbach Trace32 tool. See the `trace32_example_reports.zip` for
163163
* additional report examples.
164164
*/

teamscale-client/src/main/kotlin/com/teamscale/client/FileLoggingInterceptor.kt

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import okhttp3.Interceptor
44
import okhttp3.Request
55
import okhttp3.Response
66
import okhttp3.ResponseBody
7+
import okhttp3.ResponseBody.Companion.toResponseBody
78
import okio.Buffer
89
import java.io.File
910
import java.io.FileWriter
@@ -13,44 +14,35 @@ import java.io.PrintWriter
1314
/**
1415
* OkHttpInterceptor which prints out the full request and server response of requests to a file.
1516
*/
16-
class FileLoggingInterceptor
17-
/** Constructor. */(private val logfile: File) : Interceptor {
17+
class FileLoggingInterceptor(
18+
private val logfile: File
19+
) : Interceptor {
1820
@Throws(IOException::class)
1921
override fun intercept(chain: Interceptor.Chain): Response {
20-
val request: Request = chain.request()
22+
val request = chain.request()
2123

2224
val requestStartTime = System.nanoTime()
2325
PrintWriter(FileWriter(logfile)).use { fileWriter ->
2426
fileWriter.write(
25-
String.format(
26-
"--> Sending request %s on %s %s%n%s%n", request.method, request.url,
27-
chain.connection(),
28-
request.headers
29-
)
27+
"--> Sending request ${request.method} on ${request.url} ${chain.connection()}\n${request.headers}\n"
3028
)
3129
val requestBuffer = Buffer()
32-
if (request.body != null) {
33-
request.body?.writeTo(requestBuffer)
34-
}
30+
request.body?.writeTo(requestBuffer)
3531
fileWriter.write(requestBuffer.readUtf8())
3632

3733
val response = getResponse(chain, request, fileWriter)
38-
3934
val requestEndTime = System.nanoTime()
4035
fileWriter.write(
41-
String.format(
42-
"<-- Received response for %s %s in %.1fms%n%s%n%n", response.code,
43-
response.request.url, (requestEndTime - requestStartTime) / 1e6, response.headers
44-
)
36+
"<-- Received response for ${response.code} ${response.request.url} in ${(requestEndTime - requestStartTime) / 1e6}ms\n${response.headers}\n\n"
4537
)
4638

4739
var wrappedBody: ResponseBody? = null
48-
if (response.body != null) {
49-
val contentType = response.body!!.contentType()
50-
val content = response.body!!.string()
40+
response.body?.let {
41+
val contentType = it.contentType()
42+
val content = it.string()
5143
fileWriter.write(content)
5244

53-
wrappedBody = ResponseBody.create(contentType, content)
45+
wrappedBody = content.toResponseBody(contentType)
5446
}
5547
return response.newBuilder().body(wrappedBody).build()
5648
}

teamscale-client/src/main/kotlin/com/teamscale/client/FileSystemUtils.kt

Lines changed: 0 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,9 @@ import java.nio.charset.StandardCharsets
77
* File system utilities.
88
*/
99
object FileSystemUtils {
10-
/** Encoding for UTF-8. */
11-
val UTF8_ENCODING: String = StandardCharsets.UTF_8.name()
12-
1310
/** Unix file path separator */
1411
private const val UNIX_SEPARATOR = '/'
1512

16-
/**
17-
* Checks if a directory exists. If not it creates the directory and all necessary parent directories.
18-
*
19-
* @throws IOException if directories couldn't be created.
20-
*/
21-
@Throws(IOException::class)
22-
fun ensureDirectoryExists(directory: File) {
23-
if (!directory.exists() && !directory.mkdirs()) {
24-
throw IOException("Couldn't create directory: $directory")
25-
}
26-
}
27-
2813
/**
2914
* Returns a list of all files and directories contained in the given directory and all subdirectories matching the
3015
* filter provided. The given directory itself is not included in the result.
@@ -130,19 +115,4 @@ object FileSystemUtils {
130115
}
131116
return size
132117
}
133-
134-
/**
135-
* Returns the name of the given file without extension. Example:
136-
* '/home/joe/data.dat' returns 'data'.
137-
*/
138-
fun getFilenameWithoutExtension(file: File): String {
139-
return getFilenameWithoutExtension(file.name)
140-
}
141-
142-
/**
143-
* Returns the name of the given file without extension. Example: 'data.dat' returns 'data'.
144-
*/
145-
fun getFilenameWithoutExtension(fileName: String): String {
146-
return StringUtils.removeLastPart(fileName, '.')
147-
}
148118
}

teamscale-client/src/main/kotlin/com/teamscale/client/HttpUtils.kt

Lines changed: 31 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,6 @@ import okhttp3.Authenticator
44
import okhttp3.Credentials.basic
55
import okhttp3.Interceptor
66
import okhttp3.OkHttpClient.Builder
7-
import okhttp3.Response
8-
import okhttp3.Route
9-
import org.slf4j.Logger
107
import org.slf4j.LoggerFactory
118
import retrofit2.Retrofit
129
import java.io.IOException
@@ -24,24 +21,24 @@ import javax.net.ssl.*
2421
* Utility functions to set up [Retrofit] and [OkHttpClient].
2522
*/
2623
object HttpUtils {
27-
private val LOGGER: Logger = LoggerFactory.getLogger(HttpUtils::class.java)
24+
private val LOGGER = LoggerFactory.getLogger(HttpUtils::class.java)
2825

2926
/**
3027
* Default read timeout in seconds.
3128
*/
3229
@JvmField
33-
val DEFAULT_READ_TIMEOUT: Duration = Duration.ofSeconds(60)
30+
val DEFAULT_READ_TIMEOUT = Duration.ofSeconds(60)
3431

3532
/**
3633
* Default write timeout in seconds.
3734
*/
3835
@JvmField
39-
val DEFAULT_WRITE_TIMEOUT: Duration = Duration.ofSeconds(60)
36+
val DEFAULT_WRITE_TIMEOUT = Duration.ofSeconds(60)
4037

4138
/**
4239
* HTTP header used for authenticating against a proxy server
4340
*/
44-
const val PROXY_AUTHORIZATION_HTTP_HEADER: String = "Proxy-Authorization"
41+
const val PROXY_AUTHORIZATION_HTTP_HEADER = "Proxy-Authorization"
4542

4643
/** Controls whether [OkHttpClient]s built with this class will validate SSL certificates. */
4744
private var shouldValidateSsl = true
@@ -68,10 +65,11 @@ object HttpUtils {
6865
okHttpBuilderAction: Consumer<Builder>, readTimeout: Duration = DEFAULT_READ_TIMEOUT,
6966
writeTimeout: Duration = DEFAULT_WRITE_TIMEOUT
7067
): Retrofit {
71-
val httpClientBuilder = Builder()
72-
setTimeouts(httpClientBuilder, readTimeout, writeTimeout)
73-
setUpSslValidation(httpClientBuilder)
74-
setUpProxyServer(httpClientBuilder)
68+
val httpClientBuilder = Builder().apply {
69+
setTimeouts(readTimeout, writeTimeout)
70+
setUpSslValidation()
71+
setUpProxyServer()
72+
}
7573
okHttpBuilderAction.accept(httpClientBuilder)
7674

7775
val builder = Retrofit.Builder().client(httpClientBuilder.build())
@@ -88,41 +86,39 @@ object HttpUtils {
8886
* &
8987
* [https://stackoverflow.com/a/35567936](https://stackoverflow.com/a/35567936)
9088
*/
91-
private fun setUpProxyServer(httpClientBuilder: Builder) {
89+
private fun Builder.setUpProxyServer() {
9290
val setHttpsProxyWasSuccessful = setUpProxyServerForProtocol(
9391
ProxySystemProperties.Protocol.HTTPS,
94-
httpClientBuilder
92+
this
9593
)
9694
if (!setHttpsProxyWasSuccessful) {
97-
setUpProxyServerForProtocol(ProxySystemProperties.Protocol.HTTP, httpClientBuilder)
95+
setUpProxyServerForProtocol(ProxySystemProperties.Protocol.HTTP, this)
9896
}
9997
}
10098

10199
private fun setUpProxyServerForProtocol(
102100
protocol: ProxySystemProperties.Protocol,
103101
httpClientBuilder: Builder
104102
): Boolean {
105-
val teamscaleProxySystemProperties = TeamscaleProxySystemProperties(protocol)
103+
val proxySystemProperties = TeamscaleProxySystemProperties(protocol)
106104
try {
107-
if (!teamscaleProxySystemProperties.isProxyServerSet()) {
105+
if (!proxySystemProperties.isProxyServerSet()) {
108106
return false
109107
}
110108

111109
useProxyServer(
112-
httpClientBuilder, teamscaleProxySystemProperties.proxyHost!!,
113-
teamscaleProxySystemProperties.proxyPort
110+
httpClientBuilder, proxySystemProperties.proxyHost!!,
111+
proxySystemProperties.proxyPort
114112
)
115113
} catch (e: ProxySystemProperties.IncorrectPortFormatException) {
116114
LOGGER.warn(e.message)
117115
return false
118116
}
119117

120-
if (teamscaleProxySystemProperties.isProxyAuthSet()) {
121-
useProxyAuthenticator(
122-
httpClientBuilder,
123-
teamscaleProxySystemProperties.proxyUser!!,
124-
teamscaleProxySystemProperties.proxyPassword!!
125-
)
118+
if (proxySystemProperties.isProxyAuthSet()) {
119+
val user = proxySystemProperties.proxyUser ?: return false
120+
val password = proxySystemProperties.proxyPassword ?: return false
121+
useProxyAuthenticator(httpClientBuilder, user, password)
126122
}
127123

128124
return true
@@ -133,7 +129,7 @@ object HttpUtils {
133129
}
134130

135131
private fun useProxyAuthenticator(httpClientBuilder: Builder, user: String, password: String) {
136-
val proxyAuthenticator = Authenticator { route: Route?, response: Response ->
132+
val proxyAuthenticator = Authenticator { _, response ->
137133
val credential = basic(user, password)
138134
response.request.newBuilder()
139135
.header(PROXY_AUTHORIZATION_HTTP_HEADER, credential)
@@ -146,16 +142,16 @@ object HttpUtils {
146142
/**
147143
* Sets sensible defaults for the [OkHttpClient].
148144
*/
149-
private fun setTimeouts(builder: Builder, readTimeout: Duration, writeTimeout: Duration) {
150-
builder.connectTimeout(Duration.ofSeconds(60))
151-
builder.readTimeout(readTimeout)
152-
builder.writeTimeout(writeTimeout)
145+
private fun Builder.setTimeouts(readTimeout: Duration, writeTimeout: Duration) {
146+
connectTimeout(Duration.ofSeconds(60))
147+
readTimeout(readTimeout)
148+
writeTimeout(writeTimeout)
153149
}
154150

155151
/**
156152
* Enables or disables SSL certificate validation for the [Retrofit] instance
157153
*/
158-
private fun setUpSslValidation(builder: Builder) {
154+
private fun Builder.setUpSslValidation() {
159155
if (shouldValidateSsl) {
160156
// this is the default behaviour of OkHttp, so we don't need to do anything
161157
return
@@ -164,17 +160,17 @@ object HttpUtils {
164160
val sslSocketFactory: SSLSocketFactory
165161
try {
166162
val sslContext = SSLContext.getInstance("TLS")
167-
sslContext.init(null, arrayOf<TrustManager>(TrustAllCertificatesManager.INSTANCE), SecureRandom())
163+
sslContext.init(null, arrayOf<TrustManager>(TrustAllCertificatesManager), SecureRandom())
168164
sslSocketFactory = sslContext.socketFactory
169165
} catch (e: GeneralSecurityException) {
170166
LOGGER.error("Could not disable SSL certificate validation. Leaving it enabled", e)
171167
return
172168
}
173169

174170
// this causes OkHttp to accept all certificates
175-
builder.sslSocketFactory(sslSocketFactory, TrustAllCertificatesManager.INSTANCE)
171+
sslSocketFactory(sslSocketFactory, TrustAllCertificatesManager)
176172
// this causes it to ignore invalid host names in the certificates
177-
builder.hostnameVerifier(HostnameVerifier { hostName: String?, session: SSLSession? -> true })
173+
hostnameVerifier { _, _ -> true }
178174
}
179175

180176
/**
@@ -204,11 +200,9 @@ object HttpUtils {
204200
/**
205201
* A simple implementation of [X509TrustManager] that simple trusts every certificate.
206202
*/
207-
class TrustAllCertificatesManager : X509TrustManager {
203+
object TrustAllCertificatesManager : X509TrustManager {
208204
/** Returns `null`. */
209-
override fun getAcceptedIssuers(): Array<X509Certificate> {
210-
return arrayOf()
211-
}
205+
override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
212206

213207
/** Does nothing. */
214208
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) {
@@ -219,10 +213,5 @@ object HttpUtils {
219213
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) {
220214
// Nothing to do
221215
}
222-
223-
companion object {
224-
/** Singleton instance. */ /*package*/
225-
val INSTANCE: TrustAllCertificatesManager = TrustAllCertificatesManager()
226-
}
227216
}
228217
}

0 commit comments

Comments
 (0)