Skip to content

Commit

Permalink
#36 - use gson instead of string substitution
Browse files Browse the repository at this point in the history
  • Loading branch information
cbellone committed Aug 7, 2015
1 parent bb87a0f commit fb51960
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/main/java/alfio/plugin/mailchimp/MailChimpPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,25 @@
import alfio.plugin.ReservationConfirmationPlugin;
import alfio.plugin.TicketAssignmentPlugin;
import alfio.plugin.WaitingQueueSubscriptionPlugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.lang.reflect.Type;
import java.util.*;

public class MailChimpPlugin implements ReservationConfirmationPlugin, TicketAssignmentPlugin, WaitingQueueSubscriptionPlugin {

private static final String DATA_CENTER = "dataCenter";
private static final String API_KEY = "apiKey";
private static final String LIST_ID = "listId";
private static final String LIST_ADDRESS = "https://%s.api.mailchimp.com/3.0/lists/%s/members/";
private static final String REQUEST_TEMPLATE = "{ \"email_address\": \"%s\", \"status\": \"subscribed\", \"merge_fields\": { \"FNAME\": \"%s\" }, \"language\": \"%s\"}";
public static final String FAILURE_MSG = "cannot add user {email: %s, name:%s, language: %s} to the list (%s)";
private final String id = "alfio.mailchimp";
private final PluginDataStorage pluginDataStorage;
private final OkHttpClient httpClient = new OkHttpClient();
private final Gson gson = new GsonBuilder().create();

public MailChimpPlugin(PluginDataStorageProvider pluginDataStorageProvider) {
this.pluginDataStorage = pluginDataStorageProvider.getDataStorage(id);
Expand Down Expand Up @@ -120,10 +121,15 @@ private void subscribeUser(String email, String name, String language, int event
}

private boolean send(int eventId, String address, String apiKey, String email, String name, String language) {
Map<String, Object> content = new HashMap<>();
content.put("email_address", email);
content.put("status", "subscribed");
content.put("merge_fields", Collections.singletonMap("FNAME", name));
content.put("language", language);
Request request = new Request.Builder()
.url(address)
.header("Authorization", Credentials.basic("api", apiKey))
.post(RequestBody.create(MediaType.parse("application/json"), String.format(REQUEST_TEMPLATE, email, name, language)))
.post(RequestBody.create(MediaType.parse("application/json"), gson.toJson(content, Map.class)))
.build();
try {
Response response = httpClient.newCall(request).execute();
Expand Down

0 comments on commit fb51960

Please sign in to comment.