From 5a9811c3771d92832c9bba718b5ec935844978e8 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Sat, 2 Jun 2018 14:17:51 +1200 Subject: Remove async HTTP client dependency --- src/org/traccar/Context.java | 36 ++++++------ src/org/traccar/WebDataHandler.java | 23 ++------ src/org/traccar/database/StatisticsManager.java | 37 ++++++------ src/org/traccar/geocoder/JsonGeocoder.java | 67 +++++++++------------- .../geolocation/OpenCellIdGeolocationProvider.java | 31 ++++------ .../geolocation/UniversalGeolocationProvider.java | 60 +++++++------------ .../geolocation/UnwiredGeolocationProvider.java | 61 +++++++------------- src/org/traccar/notification/EventForwarder.java | 59 +++++++------------ .../notification/JsonTypeEventForwarder.java | 12 ++-- .../notification/MultiPartEventForwarder.java | 47 --------------- 10 files changed, 152 insertions(+), 281 deletions(-) delete mode 100644 src/org/traccar/notification/MultiPartEventForwarder.java (limited to 'src/org/traccar') diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 23d0a983e..7224fd742 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -17,13 +17,14 @@ package org.traccar; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import com.ning.http.client.AsyncHttpClient; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Properties; -import com.ning.http.client.AsyncHttpClientConfigDefaults; +import com.fasterxml.jackson.datatype.jsr353.JSR353Module; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import org.apache.velocity.app.VelocityEngine; import org.eclipse.jetty.util.URIUtil; import org.traccar.database.CalendarManager; @@ -76,11 +77,13 @@ import org.traccar.geolocation.MozillaGeolocationProvider; import org.traccar.geolocation.OpenCellIdGeolocationProvider; import org.traccar.notification.EventForwarder; import org.traccar.notification.JsonTypeEventForwarder; -import org.traccar.notification.MultiPartEventForwarder; import org.traccar.reports.model.TripsConfig; import org.traccar.smpp.SmppClient; import org.traccar.web.WebServer; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; + public final class Context { private static final String USER_AGENT = @@ -209,15 +212,10 @@ public final class Context { return velocityEngine; } - private static AsyncHttpClient asyncHttpClient; - - static { - System.setProperty(AsyncHttpClientConfigDefaults.ASYNC_CLIENT + "userAgent", USER_AGENT); - asyncHttpClient = new AsyncHttpClient(); - } + private static Client client = ClientBuilder.newClient(); - public static AsyncHttpClient getAsyncHttpClient() { - return asyncHttpClient; + public static Client getClient() { + return client; } private static EventForwarder eventForwarder; @@ -343,12 +341,18 @@ public final class Context { } objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JSR353Module()); objectMapper.setConfig( objectMapper.getSerializationConfig().without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)); if (Context.getConfig().getBoolean("mapper.prettyPrintedJson")) { objectMapper.enable(SerializationFeature.INDENT_OUTPUT); } + JacksonJsonProvider jsonProvider = + new JacksonJaxbJsonProvider(objectMapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS); + client = ClientBuilder.newClient().register(jsonProvider); + + if (config.hasKey("database.url")) { dataManager = new DataManager(config); } @@ -392,11 +396,7 @@ public final class Context { serverManager = new ServerManager(); if (config.getBoolean("event.forward.enable")) { - if (Context.getConfig().getBoolean("event.forward.payloadAsParamMode")) { - eventForwarder = new MultiPartEventForwarder(); - } else { - eventForwarder = new JsonTypeEventForwarder(); - } + eventForwarder = new JsonTypeEventForwarder(); } attributesManager = new AttributesManager(dataManager); @@ -471,6 +471,10 @@ public final class Context { public static void init(IdentityManager testIdentityManager) { config = new Config(); objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JSR353Module()); + JacksonJsonProvider jsonProvider = + new JacksonJaxbJsonProvider(objectMapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS); + client = ClientBuilder.newClient().register(jsonProvider); identityManager = testIdentityManager; } diff --git a/src/org/traccar/WebDataHandler.java b/src/org/traccar/WebDataHandler.java index cdd9d0c11..79221de9a 100644 --- a/src/org/traccar/WebDataHandler.java +++ b/src/org/traccar/WebDataHandler.java @@ -16,12 +16,12 @@ package org.traccar; import com.fasterxml.jackson.core.JsonProcessingException; -import com.ning.http.client.AsyncHttpClient; import org.traccar.helper.Checksum; import org.traccar.helper.Log; import org.traccar.model.Device; import org.traccar.model.Position; +import javax.ws.rs.client.Entity; import java.util.HashMap; import java.util.Map; import java.io.UnsupportedEncodingException; @@ -129,21 +129,14 @@ public class WebDataHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { if (json) { - AsyncHttpClient.BoundRequestBuilder requestBuilder = Context.getAsyncHttpClient().preparePost(url); - requestBuilder.setBodyEncoding(StandardCharsets.UTF_8.name()); - - requestBuilder.addHeader("Content-Type", "application/json; charset=utf-8"); - - requestBuilder.setBody(prepareJsonPayload(position)); - requestBuilder.execute(); - + Context.getClient().target(url).request().async().post(Entity.json(prepareJsonPayload(position))); } else { - Context.getAsyncHttpClient().prepareGet(formatRequest(position)).execute(); + Context.getClient().target(formatRequest(position)).request().async().get(); } return position; } - protected String prepareJsonPayload(Position position) { + protected Map prepareJsonPayload(Position position) { Map data = new HashMap<>(); Device device = Context.getIdentityManager().getById(position.getDeviceId()); @@ -154,11 +147,7 @@ public class WebDataHandler extends BaseDataHandler { data.put(KEY_DEVICE, device); } - try { - return Context.getObjectMapper().writeValueAsString(data); - } catch (JsonProcessingException e) { - Log.warning(e); - return null; - } + return data; } + } diff --git a/src/org/traccar/database/StatisticsManager.java b/src/org/traccar/database/StatisticsManager.java index 9a3ff06bd..452cdffa0 100644 --- a/src/org/traccar/database/StatisticsManager.java +++ b/src/org/traccar/database/StatisticsManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 - 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2016 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,13 @@ */ package org.traccar.database; -import com.ning.http.client.Request; -import com.ning.http.client.RequestBuilder; import org.joda.time.format.ISODateTimeFormat; import org.traccar.Context; import org.traccar.helper.Log; import org.traccar.model.Statistics; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Form; import java.sql.SQLException; import java.util.Calendar; import java.util.Date; @@ -70,22 +70,21 @@ public class StatisticsManager { String url = Context.getConfig().getString("server.statistics"); if (url != null) { String time = ISODateTimeFormat.dateTime().print(statistics.getCaptureTime().getTime()); - Request request = new RequestBuilder("POST") - .setUrl(url) - .addHeader("Content-Type", "application/x-www-form-urlencoded") - .addFormParam("version", Log.getAppVersion()) - .addFormParam("captureTime", time) - .addFormParam("activeUsers", String.valueOf(statistics.getActiveUsers())) - .addFormParam("activeDevices", String.valueOf(statistics.getActiveDevices())) - .addFormParam("requests", String.valueOf(statistics.getRequests())) - .addFormParam("messagesReceived", String.valueOf(statistics.getMessagesReceived())) - .addFormParam("messagesStored", String.valueOf(statistics.getMessagesStored())) - .addFormParam("mailSent", String.valueOf(statistics.getMailSent())) - .addFormParam("smsSent", String.valueOf(statistics.getSmsSent())) - .addFormParam("geocoderRequests", String.valueOf(statistics.getGeocoderRequests())) - .addFormParam("geolocationRequests", String.valueOf(statistics.getGeolocationRequests())) - .build(); - Context.getAsyncHttpClient().prepareRequest(request).execute(); + + Form form = new Form(); + form.param("version", Log.getAppVersion()); + form.param("captureTime", time); + form.param("activeUsers", String.valueOf(statistics.getActiveUsers())); + form.param("activeDevices", String.valueOf(statistics.getActiveDevices())); + form.param("requests", String.valueOf(statistics.getRequests())); + form.param("messagesReceived", String.valueOf(statistics.getMessagesReceived())); + form.param("messagesStored", String.valueOf(statistics.getMessagesStored())); + form.param("mailSent", String.valueOf(statistics.getMailSent())); + form.param("smsSent", String.valueOf(statistics.getSmsSent())); + form.param("geocoderRequests", String.valueOf(statistics.getGeocoderRequests())); + form.param("geolocationRequests", String.valueOf(statistics.getGeolocationRequests())); + + Context.getClient().target(url).request().async().post(Entity.form(form)); } users.clear(); diff --git a/src/org/traccar/geocoder/JsonGeocoder.java b/src/org/traccar/geocoder/JsonGeocoder.java index 82a6ee604..e06663689 100644 --- a/src/org/traccar/geocoder/JsonGeocoder.java +++ b/src/org/traccar/geocoder/JsonGeocoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 - 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2015 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,21 +15,16 @@ */ package org.traccar.geocoder; -import com.ning.http.client.AsyncCompletionHandler; -import com.ning.http.client.Response; import org.traccar.Context; import org.traccar.helper.Log; -import javax.json.Json; import javax.json.JsonObject; -import javax.json.JsonReader; - -import java.io.IOException; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.InvocationCallback; import java.util.AbstractMap; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import java.util.concurrent.ExecutionException; public abstract class JsonGeocoder implements Geocoder { @@ -51,25 +46,24 @@ public abstract class JsonGeocoder implements Geocoder { } } - private String handleResponse(double latitude, double longitude, Response response, - ReverseGeocoderCallback callback) throws IOException { - try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) { - Address address = parseAddress(reader.readObject()); - if (address != null) { - String formattedAddress = addressFormat.format(address); - if (cache != null) { - cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress); - } - if (callback != null) { - callback.onSuccess(formattedAddress); - } - return formattedAddress; - } else { - if (callback != null) { - callback.onFailure(new GeocoderException("Empty address")); - } - Log.warning("Empty address"); + private String handleResponse( + double latitude, double longitude, JsonObject json, ReverseGeocoderCallback callback) { + + Address address = parseAddress(json); + if (address != null) { + String formattedAddress = addressFormat.format(address); + if (cache != null) { + cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress); + } + if (callback != null) { + callback.onSuccess(formattedAddress); + } + return formattedAddress; + } else { + if (callback != null) { + callback.onFailure(new GeocoderException("Empty address")); } + Log.warning("Empty address"); } return null; } @@ -88,27 +82,22 @@ public abstract class JsonGeocoder implements Geocoder { } } + Invocation.Builder request = Context.getClient().target(String.format(url, latitude, longitude)).request(); + if (callback != null) { - Context.getAsyncHttpClient().prepareGet(String.format(url, latitude, longitude)) - .execute(new AsyncCompletionHandler() { + request.async().get(new InvocationCallback() { @Override - public Object onCompleted(Response response) throws Exception { - return handleResponse(latitude, longitude, response, callback); + public void completed(JsonObject json) { + callback.onSuccess(handleResponse(latitude, longitude, json, callback)); } @Override - public void onThrowable(Throwable t) { - callback.onFailure(t); + public void failed(Throwable throwable) { + callback.onFailure(throwable); } }); } else { - try { - Response response = Context.getAsyncHttpClient() - .prepareGet(String.format(url, latitude, longitude)).execute().get(); - return handleResponse(latitude, longitude, response, null); - } catch (InterruptedException | ExecutionException | IOException error) { - Log.warning("Geocoding failed", error); - } + return handleResponse(latitude, longitude, request.get(JsonObject.class), null); } return null; } diff --git a/src/org/traccar/geolocation/OpenCellIdGeolocationProvider.java b/src/org/traccar/geolocation/OpenCellIdGeolocationProvider.java index d6e45b550..768aaf6a2 100644 --- a/src/org/traccar/geolocation/OpenCellIdGeolocationProvider.java +++ b/src/org/traccar/geolocation/OpenCellIdGeolocationProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 Anton Tananaev (anton@traccar.org) + * Copyright 2015 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,15 +15,12 @@ */ package org.traccar.geolocation; -import com.ning.http.client.AsyncCompletionHandler; -import com.ning.http.client.Response; import org.traccar.Context; import org.traccar.model.CellTower; import org.traccar.model.Network; -import javax.json.Json; import javax.json.JsonObject; -import javax.json.JsonReader; +import javax.ws.rs.client.InvocationCallback; public class OpenCellIdGeolocationProvider implements GeolocationProvider { @@ -45,25 +42,21 @@ public class OpenCellIdGeolocationProvider implements GeolocationProvider { String request = String.format(url, cellTower.getMobileCountryCode(), cellTower.getMobileNetworkCode(), cellTower.getLocationAreaCode(), cellTower.getCellId()); - Context.getAsyncHttpClient().prepareGet(request).execute(new AsyncCompletionHandler() { + Context.getClient().target(request).request().async().get(new InvocationCallback() { @Override - public Object onCompleted(Response response) throws Exception { - try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) { - JsonObject json = reader.readObject(); - if (json.containsKey("lat") && json.containsKey("lon")) { - callback.onSuccess( - json.getJsonNumber("lat").doubleValue(), - json.getJsonNumber("lon").doubleValue(), 0); - } else { - callback.onFailure(new GeolocationException("Coordinates are missing")); - } + public void completed(JsonObject json) { + if (json.containsKey("lat") && json.containsKey("lon")) { + callback.onSuccess( + json.getJsonNumber("lat").doubleValue(), + json.getJsonNumber("lon").doubleValue(), 0); + } else { + callback.onFailure(new GeolocationException("Coordinates are missing")); } - return null; } @Override - public void onThrowable(Throwable t) { - callback.onFailure(t); + public void failed(Throwable throwable) { + callback.onFailure(throwable); } }); diff --git a/src/org/traccar/geolocation/UniversalGeolocationProvider.java b/src/org/traccar/geolocation/UniversalGeolocationProvider.java index 6416b2633..f71620d8a 100644 --- a/src/org/traccar/geolocation/UniversalGeolocationProvider.java +++ b/src/org/traccar/geolocation/UniversalGeolocationProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Anton Tananaev (anton@traccar.org) + * Copyright 2016 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,17 +15,13 @@ */ package org.traccar.geolocation; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.ning.http.client.AsyncCompletionHandler; -import com.ning.http.client.Response; import org.traccar.Context; import org.traccar.model.Network; -import javax.json.Json; import javax.json.JsonObject; -import javax.json.JsonReader; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; +import javax.ws.rs.client.AsyncInvoker; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.InvocationCallback; public class UniversalGeolocationProvider implements GeolocationProvider { @@ -37,38 +33,26 @@ public class UniversalGeolocationProvider implements GeolocationProvider { @Override public void getLocation(Network network, final LocationProviderCallback callback) { - try { - String request = Context.getObjectMapper().writeValueAsString(network); - Context.getAsyncHttpClient().preparePost(url) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(request.length())) - .setBody(request).execute(new AsyncCompletionHandler() { - @Override - public Object onCompleted(Response response) throws Exception { - try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) { - JsonObject json = reader.readObject(); - if (json.containsKey("error")) { - callback.onFailure( - new GeolocationException(json.getJsonObject("error").getString("message"))); - } else { - JsonObject location = json.getJsonObject("location"); - callback.onSuccess( - location.getJsonNumber("lat").doubleValue(), - location.getJsonNumber("lng").doubleValue(), - json.getJsonNumber("accuracy").doubleValue()); - } - } - return null; + AsyncInvoker invoker = Context.getClient().target(url).request().async(); + invoker.post(Entity.json(network), new InvocationCallback() { + @Override + public void completed(JsonObject json) { + if (json.containsKey("error")) { + callback.onFailure(new GeolocationException(json.getJsonObject("error").getString("message"))); + } else { + JsonObject location = json.getJsonObject("location"); + callback.onSuccess( + location.getJsonNumber("lat").doubleValue(), + location.getJsonNumber("lng").doubleValue(), + json.getJsonNumber("accuracy").doubleValue()); } + } - @Override - public void onThrowable(Throwable t) { - callback.onFailure(t); - } - }); - } catch (JsonProcessingException e) { - callback.onFailure(e); - } + @Override + public void failed(Throwable throwable) { + callback.onFailure(throwable); + } + }); } } diff --git a/src/org/traccar/geolocation/UnwiredGeolocationProvider.java b/src/org/traccar/geolocation/UnwiredGeolocationProvider.java index dcc5a4e7a..963bcb688 100644 --- a/src/org/traccar/geolocation/UnwiredGeolocationProvider.java +++ b/src/org/traccar/geolocation/UnwiredGeolocationProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,21 +17,16 @@ package org.traccar.geolocation; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.ning.http.client.AsyncCompletionHandler; -import com.ning.http.client.Response; import org.traccar.Context; import org.traccar.model.CellTower; import org.traccar.model.Network; import org.traccar.model.WifiAccessPoint; -import javax.json.Json; import javax.json.JsonObject; -import javax.json.JsonReader; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.InvocationCallback; import java.util.Collection; public class UnwiredGeolocationProvider implements GeolocationProvider { @@ -90,39 +85,27 @@ public class UnwiredGeolocationProvider implements GeolocationProvider { @Override public void getLocation(Network network, final LocationProviderCallback callback) { - try { - ObjectNode json = objectMapper.valueToTree(network); - json.put("token", key); - String request = objectMapper.writeValueAsString(json); - Context.getAsyncHttpClient().preparePost(url) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(request.length())) - .setBody(request).execute(new AsyncCompletionHandler() { - @Override - public Object onCompleted(Response response) throws Exception { - try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) { - JsonObject json = reader.readObject(); - if (json.getString("status").equals("error")) { - callback.onFailure( - new GeolocationException(json.getString("message"))); - } else { - callback.onSuccess( - json.getJsonNumber("lat").doubleValue(), - json.getJsonNumber("lon").doubleValue(), - json.getJsonNumber("accuracy").doubleValue()); - } - } - return null; - } + ObjectNode json = objectMapper.valueToTree(network); + json.put("token", key); - @Override - public void onThrowable(Throwable t) { - callback.onFailure(t); + Context.getClient().target(url).request().async().post(Entity.json(json), new InvocationCallback() { + @Override + public void completed(JsonObject json) { + if (json.getString("status").equals("error")) { + callback.onFailure(new GeolocationException(json.getString("message"))); + } else { + callback.onSuccess( + json.getJsonNumber("lat").doubleValue(), + json.getJsonNumber("lon").doubleValue(), + json.getJsonNumber("accuracy").doubleValue()); } - }); - } catch (JsonProcessingException e) { - callback.onFailure(e); - } + } + + @Override + public void failed(Throwable throwable) { + callback.onFailure(throwable); + } + }); } } diff --git a/src/org/traccar/notification/EventForwarder.java b/src/org/traccar/notification/EventForwarder.java index 9d2181e21..b8990d84f 100644 --- a/src/org/traccar/notification/EventForwarder.java +++ b/src/org/traccar/notification/EventForwarder.java @@ -15,26 +15,21 @@ */ package org.traccar.notification; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder; -import java.util.Collections; -import java.util.List; - +import org.apache.commons.collections4.MultiValuedMap; +import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import org.traccar.Context; -import org.traccar.helper.Log; import org.traccar.model.Device; import org.traccar.model.Event; import org.traccar.model.Geofence; import org.traccar.model.Maintenance; import org.traccar.model.Position; -import java.nio.charset.StandardCharsets; +import javax.ws.rs.client.AsyncInvoker; +import javax.ws.rs.client.Invocation; import java.util.HashMap; import java.util.Map; import java.util.Set; -import com.ning.http.client.FluentCaseInsensitiveStringsMap; - public abstract class EventForwarder { private final String url; @@ -54,37 +49,29 @@ public abstract class EventForwarder { public final void forwardEvent(Event event, Position position, Set users) { - BoundRequestBuilder requestBuilder = Context.getAsyncHttpClient().preparePost(url); - requestBuilder.setBodyEncoding(StandardCharsets.UTF_8.name()); - - requestBuilder.addHeader("Content-Type", getContentType()); + Invocation.Builder requestBuilder = Context.getClient().target(url).request(); if (header != null && !header.isEmpty()) { - FluentCaseInsensitiveStringsMap params = new FluentCaseInsensitiveStringsMap(); - params.putAll(splitIntoKeyValues(header, ":")); - requestBuilder.setHeaders(params); + for (Map.Entry entry : splitKeyValues(header, ":").entries()) { + requestBuilder = requestBuilder.header(entry.getKey(), entry.getValue()); + } } - setContent(event, position, users, requestBuilder); - requestBuilder.execute(); + executeRequest(event, position, users, requestBuilder.async()); } - protected Map> splitIntoKeyValues(String params, String separator) { - - String[] splitedLine; - Map> paramsMap = new HashMap<>(); - String[] paramsLines = params.split("\\r?\\n"); - - for (String paramLine: paramsLines) { - splitedLine = paramLine.split(separator, 2); - if (splitedLine.length == 2) { - paramsMap.put(splitedLine[0].trim(), Collections.singletonList(splitedLine[1].trim())); + protected MultiValuedMap splitKeyValues(String params, String separator) { + MultiValuedMap data = new ArrayListValuedHashMap<>(); + for (String line: params.split("\\r?\\n")) { + String[] values = line.split(separator, 2); + if (values.length == 2) { + data.put(values[0].trim(), values[1].trim()); } } - return paramsMap; + return data; } - protected String prepareJsonPayload(Event event, Position position, Set users) { + protected Map preparePayload(Event event, Position position, Set users) { Map data = new HashMap<>(); data.put(KEY_EVENT, event); if (position != null) { @@ -107,16 +94,10 @@ public abstract class EventForwarder { } } data.put(KEY_USERS, Context.getUsersManager().getItems(users)); - try { - return Context.getObjectMapper().writeValueAsString(data); - } catch (JsonProcessingException e) { - Log.warning(e); - return null; - } + return data; } - protected abstract String getContentType(); - protected abstract void setContent( - Event event, Position position, Set users, BoundRequestBuilder requestBuilder); + protected abstract void executeRequest( + Event event, Position position, Set users, AsyncInvoker invoker); } diff --git a/src/org/traccar/notification/JsonTypeEventForwarder.java b/src/org/traccar/notification/JsonTypeEventForwarder.java index 27ef61af1..fcafb964a 100644 --- a/src/org/traccar/notification/JsonTypeEventForwarder.java +++ b/src/org/traccar/notification/JsonTypeEventForwarder.java @@ -5,18 +5,14 @@ import java.util.Set; import org.traccar.model.Event; import org.traccar.model.Position; -import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder; +import javax.ws.rs.client.AsyncInvoker; +import javax.ws.rs.client.Entity; public class JsonTypeEventForwarder extends EventForwarder { @Override - protected String getContentType() { - return "application/json; charset=utf-8"; - } - - @Override - protected void setContent(Event event, Position position, Set users, BoundRequestBuilder requestBuilder) { - requestBuilder.setBody(prepareJsonPayload(event, position, users)); + protected void executeRequest(Event event, Position position, Set users, AsyncInvoker invoker) { + invoker.post(Entity.json(preparePayload(event, position, users))); } } diff --git a/src/org/traccar/notification/MultiPartEventForwarder.java b/src/org/traccar/notification/MultiPartEventForwarder.java deleted file mode 100644 index 6227c66cc..000000000 --- a/src/org/traccar/notification/MultiPartEventForwarder.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.traccar.notification; - -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; - -import org.traccar.Context; -import org.traccar.model.Event; -import org.traccar.model.Position; - -import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder; -import com.ning.http.client.multipart.StringPart; - -public class MultiPartEventForwarder extends EventForwarder { - - private final String payloadParamName; - private final String additionalParams; - - public MultiPartEventForwarder() { - payloadParamName = Context.getConfig().getString("event.forward.paramMode.payloadParamName", "payload"); - additionalParams = Context.getConfig().getString("event.forward.paramMode.additionalParams"); - } - - @Override - protected String getContentType() { - return "multipart/form-data"; - } - - @Override - protected void setContent(Event event, Position position, Set users, BoundRequestBuilder requestBuilder) { - - if (additionalParams != null && !additionalParams.isEmpty()) { - Map> paramsToAdd = splitIntoKeyValues(additionalParams, "="); - - for (Entry> param : paramsToAdd.entrySet()) { - for (String singleParamValue : param.getValue()) { - requestBuilder.addBodyPart(new StringPart(param.getKey(), singleParamValue, null, - StandardCharsets.UTF_8)); - } - } - } - requestBuilder.addBodyPart(new StringPart(payloadParamName, - prepareJsonPayload(event, position, users), "application/json", StandardCharsets.UTF_8)); - } -} -- cgit v1.2.3