Skip to content

Commit

Permalink
Adapt for new translations format (#102)
Browse files Browse the repository at this point in the history
* Adapt for new translations format

* Change apiUrl and adapt method for params

* add unit test for params being empty
  • Loading branch information
diegomallada1 authored Oct 31, 2024
1 parent a14f42b commit d9883da
Show file tree
Hide file tree
Showing 5 changed files with 122 additions and 22 deletions.
47 changes: 36 additions & 11 deletions library/src/main/java/com/fidesmo/fdsm/FidesmoApiClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,10 @@
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Map;
import java.text.MessageFormat;

public class FidesmoApiClient {
public static final String APIv2 = "https://api.fidesmo.com/";
public static final String APIv3 = "https://api.fidesmo.com/v3";

public static final String APPS_URL = "apps%s";
public static final String APP_INFO_URL = "apps/%s";
Expand Down Expand Up @@ -95,7 +96,7 @@ public class FidesmoApiClient {

@Deprecated
public FidesmoApiClient() {
this(APIv2, null, null);
this(APIv3, null, null);
}

public FidesmoApiClient(String url, ClientAuthentication authentication, OutputStream apidump) {
Expand All @@ -111,7 +112,7 @@ public FidesmoApiClient(String url, ClientAuthentication authentication, OutputS
}

public FidesmoApiClient(ClientAuthentication authentication, OutputStream apidump) {
this(APIv2, authentication, apidump);
this(APIv3, authentication, apidump);
}

public CloseableHttpResponse get(URI uri) throws IOException {
Expand Down Expand Up @@ -161,11 +162,11 @@ public CloseableHttpResponse transmit(HttpRequestBase request) throws IOExceptio
}

CloseableHttpResponse response = http.execute(request, context);
int responsecode = response.getStatusLine().getStatusCode();
if (responsecode < 200 || responsecode > 299) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode < 200 || responseCode > 299) {
String message = response.getStatusLine() + "\n" + IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
response.close();
throw new HttpResponseException(responsecode, message);
throw new HttpResponseException(responseCode, message);
}
return response;
}
Expand Down Expand Up @@ -193,6 +194,7 @@ public JsonNode rpc(URI uri, JsonNode request) throws IOException {

req.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
req.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
req.setHeader(HttpHeaders.ACCEPT_LANGUAGE, Locale.getDefault().toLanguageTag());

try (CloseableHttpResponse response = transmit(req)) {
if (apidump != null) {
Expand Down Expand Up @@ -245,13 +247,36 @@ public static String lamei18n(JsonNode n) {
// For missing values
if (n == null)
return "";
if (n.size() > 0) {
Map<String, Object> langs = mapper.convertValue(n, new TypeReference<Map<String, Object>>() {
});
Map.Entry<String, Object> first = langs.entrySet().iterator().next();
return langs.getOrDefault(Locale.getDefault().getLanguage(), langs.getOrDefault("en", first.getValue())).toString();
if (!n.isEmpty()) {
boolean isNewFormat = n.has("text");
if (isNewFormat) {
return FidesmoApiClient.buildMessageWithParams(n);
}
else {
Map<String, Object> langs = mapper.convertValue(n, new TypeReference<Map<String, Object>>() {
});
Map.Entry<String, Object> first = langs.entrySet().iterator().next();
return langs.getOrDefault(Locale.getDefault().getLanguage(), langs.getOrDefault("en", first.getValue())).toString();
}
} else {
return n.asText();
}
}


public static String buildMessageWithParams(JsonNode n) {

String text = n.path("text").asText();

JsonNode paramsNode = n.path("params");

// Convert the params array to String[]
String[] params = new String[paramsNode.size()];
for (int i = 0; i < paramsNode.size(); i++) {
params[i] = paramsNode.get(i).asText();
}

MessageFormat mf = new MessageFormat(text.replace("'", "''"));
return mf.format(params);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ public String toString() {
}
}

public static ServiceDeliverySession.DeliveryResult deliverService(final RunnableFuture<DeliveryResult> serviceDelivery) {
public static DeliveryResult deliverService(final RunnableFuture<DeliveryResult> serviceDelivery) {
Thread cleanup = new Thread(() -> {
System.err.println("\nCtrl-C received, cancelling delivery");
serviceDelivery.cancel(true);
Expand All @@ -548,7 +548,7 @@ public static ServiceDeliverySession.DeliveryResult deliverService(final Runnabl
try {
// Run in current thread
serviceDelivery.run();
ServiceDeliverySession.DeliveryResult result = serviceDelivery.get();
DeliveryResult result = serviceDelivery.get();
ran = true;
return result;
} catch (ExecutionException e) {
Expand Down
77 changes: 77 additions & 0 deletions library/src/test/java/com/fidesmo/fdsm/TranslationsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.fidesmo.fdsm;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;

import static org.testng.Assert.assertEquals;

public class TranslationsTest {

// @Test
public void returnMessagesInOldFormat() throws JsonProcessingException {
String jsonString = "{ \"fr\" : \"Connecter votre carte de paiement\",\n" +
" \"it\" : \"Associa carta di pagamento\",\n" +
" \"nl\" : \"Koppel uw betaalkaart\",\n" +
" \"de\" : \"Karte verbinden\",\n" +
" \"ru\" : \"Подключить платежную карту\",\n" +
" \"sv\" : \"Anslut betalkort\",\n" +
" \"en\" : \"Connect payment card\"\n}";

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);

assertEquals(FidesmoApiClient.lamei18n(jsonNode), "Connect payment card");
}
@Test
public void returnMessagesInNewFormatWithParams() throws JsonProcessingException {
String jsonString = "{ \"id\": \"service.statuses.success\", \"text\": \"Congrats! Now you can pay with your {0}\", \"params\": [ \"Ring!\" ] }";

// Parse JSON to JsonNode
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);

assertEquals(FidesmoApiClient.lamei18n(jsonNode), "Congrats! Now you can pay with your Ring!");
}

@Test
public void returnMessagesInNewFormatWithMultipleParams() throws JsonProcessingException {
String jsonString = "{ \"id\": \"service.statuses.success\", \"text\": \"Congrats! Now you can pay with your {0} from {1}\", \"params\": [ \"Ring!\", \"your bank\" ] }";

// Parse JSON to JsonNode
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);

assertEquals(FidesmoApiClient.lamei18n(jsonNode), "Congrats! Now you can pay with your Ring! from your bank");
}

@Test
public void returnMessagesInNewFormatWithApostrophes() throws JsonProcessingException {
String jsonString = "{ \"id\": \"service.statuses.success\", \"text\": \"You're now able to pay with your {0}\", \"params\": [ \"Ring!\"] }";

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);

assertEquals(FidesmoApiClient.lamei18n(jsonNode), "You're now able to pay with your Ring!");
}

@Test
public void returnMessagesInNewFormatWithoutParams() throws JsonProcessingException {
String jsonString = "{ \"id\": \"service.statuses.success\", \"text\": \"Your card has been removed\"}";

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);

assertEquals(FidesmoApiClient.lamei18n(jsonNode), "Your card has been removed");
}
@Test
public void returnMessagesInNewFormatWithEmptyParams() throws JsonProcessingException {
String jsonString = "{ \"id\": \"service.statuses.success\", \"text\": \"Your card has been removed\", \"params\": []}";

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);

assertEquals(FidesmoApiClient.lamei18n(jsonNode), "Your card has been removed");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ protected static void inspectEnvironment(OptionSet args) {

// API URL
try {
String url = new URL(System.getenv().getOrDefault(ENV_FIDESMO_API_URL, FidesmoApiClient.APIv2)).toString();
String url = new URL(System.getenv().getOrDefault(ENV_FIDESMO_API_URL, FidesmoApiClient.APIv3)).toString();
// normalize URL
apiurl = url.endsWith("/") ? url : url + "/";
} catch (MalformedURLException e) {
Expand Down
14 changes: 6 additions & 8 deletions tool/src/main/java/com/fidesmo/fdsm/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -326,9 +326,7 @@ public static void main(String[] argv) {
DeliveryUrl delivery = DeliveryUrl.parse(args.valueOf(OPT_RUN));

if (delivery.isWebSocket()) {
if (fidesmoMetadata.isPresent()) {
fidesmoMetadata.get().selectEmpty(bibo);
}
fidesmoMetadata.ifPresent(fidesmoCard -> fidesmoCard.selectEmpty(bibo));
boolean success = WsClient.execute(new URI(delivery.getService()), bibo, auth).join().isSuccess();
if (!success) {
fail("Fail to run a script");
Expand Down Expand Up @@ -494,15 +492,15 @@ private static List<FidesmoApp> queryApps(FidesmoApiClient client, List<byte[]>
List<FidesmoApp> result = new ArrayList<>();
// Construct list in one go
for (byte[] app : apps) {
JsonNode appdesc = client.rpc(client.getURI(FidesmoApiClient.APP_INFO_URL, HexUtils.bin2hex(app)));
JsonNode appDesc = client.rpc(client.getURI(FidesmoApiClient.APP_INFO_URL, HexUtils.bin2hex(app)));
// Multilanguague
String appID = HexUtils.bin2hex(app);
String appName = FidesmoApiClient.lamei18n(appdesc.get("name"));
String appVendor = FidesmoApiClient.lamei18n(appdesc.get("organization").get("name"));
String appName = FidesmoApiClient.lamei18n(appDesc.get("name"));
String appVendor = FidesmoApiClient.lamei18n(appDesc.get("organization").get("name"));
FidesmoApp fidesmoApp = new FidesmoApp(app, appName, appVendor);
// Fetch services
JsonNode services = client.rpc(client.getURI(FidesmoApiClient.APP_SERVICES_URL, appID));
if (services.size() > 0) {
if (!services.isEmpty()) {
for (JsonNode s : services) {
if (verbose) {
JsonNode service = client.rpc(client.getURI(FidesmoApiClient.SERVICE_URL, appID, s.asText()));
Expand All @@ -523,7 +521,7 @@ private static void printApps(List<FidesmoApp> apps, PrintStream out, boolean ve
out.println("# appId - name and vendor");
for (FidesmoApp app : apps) {
out.println(HexUtils.bin2hex(app.id).toLowerCase() + " - " + app.name + " (by " + app.vendor + ")");
if (app.services.size() > 0) {
if (!app.services.isEmpty()) {
if (verbose) {
for (FidesmoService service : app.services) {
out.println(" " + service.name + " - " + service.description);
Expand Down

0 comments on commit d9883da

Please sign in to comment.