0
# Core Configuration and Authentication
1
2
Primary entry points and authentication management for Twitter API access.
3
4
## Core Entry Points
5
6
### Twitter Factory Interface
7
8
Main factory interface for creating Twitter API instances.
9
10
```java { .api }
11
interface Twitter {
12
/**
13
* Returns a new Twitter instance with builder pattern configuration
14
*/
15
static TwitterBuilder newBuilder();
16
17
/**
18
* Returns a new Twitter instance with default configuration
19
* Equivalent to newBuilder().build()
20
*/
21
static Twitter getInstance();
22
23
/**
24
* Provides access to Twitter API v1.1 functionality
25
*/
26
TwitterV1 v1();
27
}
28
```
29
30
### Twitter Builder
31
32
Builder pattern for configuring Twitter instances with authentication and settings.
33
34
```java { .api }
35
class TwitterBuilder {
36
/**
37
* Configure OAuth 1.0a consumer credentials
38
*/
39
TwitterBuilder oAuthConsumer(String consumerKey, String consumerSecret);
40
41
/**
42
* Configure OAuth 1.0a access token credentials
43
*/
44
TwitterBuilder oAuthAccessToken(String accessToken, String accessTokenSecret);
45
46
/**
47
* Configure OAuth 2.0 bearer token for application-only authentication
48
*/
49
TwitterBuilder oAuth2AccessToken(String oauth2AccessToken);
50
51
/**
52
* Add connection lifecycle listener for monitoring
53
*/
54
TwitterBuilder connectionLifeCycleListener(ConnectionLifeCycleListener listener);
55
56
/**
57
* Add stream listener for real-time data processing
58
*/
59
TwitterBuilder listener(StreamListener streamListener);
60
61
/**
62
* Add raw stream listener for JSON data processing
63
*/
64
TwitterBuilder listener(RawStreamListener rawStreamListener);
65
66
/**
67
* Configure status event handler
68
*/
69
TwitterBuilder onStatus(Consumer<Status> onStatus);
70
71
/**
72
* Configure exception handler
73
*/
74
TwitterBuilder onException(Consumer<Exception> onException);
75
76
/**
77
* Build configured Twitter instance
78
*/
79
Twitter build();
80
}
81
```
82
83
## Authentication Methods
84
85
### OAuth 1.0a (3-legged Authorization)
86
87
Standard OAuth flow for user-authorized access with read/write permissions.
88
89
```java { .api }
90
class OAuthAuthorization implements Authorization {
91
/**
92
* Create new OAuthAuthorization builder
93
*/
94
static OAuthAuthorizationBuilder newBuilder();
95
96
/**
97
* Create OAuthAuthorization with consumer credentials
98
*/
99
static OAuthAuthorization getInstance(String consumerKey, String consumerSecret);
100
101
/**
102
* Create OAuthAuthorization with default configuration
103
*/
104
static OAuthAuthorization getInstance();
105
106
/**
107
* Get OAuth request token to start authorization flow
108
*/
109
RequestToken getOAuthRequestToken() throws TwitterException;
110
111
/**
112
* Get OAuth request token with callback URL
113
*/
114
RequestToken getOAuthRequestToken(String callbackURL) throws TwitterException;
115
116
/**
117
* Get OAuth access token (requires prior authorization)
118
*/
119
AccessToken getOAuthAccessToken() throws TwitterException;
120
121
/**
122
* Get OAuth access token with verifier PIN/code
123
*/
124
AccessToken getOAuthAccessToken(String oauthVerifier) throws TwitterException;
125
126
/**
127
* Get OAuth access token using request token
128
*/
129
AccessToken getOAuthAccessToken(RequestToken requestToken) throws TwitterException;
130
131
/**
132
* Get OAuth access token using request token and verifier
133
*/
134
AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;
135
136
/**
137
* Check if authorization is enabled
138
*/
139
boolean isEnabled();
140
}
141
142
class AccessToken {
143
/**
144
* Create access token with credentials
145
*/
146
AccessToken(String token, String tokenSecret);
147
148
/**
149
* Get access token string
150
*/
151
String getToken();
152
153
/**
154
* Get access token secret
155
*/
156
String getTokenSecret();
157
158
/**
159
* Get authorized user ID
160
*/
161
long getUserId();
162
163
/**
164
* Get authorized user screen name
165
*/
166
String getScreenName();
167
}
168
169
class RequestToken {
170
/**
171
* Get request token for authorization flow
172
*/
173
String getToken();
174
175
/**
176
* Get request token secret
177
*/
178
String getTokenSecret();
179
180
/**
181
* Get authorization URL for user consent
182
*/
183
String getAuthorizationURL();
184
185
/**
186
* Get authentication URL for user login
187
*/
188
String getAuthenticationURL();
189
}
190
```
191
192
**Usage Examples:**
193
194
```java
195
// Basic OAuth 1.0a with existing tokens
196
Twitter twitter = Twitter.newBuilder()
197
.oAuthConsumer("your_consumer_key", "your_consumer_secret")
198
.oAuthAccessToken("user_access_token", "user_access_token_secret")
199
.build();
200
201
// Access API with full user permissions
202
TwitterV1 v1 = twitter.v1();
203
Status status = v1.tweets().updateStatus("Hello Twitter!");
204
```
205
206
**Complete OAuth 1.0a Authorization Flow:**
207
208
```java
209
// Step 1: Get request token
210
OAuthAuthorization oauth = OAuthAuthorization.getInstance("consumer_key", "consumer_secret");
211
RequestToken requestToken = oauth.getOAuthRequestToken("http://your-app.com/callback");
212
213
// Step 2: Direct user to authorization URL
214
String authUrl = requestToken.getAuthorizationURL();
215
System.out.println("Open this URL and authorize the app: " + authUrl);
216
217
// Step 3: Get access token after user authorization
218
// For PIN-based flow (desktop apps):
219
Scanner scanner = new Scanner(System.in);
220
System.out.print("Enter the PIN: ");
221
String pin = scanner.nextLine();
222
AccessToken accessToken = oauth.getOAuthAccessToken(requestToken, pin);
223
224
// For callback-based flow (web apps):
225
// String oauthVerifier = extractFromCallback(); // Extract from callback URL
226
// AccessToken accessToken = oauth.getOAuthAccessToken(requestToken, oauthVerifier);
227
228
// Step 4: Create Twitter instance with access token
229
Twitter twitter = Twitter.newBuilder()
230
.oAuthConsumer("consumer_key", "consumer_secret")
231
.oAuthAccessToken(accessToken.getToken(), accessToken.getTokenSecret())
232
.build();
233
```
234
235
### OAuth 2.0 (Application-only Authentication)
236
237
Bearer token authentication for read-only access without user context.
238
239
```java { .api }
240
class OAuth2Authorization implements Authorization {
241
/**
242
* Create new OAuth2Authorization builder
243
*/
244
static OAuth2AuthorizationBuilder newBuilder();
245
246
/**
247
* Create OAuth2Authorization with consumer credentials
248
*/
249
static OAuth2Authorization getInstance(String consumerKey, String consumerSecret);
250
251
/**
252
* Get OAuth 2.0 bearer token for application-only authentication
253
*/
254
OAuth2Token getOAuth2Token() throws TwitterException;
255
256
/**
257
* Check if authorization is enabled
258
*/
259
boolean isEnabled();
260
}
261
262
class OAuth2Token {
263
/**
264
* Create OAuth 2.0 token
265
*/
266
OAuth2Token(String tokenType, String accessToken);
267
268
/**
269
* Get token type (typically "bearer")
270
*/
271
String getTokenType();
272
273
/**
274
* Get access token string
275
*/
276
String getAccessToken();
277
}
278
```
279
280
**Usage Examples:**
281
282
```java
283
// Basic OAuth 2.0 with existing bearer token
284
Twitter twitter = Twitter.newBuilder()
285
.oAuth2AccessToken("your_bearer_token")
286
.build();
287
288
// Read-only access (no posting capabilities)
289
TwitterV1 v1 = twitter.v1();
290
QueryResult results = v1.search().search(new Query("Twitter4J"));
291
```
292
293
**Complete OAuth 2.0 Authorization Flow:**
294
295
```java
296
// Step 1: Get OAuth 2.0 bearer token
297
OAuth2Authorization oauth2 = OAuth2Authorization.getInstance("consumer_key", "consumer_secret");
298
OAuth2Token bearerToken = oauth2.getOAuth2Token();
299
300
// Step 2: Create Twitter instance with bearer token
301
Twitter twitter = Twitter.newBuilder()
302
.oAuth2AccessToken(bearerToken.getAccessToken())
303
.build();
304
305
// Step 3: Use for read-only operations
306
TwitterV1 v1 = twitter.v1();
307
QueryResult searchResults = v1.search().search(new Query("machine learning"));
308
ResponseList<Status> timeline = v1.timelines().getUserTimeline("twitter");
309
```
310
311
## Configuration Options
312
313
### Properties File Configuration
314
315
Configure authentication via `twitter4j.properties` file:
316
317
```properties
318
oauth.consumerKey=your_consumer_key
319
oauth.consumerSecret=your_consumer_secret
320
oauth.accessToken=your_access_token
321
oauth.accessTokenSecret=your_access_token_secret
322
323
# Or OAuth 2.0
324
oauth2.tokenType=bearer
325
oauth2.accessToken=your_bearer_token
326
327
# HTTP settings
328
http.connectionTimeout=20000
329
http.readTimeout=120000
330
http.retryCount=3
331
332
# API URLs (usually defaults are fine)
333
restBaseURL=https://api.twitter.com/1.1/
334
streamBaseURL=https://stream.twitter.com/1.1/
335
uploadBaseURL=https://upload.twitter.com/1.1/
336
```
337
338
### Programmatic Configuration
339
340
```java { .api }
341
interface Configuration {
342
/**
343
* Get OAuth consumer key
344
*/
345
String getOAuthConsumerKey();
346
347
/**
348
* Get OAuth consumer secret
349
*/
350
String getOAuthConsumerSecret();
351
352
/**
353
* Get OAuth access token
354
*/
355
String getOAuthAccessToken();
356
357
/**
358
* Get OAuth access token secret
359
*/
360
String getOAuthAccessTokenSecret();
361
362
/**
363
* Get OAuth 2.0 access token
364
*/
365
String getOAuth2AccessToken();
366
367
/**
368
* Get REST API base URL
369
*/
370
String getRestBaseURL();
371
372
/**
373
* Get Streaming API base URL
374
*/
375
String getStreamBaseURL();
376
377
/**
378
* Get HTTP connection timeout in milliseconds
379
*/
380
int getHttpConnectionTimeout();
381
382
/**
383
* Get HTTP read timeout in milliseconds
384
*/
385
int getHttpReadTimeout();
386
}
387
```
388
389
## Error Handling and Monitoring
390
391
### Twitter Exception
392
393
Primary exception type for all Twitter API errors.
394
395
```java { .api }
396
class TwitterException extends Exception {
397
/**
398
* Get Twitter-specific error code
399
*/
400
int getErrorCode();
401
402
/**
403
* Get error message from Twitter API
404
*/
405
String getErrorMessage();
406
407
/**
408
* Get HTTP status code
409
*/
410
int getStatusCode();
411
412
/**
413
* Check if error was caused by network issues
414
*/
415
boolean isCausedByNetworkIssue();
416
417
/**
418
* Check if error message is available
419
*/
420
boolean isErrorMessageAvailable();
421
422
/**
423
* Check if error is due to rate limiting
424
*/
425
boolean exceededRateLimitation();
426
427
/**
428
* Get rate limit status if available
429
*/
430
RateLimitStatus getRateLimitStatus();
431
432
/**
433
* Check if retry after period is specified
434
*/
435
boolean isRetryAfter();
436
437
/**
438
* Get retry after period in seconds
439
*/
440
int getRetryAfter();
441
}
442
```
443
444
### Rate Limiting
445
446
```java { .api }
447
interface RateLimitStatus {
448
/**
449
* Get rate limit for this endpoint
450
*/
451
int getLimit();
452
453
/**
454
* Get remaining calls in current window
455
*/
456
int getRemaining();
457
458
/**
459
* Get reset time as Unix timestamp
460
*/
461
int getResetTimeInSeconds();
462
463
/**
464
* Get seconds until rate limit resets
465
*/
466
int getSecondsUntilReset();
467
}
468
469
interface TwitterResponse {
470
/**
471
* Get rate limit status for this response
472
*/
473
RateLimitStatus getRateLimitStatus();
474
475
/**
476
* Get access level for this response
477
*/
478
int getAccessLevel();
479
}
480
```
481
482
**Usage Example:**
483
484
```java
485
try {
486
ResponseList<Status> timeline = v1.timelines().getHomeTimeline();
487
488
// Check rate limit status
489
RateLimitStatus rateLimit = timeline.getRateLimitStatus();
490
System.out.println("Remaining calls: " + rateLimit.getRemaining());
491
System.out.println("Reset time: " + rateLimit.getResetTimeInSeconds());
492
493
} catch (TwitterException e) {
494
if (e.exceededRateLimitation()) {
495
System.out.println("Rate limit exceeded. Retry after: " + e.getRetryAfter());
496
} else {
497
System.out.println("API Error: " + e.getErrorMessage());
498
}
499
}
500
```
501
502
## Authentication Flow Examples
503
504
### Complete OAuth 1.0a Flow
505
506
```java
507
// Step 1: Get request token
508
Twitter twitter = Twitter.newBuilder()
509
.oAuthConsumer("consumer_key", "consumer_secret")
510
.build();
511
512
RequestToken requestToken = twitter.getOAuthRequestToken();
513
514
// Step 2: Redirect user to authorization URL
515
String authUrl = requestToken.getAuthorizationURL();
516
System.out.println("Visit: " + authUrl);
517
518
// Step 3: Get access token with PIN/verifier
519
Scanner scanner = new Scanner(System.in);
520
System.out.print("Enter PIN: ");
521
String pin = scanner.nextLine();
522
523
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin);
524
525
// Step 4: Configure Twitter instance with access token
526
Twitter authorizedTwitter = Twitter.newBuilder()
527
.oAuthConsumer("consumer_key", "consumer_secret")
528
.oAuthAccessToken(accessToken.getToken(), accessToken.getTokenSecret())
529
.build();
530
```
531
532
### OAuth 2.0 Bearer Token Flow
533
534
```java
535
// Application-only authentication for read-only access
536
Twitter twitter = Twitter.newBuilder()
537
.oAuthConsumer("consumer_key", "consumer_secret")
538
.build();
539
540
// Get bearer token
541
OAuth2Token oauth2Token = twitter.getOAuth2Token();
542
543
// Configure with bearer token
544
Twitter appOnlyTwitter = Twitter.newBuilder()
545
.oAuth2AccessToken(oauth2Token.getAccessToken())
546
.build();
547
```