Skip to content

Commit ba2ecb2

Browse files
committed
some cleanup in tests
1 parent f7b0010 commit ba2ecb2

17 files changed

+439
-209
lines changed

src/main/java/ug/sparkpl/momoapi/MomoApi.java

+22-69
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,13 @@
11
package ug.sparkpl.momoapi;
22

33
import java.io.IOException;
4-
import java.util.UUID;
5-
import java.util.concurrent.TimeUnit;
6-
7-
import ug.sparkpl.momoapi.models.NewUser;
8-
import ug.sparkpl.momoapi.models.User;
9-
import ug.sparkpl.momoapi.network.collections.CollectionsApiService;
10-
import ug.sparkpl.momoapi.utils.DateTimeTypeConverter;
11-
12-
import org.apache.commons.cli.CommandLine;
13-
import org.apache.commons.cli.CommandLineParser;
14-
import org.apache.commons.cli.DefaultParser;
15-
import org.apache.commons.cli.HelpFormatter;
16-
import org.apache.commons.cli.Option;
17-
import org.apache.commons.cli.Options;
18-
import org.apache.commons.cli.ParseException;
19-
import org.joda.time.DateTime;
4+
import java.util.HashMap;
205

21-
import com.google.gson.FieldNamingPolicy;
22-
import com.google.gson.Gson;
23-
import com.google.gson.GsonBuilder;
6+
import ug.sparkpl.momoapi.network.MomoApiException;
7+
import ug.sparkpl.momoapi.network.RequestOptions;
8+
import ug.sparkpl.momoapi.network.collections.CollectionsClient;
249

25-
import okhttp3.OkHttpClient;
26-
import retrofit2.Response;
27-
import retrofit2.Retrofit;
28-
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
29-
import retrofit2.converter.gson.GsonConverterFactory;
10+
import org.apache.commons.cli.ParseException;
3011

3112

3213
public class MomoApi {
@@ -46,54 +27,26 @@ public class MomoApi {
4627
*/
4728
public static void main(String[] args) throws ParseException, IOException {
4829

49-
String baseUrl = "https://ericssonbasicapi2.azure-api.net";
50-
final CollectionsApiService apiService;
51-
Gson gson = new GsonBuilder()
52-
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
53-
.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter())
54-
.create();
55-
56-
57-
final OkHttpClient.Builder okhttpbuilder = new OkHttpClient.Builder();
58-
59-
okhttpbuilder.connectTimeout(30, TimeUnit.SECONDS);
60-
okhttpbuilder.readTimeout(30, TimeUnit.SECONDS);
61-
okhttpbuilder.writeTimeout(30, TimeUnit.SECONDS);
62-
63-
64-
OkHttpClient httpClient = okhttpbuilder
65-
.build();
66-
6730

68-
Retrofit retrofitClient = new Retrofit.Builder()
69-
.client(httpClient)
70-
.baseUrl(baseUrl)
71-
.addConverterFactory(GsonConverterFactory.create(gson))
72-
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
31+
// Make a request to pay call
32+
RequestOptions opts = RequestOptions.builder()
7333
.build();
7434

75-
apiService = retrofitClient.create(CollectionsApiService.class);
76-
77-
CommandLineParser parser = new DefaultParser();
78-
final Options options = new Options();
79-
options.addOption(new Option("h", "providerCallBackHost", true, "providerCallBackHost"));
80-
options.addOption(new Option("k", "primaryKey", true, "Ocp-Apim-Subscription-Key"));
81-
CommandLine cmd = parser.parse(options, args);
82-
83-
84-
HelpFormatter formatter = new HelpFormatter();
85-
formatter.printHelp("MomoApi", options);
86-
87-
String token = UUID.randomUUID().toString();
88-
89-
Response<Void> res = apiService
90-
.provisonUser(cmd.getOptionValue("k"), token, new NewUser(cmd.getOptionValue("h")))
91-
.execute();
92-
93-
Response<User> user = apiService.getUser(token, cmd.getOptionValue("k")).execute();
94-
95-
96-
System.out.print("{'apiKey':" + user.body().getApiKey() + ", 'UserId': " + token + "}");
35+
HashMap<String, String> collMap = new HashMap<String, String>();
36+
collMap.put("amount", "100");
37+
collMap.put("mobile", "0782123456");
38+
collMap.put("externalId", "ext123");
39+
collMap.put("payeeNote", "testNote");
40+
collMap.put("payerMessage", "testMessage");
41+
42+
CollectionsClient client = new CollectionsClient(opts);
43+
44+
try {
45+
String transactionRef = client.requestToPay(collMap);
46+
System.out.println(transactionRef);
47+
} catch (MomoApiException e) {
48+
e.printStackTrace();
49+
}
9750

9851

9952
}

src/main/java/ug/sparkpl/momoapi/network/RequestOptions.java

+9-9
Original file line numberDiff line numberDiff line change
@@ -239,17 +239,17 @@ public static class Builder {
239239
* API version) as default values.
240240
*/
241241
public Builder() {
242-
this.collectionUserId = System.getenv("collectionUserId");
243-
this.collectionApiSecret = System.getenv("collectionApiSecret");
244-
this.collectionPrimaryKey = System.getenv("collectionPrimaryKey");
242+
this.collectionUserId = System.getenv("COLLECTION_USER_ID");
243+
this.collectionApiSecret = System.getenv("COLLECTION_API_SECRET");
244+
this.collectionPrimaryKey = System.getenv("COLLECTION_PRIMARY_KEY");
245245

246-
this.remittancePrimaryKey = System.getenv("remittancePrimaryKey");
247-
this.remittanceUserId = System.getenv("remittanceUserId");
248-
this.remittanceApiSecret = System.getenv("remittanceApiSecret");
246+
this.remittancePrimaryKey = System.getenv("REMITTANCE_PRIMARY_KEY");
247+
this.remittanceUserId = System.getenv("REMITTANCE_USER_ID");
248+
this.remittanceApiSecret = System.getenv("REMITTANCE_API_SECRET");
249249

250-
this.disbursementPrimaryKey = System.getenv("disbursementPrimaryKey");
251-
this.disbursementUserId = System.getenv("disbursementUserId");
252-
this.disbursementApiSecret = System.getenv("disbursementApiSecret");
250+
this.disbursementPrimaryKey = System.getenv("DISBURSEMENT_PRIMARY_KEY");
251+
this.disbursementUserId = System.getenv("DISBURSEMENT_USER_ID");
252+
this.disbursementApiSecret = System.getenv("DISBURSEMENT_API_SECRET");
253253

254254
}
255255

src/main/java/ug/sparkpl/momoapi/network/collections/CollectionsAuthorizationInterceptor.java

+49-35
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33

44
import java.io.IOException;
5+
import java.net.UnknownHostException;
56
import java.util.concurrent.TimeUnit;
67
import java.util.logging.Level;
78
import java.util.logging.Logger;
@@ -61,9 +62,9 @@ public CollectionsAuthorizationInterceptor(CollectionSession session, RequestOpt
6162
okhttpbuilder.addInterceptor(httpLoggingInterceptor);
6263

6364

64-
okhttpbuilder.connectTimeout(30, TimeUnit.SECONDS);
65-
okhttpbuilder.readTimeout(30, TimeUnit.SECONDS);
66-
okhttpbuilder.writeTimeout(30, TimeUnit.SECONDS);
65+
okhttpbuilder.connectTimeout(60, TimeUnit.SECONDS);
66+
okhttpbuilder.readTimeout(60, TimeUnit.SECONDS);
67+
okhttpbuilder.writeTimeout(60, TimeUnit.SECONDS);
6768

6869

6970
OkHttpClient httpClient = okhttpbuilder
@@ -113,52 +114,65 @@ private Request request(final Request initialRequest) {
113114
*/
114115
@Override
115116
public okhttp3.Response intercept(Chain chain) throws IOException {
116-
okhttp3.Response mainResponse = chain.proceed(request(chain.request()));
117-
Request mainRequest = chain.request();
118117

119118

120-
// if response code is 401 or 403, 'mainRequest' has encountered authentication error
121-
if (mainResponse.code() == 401 || mainResponse.code() == 403) {
119+
try {
120+
okhttp3.Response mainResponse = chain.proceed(request(chain.request()));
122121

123122

124-
this.logger.log(Level.INFO, "<<<<<<<<<<<<<<<Getting Fresh Token");
123+
Request mainRequest = chain.request();
125124

126125

127-
String credentials = Credentials.basic(this.opts.getCollectionUserId(),
128-
this.opts.getCollectionApiSecret());
129-
Response<AccessToken> loginResponse = this.apiService
130-
.getToken(credentials, this.opts.getCollectionPrimaryKey()).execute();
126+
// if response code is 401 or 403, 'mainRequest' has encountered authentication error
127+
if (mainResponse.code() == 401 || mainResponse.code() == 403) {
131128

132-
if (loginResponse.isSuccessful()) {
133-
// login request succeed, new token generated
134-
AccessToken token = loginResponse.body();
135-
// save the new token
136-
this.session.saveToken(token.getToken());
137-
// retry the 'mainRequest' which encountered an authentication error
138-
// add new token into 'mainRequest' header and request again
139-
Request.Builder builder = mainRequest.newBuilder().addHeader("Authorization",
140-
"Bearer " + this.session.getToken())
141-
.addHeader("Ocp-Apim-Subscription-Key", this.opts.getCollectionPrimaryKey())
142-
.addHeader("X-Target-Environment", this.opts.getTargetEnvironment())
143-
.method(mainRequest.method(), mainRequest.body());
144-
mainResponse = chain.proceed(builder.build());
145-
}
146-
} else if (!mainResponse.isSuccessful()) {
147129

148-
this.logger.log(Level.INFO, "<<<<<<<<<<<<<<< ETETETET "
149-
+ mainResponse.code() + " .." + mainResponse.body().string());
130+
this.logger.log(Level.INFO, "<<<<<<<<<<<<<<<Getting Fresh Token");
150131

151132

152-
throw new MomoApiException(mainResponse.body().string());
133+
String credentials = Credentials.basic(this.opts.getCollectionUserId(),
134+
this.opts.getCollectionApiSecret());
135+
Response<AccessToken> loginResponse = this.apiService
136+
.getToken(credentials, this.opts.getCollectionPrimaryKey()).execute();
153137

138+
if (loginResponse.isSuccessful()) {
139+
// login request succeed, new token generated
140+
AccessToken token = loginResponse.body();
141+
// save the new token
142+
this.session.saveToken(token.getToken());
143+
// retry the 'mainRequest' which encountered an authentication error
144+
// add new token into 'mainRequest' header and request again
145+
Request.Builder builder = mainRequest.newBuilder().addHeader("Authorization",
146+
"Bearer " + this.session.getToken())
147+
.addHeader("Ocp-Apim-Subscription-Key", this.opts.getCollectionPrimaryKey())
148+
.addHeader("X-Target-Environment", this.opts.getTargetEnvironment())
149+
.method(mainRequest.method(), mainRequest.body());
150+
mainResponse = chain.proceed(builder.build());
151+
}
152+
} else if (mainResponse.code() == 400 || mainResponse.code() == 500 || mainResponse.code() == 404) {
153+
String error = "";
154154

155-
}
155+
try {
156+
error = mainResponse.body().string();
157+
} catch (IllegalStateException e) {
156158

157-
if (this.session.getToken() == "dummy") {
158-
throw new MomoApiException(mainResponse.body().string());
159-
}
159+
}
160+
161+
162+
throw new MomoApiException(error);
163+
164+
165+
}
166+
167+
168+
return mainResponse;
169+
170+
} catch (UnknownHostException exception) {
160171

172+
throw new MomoApiException("There is no internet connection.");
161173

162-
return mainResponse;
174+
175+
}
163176
}
177+
164178
}

src/main/java/ug/sparkpl/momoapi/network/collections/CollectionsClient.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,9 @@ public CollectionsClient(RequestOptions opts) {
6666
okhttpbuilder.addInterceptor(httpLoggingInterceptor);
6767

6868

69-
okhttpbuilder.connectTimeout(30, TimeUnit.SECONDS);
70-
okhttpbuilder.readTimeout(30, TimeUnit.SECONDS);
71-
okhttpbuilder.writeTimeout(30, TimeUnit.SECONDS);
69+
okhttpbuilder.connectTimeout(60, TimeUnit.SECONDS);
70+
okhttpbuilder.readTimeout(60, TimeUnit.SECONDS);
71+
okhttpbuilder.writeTimeout(60, TimeUnit.SECONDS);
7272

7373

7474
this.httpClient = okhttpbuilder
@@ -164,7 +164,7 @@ public String requestToPay(String mobile, String amount, String externalId, Stri
164164
public String requestToPay(HashMap<String, String> opts) throws IOException {
165165
RequestToPay rbody = new RequestToPay(opts.get("mobile"), opts.get("amount"),
166166
opts.get("externalId"), opts.get("payeeNote"), opts.get("payerMessage"),
167-
this.opts.getCurrency());
167+
opts.getOrDefault("currency", this.opts.getCurrency()));
168168
String ref = UUID.randomUUID().toString();
169169
this.apiService.requestToPay(rbody, ref).execute();
170170
return ref;

src/main/java/ug/sparkpl/momoapi/network/disbursements/DisbursementsAuthorizationInterceptor.java

+13-7
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ public DisbursementsAuthorizationInterceptor(DisbursementsSession session, Reque
6161
okhttpbuilder.addInterceptor(httpLoggingInterceptor);
6262

6363

64-
okhttpbuilder.connectTimeout(30, TimeUnit.SECONDS);
65-
okhttpbuilder.readTimeout(30, TimeUnit.SECONDS);
66-
okhttpbuilder.writeTimeout(30, TimeUnit.SECONDS);
64+
okhttpbuilder.connectTimeout(60, TimeUnit.SECONDS);
65+
okhttpbuilder.readTimeout(60, TimeUnit.SECONDS);
66+
okhttpbuilder.writeTimeout(60, TimeUnit.SECONDS);
6767

6868

6969
OkHttpClient httpClient = okhttpbuilder
@@ -142,14 +142,20 @@ public okhttp3.Response intercept(Chain chain) throws IOException {
142142
.addHeader("X-Target-Environment", this.opts.getTargetEnvironment())
143143
.method(mainRequest.method(), mainRequest.body());
144144
mainResponse = chain.proceed(builder.build());
145+
146+
145147
}
146-
} else if (!mainResponse.isSuccessful()) {
148+
} else if (mainResponse.code() == 400 || mainResponse.code() == 500 || mainResponse.code() == 404) {
149+
String error = "";
147150

148-
this.logger.log(Level.INFO, "<<<<<<<<<<<<<<< ETETETET "
149-
+ mainResponse.code() + " .." + mainResponse.body().string());
151+
try {
152+
error = mainResponse.body().string();
153+
} catch (IllegalStateException e) {
154+
155+
}
150156

151157

152-
throw new MomoApiException(mainResponse.body().string());
158+
throw new MomoApiException(error);
153159

154160

155161
}

src/main/java/ug/sparkpl/momoapi/network/disbursements/DisbursementsClient.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ public String transfer(String mobile, String amount,
159159
public String transfer(HashMap<String, String> opts) throws IOException {
160160
Transfer rbody = new Transfer(opts.get("mobile"), opts.get("amount"),
161161
opts.get("externalId"), opts.get("payeeNote"),
162-
opts.get("payerMessage"), this.opts.getCurrency());
162+
opts.get("payerMessage"), opts.getOrDefault("currency", this.opts.getCurrency()));
163163
String ref = UUID.randomUUID().toString();
164164
this.apiService.transfer(rbody, ref).execute();
165165
return ref;

src/main/java/ug/sparkpl/momoapi/network/remittances/RemittancesAuthorizationInterceptor.java

+8-5
Original file line numberDiff line numberDiff line change
@@ -141,17 +141,20 @@ public okhttp3.Response intercept(Chain chain) throws IOException {
141141
.method(mainRequest.method(), mainRequest.body());
142142
mainResponse = chain.proceed(builder.build());
143143
}
144-
} else if (!mainResponse.isSuccessful()) {
144+
} else if (mainResponse.code() == 400 || mainResponse.code() == 500 || mainResponse.code() == 404) {
145+
String error = "";
145146

146-
this.logger.log(Level.INFO, "<<<<<<<<<<<<<<< ETETETET " + mainResponse.code() + " .."
147-
+ mainResponse.body().string());
147+
try {
148+
error = mainResponse.body().string();
149+
} catch (IllegalStateException e) {
148150

151+
}
149152

150-
throw new MomoApiException(mainResponse.body().string());
151153

154+
throw new MomoApiException(error);
152155

153-
}
154156

157+
}
155158

156159
return mainResponse;
157160
}

src/main/java/ug/sparkpl/momoapi/network/remittances/RemittancesClient.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ public String transfer(HashMap<String, String> opts) throws IOException {
164164
Transfer rbody = new Transfer(opts.get("mobile"),
165165
opts.get("amount"), opts.get("externalId"),
166166
opts.get("payeeNote"), opts.get("payerMessage"),
167-
opts.get("currency"));
167+
opts.getOrDefault("currency", this.opts.getCurrency()));
168168
String ref = UUID.randomUUID().toString();
169169
this.apiService.transfer(rbody, ref).execute();
170170
return ref;

0 commit comments

Comments
 (0)