-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathContentstack.java
More file actions
653 lines (614 loc) · 21.7 KB
/
Contentstack.java
File metadata and controls
653 lines (614 loc) · 21.7 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package com.contentstack.cms;
import com.contentstack.cms.core.AuthInterceptor;
import com.contentstack.cms.core.Util;
import com.contentstack.cms.models.Error;
import com.contentstack.cms.models.LoginDetails;
import com.contentstack.cms.organization.Organization;
import com.contentstack.cms.stack.Stack;
import com.contentstack.cms.user.User;
import com.google.gson.Gson;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
import java.net.Proxy;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import static com.contentstack.cms.core.Util.*;
/**
* <b>Contentstack Java Management SDK</b>
* <br>
* <b>Java Management SDK</b> Interact with the Content Management APIs and
* allow you to create, update,
* delete, and fetch content from your Contentstack account. (They are
* read-write in nature.)
* <br>
* You can use them to build your own apps and manage your content from
* Contentstack.
*/
public class Contentstack {
public final Logger logger = Logger.getLogger(Contentstack.class.getName());
protected final String host;
protected final String port;
protected final String version;
protected final int timeout;
protected String authtoken;
protected Retrofit instance;
protected final Boolean retryOnFailure;
protected final Proxy proxy;
protected AuthInterceptor interceptor;
protected String[] earlyAccess;
protected User user;
/**
* All accounts registered with Contentstack are known as Users. A stack can
* have many users with varying
* permissions and roles
* <p>
* To perform User operations first get User instance like below.
* <p>
* <b>Example:</b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().setAuthtoken("authtoken").build();
* User userInstance = contentstack.user();
* </pre>
*
* <br>
* <b>OR: </b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().setAuthtoken("authtoken").build();
* User user = contentstack.user();
* </pre>
*
* <br>
*
* @return User
* @author ***REMOVED***
* @see <a href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#users">User
* </a>
* @since 2022-05-19
*/
public User user() {
if (this.authtoken == null)
throw new NullPointerException(Util.LOGIN_FLAG);
user = new User(this.instance);
return user;
}
/**
* <b>[Note]:</b> Before executing any calls, retrieve the authtoken by
* authenticating yourself via the Log in call of User Session. The authtoken is
* returned to the 'Response' body of
* the Log in call and is mandatory in all the calls.
* <p>
* <b>Example:</b>
* <p>
* All accounts registered with Contentstack are known as Users. A stack can
* have many users with varying
* permissions and roles
* <p>
* To perform User operations first get User instance like below.
* <p>
* <b>Example:</b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().setAuthtoken("authtoken").build();
* Response login = contentstack.login();
*
* Access more other user functions from the userInstance
* </pre>
*
* <br>
* <b>OR</b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().build();
* Response login = contentstack.login("emailId", "password");
* </pre>
*
* <br>
*
* @param emailId the email id of the user
* @param password the password of the user
* @return LoginDetails
* @throws IOException the IOException
* @author ***REMOVED***
* @see <a href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#users">User
* </a>
*/
public Response<LoginDetails> login(String emailId, String password) throws IOException {
if (this.authtoken != null)
throw new IllegalStateException(Util.USER_ALREADY_LOGGED_IN);
user = new User(this.instance);
Response<LoginDetails> response = user.login(emailId, password).execute();
setupLoginCredentials(response);
return response;
}
/**
* <b>[Note]:</b> Before executing any calls, retrieve the authtoken by
* authenticating yourself via the Log in call of User Session. The authtoken is
* returned to the 'Response' body of
* the Log in call and is mandatory in all the calls.
* <p>
* <b>Example:</b>
* <p>
* All accounts registered with Contentstack are known as Users. A stack can
* have many users with varying
* permissions and roles
* <p>
* To perform User operations first get User instance like below.
* <p>
* <b>Example:</b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().setAuthtoken("authtoken").build();
* Response login = contentstack.login();
*
* Access more other user functions from the userInstance
* </pre>
*
* <br>
* <b>OR: </b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().build();
* Response login = contentstack.login("emailId", "password");
* </pre>
*
* <br>
*
* @param emailId the email id
* @param password the password
* @param tfaToken the tfa token
* @return LoginDetails
* @throws IOException the io exception
* @throws IOException the IOException
* @author ***REMOVED***
* @see <a
* href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#log-in-to-your-account">Login
* your account
* </a>
*/
public Response<LoginDetails> login(String emailId, String password, String tfaToken) throws IOException {
if (this.authtoken != null)
throw new IllegalStateException(Util.USER_ALREADY_LOGGED_IN);
user = new User(this.instance);
Response<LoginDetails> response = user.login(emailId, password, tfaToken).execute();
setupLoginCredentials(response);
user = new User(this.instance);
return response;
}
private void setupLoginCredentials(Response<LoginDetails> loginResponse) throws IOException {
if (loginResponse.isSuccessful()) {
assert loginResponse.body() != null;
// logger.info(loginResponse.body().getNotice());
this.authtoken = loginResponse.body().getUser().getAuthtoken();
this.interceptor.setAuthtoken(this.authtoken);
} else {
assert loginResponse.errorBody() != null;
String errorJsonString = loginResponse.errorBody().string();
logger.info(errorJsonString);
new Gson().fromJson(errorJsonString, Error.class);
}
}
/**
* The Log out of your account call is used to sign out the user of Contentstack
* account
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().build();
* User user = contentstack.logout();
* </pre>
* <p>
*
* @return the response
* @throws IOException the io exception
*/
Response<ResponseBody> logout() throws IOException {
user = new User(this.instance);
return user.logoutWithAuthtoken(this.authtoken).execute();
}
/**
* The Log out of your account using authtoken is used to sign out the user of
* Contentstack account
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().build();
* User userInstance = contentstack.logoutWithAuthtoken("authtoken");
* </pre>
* <p>
*
* @param authtoken the authtoken
* @return the response
* @throws IOException the io exception
*/
Response<ResponseBody> logoutWithAuthtoken(String authtoken) throws IOException {
user = new User(this.instance);
this.authtoken = authtoken;
if (authtoken != null) {
return user.logoutWithAuthtoken(authtoken).execute();
}
return logout();
}
/**
* Organization is the top-level entity in the hierarchy of Contentstack,
* consisting of stacks and stack resources,
* and users. Organization allows easy management of projects as well as users
* within the Organization.
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().build();
* Organization org = contentstack.organization();
* </pre>
*
* @return the organization
*/
public Organization organization() {
Objects.requireNonNull(this.authtoken, "Please Login to access user instance");
return new Organization(this.instance);
}
/**
* Organization is the top-level entity in the hierarchy of Contentstack,
* consisting of stacks and stack resources,
* and users. Organization allows easy management of projects as well as users
* within the Organization.
* <p>
* <b> Example </b>
*
* @param organizationUid The UID of the organization that you want to retrieve
* @return the organization
* <br>
* <b>Example</b>
*
* <pre>
* Contentstack contentstack = new Contentstack.Builder().build();
* <br>
* Organization org = contentstack.organization();
* </pre>
*/
public Organization organization(@NotNull String organizationUid) {
Objects.requireNonNull(this.authtoken, "Please Login to access user instance");
if (organizationUid.isEmpty())
throw new IllegalStateException("organizationUid can not be empty");
return new Organization(this.instance, organizationUid);
}
/**
* <a href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#stacks">stack</a>
* A stack is
* a space that stores the content of a project (a web or mobile property).
* Within a stack, you can create content
* structures, content entries, users, etc. related to the project
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack client = new Contentstack.Builder().build();
* Stack org = client.stack();
* </pre>
*
* @return the stack instance
*/
public Stack stack() {
Objects.requireNonNull(this.authtoken, ILLEGAL_USER);
return new Stack(this.instance);
}
/**
* <a href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#stacks">stack</a>
* A stack is
* a space that stores the content of a project (a web or mobile property).
* Within a stack, you can create content
* structures, content entries, users, etc. related to the project
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack client = new Contentstack.Builder().build();
* Stack org = client.stack();
* </pre>
*
* @param header the headers for the stack
* @return the stack instance
*/
public Stack stack(@NotNull Map<String, Object> header) {
if (this.authtoken == null && !header.containsKey(AUTHORIZATION) && header.get(AUTHORIZATION) == null)
throw new IllegalStateException(PLEASE_LOGIN);
return new Stack(this.instance, header);
}
/**
* <a href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#stacks">stack</a>
* A stack is
* a space that stores the content of a project (a web or mobile property).
* Within a stack, you can create content
* structures, content entries, users, etc. related to the project
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack client = new Contentstack.Builder().build();
* Stack org = client.stack();
* </pre>
*
* @param managementToken the authorization for the stack
* @param apiKey the apiKey for the stack
* @return the stack instance
*/
public Stack stack(@NotNull String apiKey, @NotNull String managementToken) {
HashMap<String, Object> headers = new HashMap<>();
headers.put(API_KEY, apiKey);
headers.put(AUTHORIZATION, managementToken);
return new Stack(this.instance, headers);
}
/**
* <a href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#stacks">stack</a>
* A stack is
* a space that stores the content of a project (a web or mobile property).
* Within a stack, you can create content
* structures, content entries, users, etc. related to the project
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack client = new Contentstack.Builder().build();
* Stack org = client.stack();
* </pre>
*
* @param key You can provide apiKey of the stack or branchKey
* @return the stack instance
*/
public Stack stack(@NotNull String key) {
HashMap<String, Object> headers = new HashMap<>();
if (key.startsWith("blt")) {
// When API_Key is available
headers.put(API_KEY, key);
} else {
// When branch is available
headers.put(BRANCH, key);
}
return new Stack(this.instance, headers);
}
/**
* <a href=
* "https://www.contentstack.com/docs/developers/apis/content-management-api/#stacks">stack</a>
* A stack is
* a space that stores the content of a project (a web or mobile property).
* Within a stack, you can create content
* structures, content entries, users, etc. related to the project
* <p>
* <b> Example </b>
*
* <pre>
* Contentstack client = new Contentstack.Builder().build();
* Stack org = client.stack();
* </pre>
*
* @param managementToken the authorization for the stack
* @param apiKey the apiKey for the stack
* @param branch the branch that include branching in the response
* @return the stack instance
*/
public Stack stack(@NotNull String apiKey, @NotNull String managementToken, @NotNull String branch) {
HashMap<String, Object> headers = new HashMap<>();
headers.put(API_KEY, apiKey);
headers.put(AUTHORIZATION, managementToken);
headers.put(BRANCH, branch);
return new Stack(this.instance, headers);
}
/**
* Instantiates a new Contentstack.
*
* @param builder the builder
*/
public Contentstack(Builder builder) {
this.host = builder.hostname;
this.port = builder.port;
this.version = builder.version;
this.timeout = builder.timeout;
this.authtoken = builder.authtoken;
this.instance = builder.instance;
this.retryOnFailure = builder.retry;
this.proxy = builder.proxy;
this.interceptor = builder.authInterceptor;
this.earlyAccess = builder.earlyAccess;
}
/**
* The type Builder.
*/
public static class Builder {
/**
* The Proxy.
*/
protected Proxy proxy;
private AuthInterceptor authInterceptor;
private String authtoken; // authtoken for client
private String[] earlyAccess;
private Retrofit instance; // client instance
private String hostname = Util.HOST; // Default Host for Contentstack API (default: api.contentstack.io)
private String port = Util.PORT; // Default PORT for Contentstack API
private String version = Util.VERSION; // Default Version for Contentstack API
private int timeout = Util.TIMEOUT; // Default timeout 30 seconds
private Boolean retry = Util.RETRY_ON_FAILURE;// Default base url for contentstack
/**
* Default ConnectionPool holds up to 5 idle connections which
* will be evicted after 5 minutes of inactivity.
*/
private ConnectionPool connectionPool = new ConnectionPool(); // Connection
/**
* Instantiates a new Builder.
*/
public Builder() {
// this blank builder constructor
}
/**
* Sets proxy. (Setting proxy to the OkHttpClient) Proxy = new
* Proxy(Proxy.Type.HTTP, new
* InetSocketAddress(proxyHost, proxyPort));
* <br>
* <p>
* {@code
*
* <p>
* Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname", 433));
* Contentstack contentstack = new Contentstack.Builder().setProxy(proxy).build();
*
* <p>
* }
*
* @param proxy the proxy
* @return the Builder instance
*/
public Builder setProxy(@NotNull Proxy proxy) {
this.proxy = proxy;
return this;
}
/**
* Sets retry on failure.
*
* @param retry if retry is true
* @return the retry on failure
*/
public Builder setRetry(@NotNull Boolean retry) {
this.retry = retry;
return this;
}
/**
* Set host for client instance
*
* @param hostname host for the Contentstack Client
* @return Client host
*/
public Builder setHost(@NotNull String hostname) {
this.hostname = hostname;
return this;
}
/**
* Set port for client instance
*
* @param port - port for the Contentstack Client
* @return Client port
*/
public Builder setPort(@NotNull String port) {
this.port = port;
return this;
}
/**
* Set version for client instance
*
* @param version for the Contentstack Client
* @return Client version
*/
public Builder setVersion(@NotNull String version) {
this.version = version;
return this;
}
/**
* Set timeout for client instance
*
* @param timeout for the Contentstack Client
* @return Client timeout
*/
public Builder setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Create a new connection pool with tuning parameters appropriate for a
* single-user application.
* The tuning parameters in this pool are subject to change in future OkHttp
* releases. Currently,
* this pool holds up to 5 idle connections which will be evicted after 5
* minutes of inactivity.
* <p>
* <p>
* public ConnectionPool() {
* this(5, 5, TimeUnit.MINUTES);
* }
*
* @param maxIdleConnections Maximum number of idle connections
* @param keepAliveDuration The Keep Alive Duration
* @param timeUnit A TimeUnit represents time durations at a given
* unit of granularity and provides utility methods to
* convert across units
* @return instance of Builder
* <p>
* Example:
* {@code
* Contentstack cs = new Contentstack.Builder()
* .setAuthtoken(AUTHTOKEN)
* .setConnectionPool(5, 400, TimeUnit.MILLISECONDS)
* .setHost("host")
* .build();
* Connection}
*/
public Builder setConnectionPool(int maxIdleConnections, int keepAliveDuration, TimeUnit timeUnit) {
this.connectionPool = new ConnectionPool(maxIdleConnections, keepAliveDuration, timeUnit);
return this;
}
/**
* Sets authtoken for the client
*
* @param authtoken for the client
* @return Contentstack authtoken
*/
public Builder setAuthtoken(String authtoken) {
this.authtoken = authtoken;
return this;
}
public Builder earlyAccess(String[] earlyAccess) {
this.earlyAccess = earlyAccess;
return this;
}
/**
* Build contentstack.
*
* @return the contentstack
*/
public Contentstack build() {
Contentstack contentstack = new Contentstack(this);
validateClient(contentstack);
return contentstack;
}
private void validateClient(Contentstack contentstack) {
String baseUrl = Util.PROTOCOL + "://" + this.hostname + "/" + version + "/";
this.instance = new Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient(contentstack, this.retry)).build();
contentstack.instance = this.instance;
}
private OkHttpClient httpClient(Contentstack contentstack, Boolean retryOnFailure) {
this.authInterceptor = contentstack.interceptor = new AuthInterceptor();
return new OkHttpClient.Builder()
.connectionPool(this.connectionPool)
.addInterceptor(this.authInterceptor)
.addInterceptor(logger())
.proxy(this.proxy)
.connectTimeout(Duration.ofSeconds(this.timeout))
.retryOnConnectionFailure(retryOnFailure)
.build();
}
private HttpLoggingInterceptor logger() {
return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE);
}
}
}