4949import javax .security .auth .kerberos .KerberosTicket ;
5050
5151import java .io .File ;
52+ import java .io .IOException ;
5253import java .security .PrivilegedActionException ;
5354import java .util .ArrayList ;
5455import java .util .Collection ;
@@ -319,32 +320,30 @@ private String connectionString() {
319320 }
320321
321322 private RestHighLevelClient newClient () {
323+ RestHighLevelClient restHighLevelClient = null ;
324+
322325 try {
323326 if (StringUtils .isNotBlank (user ) && StringUtils .isNotBlank (password ) && password .contains ("keytab" ) && new File (password ).exists ()) {
324327 subject = CredentialsProviderUtil .login (user , password );
325328 }
326329
327330 RestClientBuilder restClientBuilder = getRestClientBuilder (hosts , protocol , user , password , port );
331+ restHighLevelClient = new RestHighLevelClient (restClientBuilder );
332+ boolean exists = false ;
328333
329- try (RestHighLevelClient restHighLevelClient = new RestHighLevelClient (restClientBuilder )) {
330- LOG .debug ("Initialized client" );
331-
332- boolean exists = false ;
333-
334- try {
335- exists = restHighLevelClient .indices ().open (new OpenIndexRequest (this .index ), RequestOptions .DEFAULT ).isShardsAcknowledged ();
336- } catch (Exception e ) {
337- LOG .warn ("Error validating index {}" , this .index );
338- }
339-
340- if (exists ) {
341- LOG .debug ("Index exists" );
342- } else {
343- LOG .info ("Index does not exist" );
344- }
334+ try {
335+ exists = restHighLevelClient .indices ().open (new OpenIndexRequest (this .index ), RequestOptions .DEFAULT ).isShardsAcknowledged ();
336+ } catch (Exception e ) {
337+ LOG .warn ("Error validating index {}" , this .index );
338+ }
345339
346- return restHighLevelClient ;
340+ if (exists ) {
341+ LOG .debug ("Index exists" );
342+ } else {
343+ LOG .info ("Index does not exist" );
347344 }
345+
346+ return restHighLevelClient ;
348347 } catch (Throwable t ) {
349348 lastLoggedAt .updateAndGet (lastLoggedAt -> {
350349 long now = System .currentTimeMillis ();
@@ -358,6 +357,16 @@ private RestHighLevelClient newClient() {
358357 return lastLoggedAt ;
359358 }
360359 });
360+
361+ if (restHighLevelClient != null ) {
362+ try {
363+ restHighLevelClient .close ();
364+ LOG .debug ("Closed RestHighLevelClient after failure" );
365+ } catch (IOException e ) {
366+ LOG .warn ("Error closing RestHighLevelClient: {}" , e .getMessage (), e );
367+ }
368+ }
369+
361370 return null ;
362371 }
363372 }
0 commit comments