Skip to content

Instantly share code, notes, and snippets.

@agustinprosperi
Created August 8, 2024 10:49
Show Gist options
  • Save agustinprosperi/8e0b3049d4c3990c25069ee08c94ecdc to your computer and use it in GitHub Desktop.
Save agustinprosperi/8e0b3049d4c3990c25069ee08c94ecdc to your computer and use it in GitHub Desktop.
Ednpoint para obtener traducciones de un archivo en formato JSON para otro properties
@CrossOrigin
@RestController
@RequestMapping("/api/example")
public class Exampleresource {
@GetMapping(path = "/translate", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> translate() {
// String result = "Ok";
String file1Path = "src/main/resources/transfile1.txt";
String file2Path = "src/main/resources/transfile2.txt";
LinkedHashMap<String, String> mapFile1 = new LinkedHashMap<>();
Map<String, String> mapFile2 = new HashMap<>();
Gson gson = new Gson();
// Cargar propiedades del primer archivo
try (FileInputStream fis = new FileInputStream(file1Path)) {
byte[] data = fis.readAllBytes();
String json = new String(data, StandardCharsets.UTF_8);
String[] lines = json.split("\\r?\\n");
// Recorrer cada línea
for (String line : lines) {
if (line.contains("=")) {
String[] lineParts = line.split("=");
mapFile1.put(lineParts[0], lineParts[1]);
}
}
} catch (Exception e) {
return ResponseEntityUtil.errorResponse(e.getMessage());
}
// Cargar propiedades del segundo archivo (JSON)
try (FileInputStream fis = new FileInputStream(file2Path)) {
byte[] data = fis.readAllBytes();
String json = new String(data, StandardCharsets.UTF_8);
Type type = new TypeToken<Map<String, String>>(){}.getType();
mapFile2 = gson.fromJson(json, type);
} catch (Exception e) {
return ResponseEntityUtil.errorResponse(e.getMessage());
}
for (Map.Entry<String, String> entry : mapFile1.entrySet()) {
if (mapFile2.containsKey(entry.getValue())) {
mapFile1.put(entry.getKey(), mapFile2.get(entry.getValue()));
}
}
// Guardar los cambios en el primer archivo
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file1Path), StandardCharsets.UTF_8)) {
for (Map.Entry<String, String> entry : mapFile1.entrySet()) {
String line = entry.getKey() + "=" + entry.getValue() + "\n";
writer.write(line);
}
} catch (IOException e) {
return ResponseEntityUtil.errorResponse(e.getMessage());
}
logger.info("Translate ok...");
return ResponseEntityUtil.objectResponse(mapFile1.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment