You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

139 lines
5.8 KiB

11 years ago
package org.telegram.services;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.telegram.BuildVars;
import org.telegram.telegrambots.logging.BotLogger;
11 years ago
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
11 years ago
import java.util.ArrayList;
import java.util.List;
11 years ago
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Weather service
* @date 20 of June of 2015
*/
public class DirectionsService {
private static final String LOGTAG = "DIRECTIONSSERVICE";
11 years ago
private static final String BASEURL = "https://maps.googleapis.com/maps/api/directions/json"; ///< Base url for REST
private static final String APIIDEND = "&key=" + BuildVars.DirectionsApiKey;
11 years ago
private static final String PARAMS = "&language=@language@&units=metric";
11 years ago
private static final DateTimeFormatter dateFormaterFromDate = DateTimeFormatter.ofPattern("dd/MM/yyyy"); ///< Date to text formater
private static volatile DirectionsService instance; ///< Instance of this class
/**
* Constructor (private due to singleton pattern)
*/
private DirectionsService() {
}
/**
* Singleton
*
* @return Return the instance of this class
*/
public static DirectionsService getInstance() {
DirectionsService currentInstance;
if (instance == null) {
synchronized (DirectionsService.class) {
if (instance == null) {
instance = new DirectionsService();
}
currentInstance = instance;
}
} else {
currentInstance = instance;
}
return currentInstance;
}
/**
* Fetch the directions
*
* @param origin Origin address
* @param destination Destination address
* @return Destinations
*/
11 years ago
public List<String> getDirections(String origin, String destination, String language) {
11 years ago
final List<String> responseToUser = new ArrayList<>();
11 years ago
try {
11 years ago
String completURL = BASEURL + "?origin=" + getQuery(origin) + "&destination=" +
getQuery(destination) + PARAMS.replace("@language@", language) + APIIDEND;
11 years ago
HttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completURL);
HttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseContent);
if (jsonObject.getString("status").equals("OK")) {
JSONObject route = jsonObject.getJSONArray("routes").getJSONObject(0);
11 years ago
String startOfAddress = LocalisationService.getInstance().getString("directionsInit", language);
String partialResponseToUser = String.format(startOfAddress,
route.getJSONArray("legs").getJSONObject(0).getString("start_address"),
route.getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text"),
route.getJSONArray("legs").getJSONObject(0).getString("end_address"),
route.getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text")
);
11 years ago
responseToUser.add(partialResponseToUser);
11 years ago
responseToUser.addAll(getDirectionsSteps(
route.getJSONArray("legs").getJSONObject(0).getJSONArray("steps"), language));
11 years ago
} else {
11 years ago
responseToUser.add(LocalisationService.getInstance().getString("directionsNotFound", language));
11 years ago
}
11 years ago
} catch (Exception e) {
BotLogger.warn(LOGTAG, e);
11 years ago
responseToUser.add(LocalisationService.getInstance().getString("errorFetchingDirections", language));
11 years ago
}
return responseToUser;
}
private String getQuery(String address) throws UnsupportedEncodingException {
return URLEncoder.encode(address, "UTF-8");
}
11 years ago
private List<String> getDirectionsSteps(JSONArray steps, String language) {
11 years ago
List<String> stepsStringify = new ArrayList<>();
String partialStepsStringify = "";
11 years ago
for (int i = 0; i < steps.length(); i++) {
11 years ago
String step = getDirectionForStep(steps.getJSONObject(i), language);
11 years ago
if (partialStepsStringify.length() > 1000) {
stepsStringify.add(partialStepsStringify);
partialStepsStringify = "";
}
partialStepsStringify += i + ".\t" + step + "\n\n";
}
if (!partialStepsStringify.isEmpty()) {
stepsStringify.add(partialStepsStringify);
11 years ago
}
return stepsStringify;
}
11 years ago
private String getDirectionForStep(JSONObject jsonObject, String language) {
String direction = LocalisationService.getInstance().getString("directionsStep", language);
11 years ago
String htmlIntructions = Jsoup.parse(jsonObject.getString("html_instructions")).text();
String duration = jsonObject.getJSONObject("duration").getString("text");
String distance = jsonObject.getJSONObject("distance").getString("text");
11 years ago
direction = String.format(direction, htmlIntructions, duration, distance);
11 years ago
return direction;
}
}