1+ // Copyright 2018 The NATS Authors
2+ // Licensed under the Apache License, Version 2.0 (the "License");
3+ // you may not use this file except in compliance with the License.
4+ // You may obtain a copy of the License at:
5+ //
6+ // http://www.apache.org/licenses/LICENSE-2.0
7+ //
8+ // Unless required by applicable law or agreed to in writing, software
9+ // distributed under the License is distributed on an "AS IS" BASIS,
10+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+ // See the License for the specific language governing permissions and
12+ // limitations under the License.
13+
14+ package io .nats .examples ;
15+
16+ import java .time .Duration ;
17+
18+ import io .nats .client .AuthHandler ;
19+ import io .nats .client .Connection ;
20+ import io .nats .client .ConnectionListener ;
21+ import io .nats .client .Nats ;
22+ import io .nats .client .Options ;
23+
24+ public class ExampleUtils {
25+ public static Options createExampleOptions (String server , boolean allowReconnect ) throws Exception {
26+ Options .Builder builder = new Options .Builder ().
27+ server (server ).
28+ connectionTimeout (Duration .ofSeconds (5 )).
29+ pingInterval (Duration .ofSeconds (10 )).
30+ reconnectWait (Duration .ofSeconds (1 )).
31+ connectionListener (new ConnectionListener (){
32+ public void connectionEvent (Connection conn , Events type ) {
33+ System .out .println ("Status change " +type );
34+ }
35+ });
36+
37+ if (!allowReconnect ) {
38+ builder = builder .noReconnect ();
39+ } else {
40+ builder = builder .maxReconnects (-1 );
41+ }
42+
43+ if (System .getenv ("NATS_NKEY" ) != null && System .getenv ("NATS_NKEY" ) != "" ) {
44+ AuthHandler handler = new ExampleAuthHandler (System .getenv ("NATS_NKEY" ));
45+ builder .authHandler (handler );
46+ } else if (System .getenv ("NATS_CREDS" ) != null && System .getenv ("NATS_CREDS" ) != "" ) {
47+ builder .authHandler (Nats .credentials (System .getenv ("NATS_CREDS" )));
48+ }
49+
50+ return builder .build ();
51+ }
52+ }
0 commit comments