View Javadoc
1   package com.jsql.view.swing.dialog.translate;
2   
3   import com.jsql.util.ConnectionUtil;
4   import com.jsql.util.I18nUtil;
5   import com.jsql.util.LogLevelUtil;
6   import com.jsql.util.PropertiesUtil;
7   import com.jsql.view.swing.dialog.DialogTranslate;
8   import com.jsql.view.swing.util.MediatorHelper;
9   import org.apache.logging.log4j.LogManager;
10  import org.apache.logging.log4j.Logger;
11  
12  import javax.swing.*;
13  import java.io.IOException;
14  import java.io.StringReader;
15  import java.net.URISyntaxException;
16  import java.nio.charset.StandardCharsets;
17  import java.nio.file.Files;
18  import java.nio.file.Paths;
19  import java.util.Properties;
20  import java.util.regex.Matcher;
21  import java.util.regex.Pattern;
22  
23  public class SwingWorkerGithubLocale extends SwingWorker<Object, Object> {
24      
25      /**
26       * Log4j logger sent to view.
27       */
28      private static final Logger LOGGER = LogManager.getRootLogger();
29      
30      private final Properties propertiesLanguageToTranslate = new Properties();
31      private final OrderedProperties propertiesRoot = new OrderedProperties();
32      private final StringBuilder propertiesToTranslate = new StringBuilder();
33      private final DialogTranslate dialogTranslate;
34      
35      private final ConnectionUtil connectionUtil = MediatorHelper.model().getMediatorUtils().getConnectionUtil();
36      private final PropertiesUtil propertiesUtil = MediatorHelper.model().getMediatorUtils().getPropertiesUtil();
37      
38      private static final String LINE_FEED_ESCAPE = "{@|@}";
39      private static final String LINE_FEED = "\\\\[\n\r]+";
40      
41      public SwingWorkerGithubLocale(DialogTranslate dialogTranslate) {
42          this.dialogTranslate = dialogTranslate;
43      }
44  
45      @Override
46      protected Object doInBackground() throws Exception {
47          
48          Thread.currentThread().setName("SwingWorkerDialogTranslate");
49          
50          this.dialogTranslate.getProgressBarTranslation().setVisible(this.dialogTranslate.getLanguage() != Language.OT);
51          
52          try {
53              this.loadFromGithub();
54          } catch (IOException eGithub) {
55              this.logFileNotFound(eGithub);
56          } finally {
57              this.displayDiff();
58          }
59          
60          return null;
61      }
62  
63      private void displayDiff() {
64          
65          this.propertiesRoot.entrySet()
66              .stream()
67              .filter(key ->
68                  this.dialogTranslate.getLanguage() == Language.OT
69                  || this.propertiesLanguageToTranslate.isEmpty()
70                  || !this.propertiesLanguageToTranslate.containsKey(key.getKey())
71              )
72              .forEach(key -> this.propertiesToTranslate.append(
73                  String.format(
74                      "%n%n%s=%s",
75                      key.getKey(),
76                      key.getValue().replace(LINE_FEED_ESCAPE,"\\\n")
77                  )
78              ));
79          
80          this.dialogTranslate.setTextBeforeChange(this.propertiesToTranslate.toString().trim());
81          
82          this.dialogTranslate.getButtonSend().setEnabled(true);
83          this.dialogTranslate.getTextToTranslate().setText(this.dialogTranslate.getTextBeforeChange());
84          this.dialogTranslate.getTextToTranslate().setCaretPosition(0);
85          this.dialogTranslate.getTextToTranslate().setEditable(true);
86          
87          if (this.dialogTranslate.getLanguage() != Language.OT) {
88              
89              int percentTranslated = 100 * this.propertiesLanguageToTranslate.size() / this.propertiesRoot.size();
90              this.dialogTranslate.getProgressBarTranslation().setValue(percentTranslated);
91              this.dialogTranslate.getProgressBarTranslation().setString(
92                  String.format(
93                       "%s%% translated into %s",
94                       percentTranslated,
95                       this.dialogTranslate.getLanguage()
96                  )
97              );
98          }
99      }
100 
101     private void loadFromGithub() throws IOException, URISyntaxException {
102         
103         this.loadRootFromGithub();
104         
105         if (this.dialogTranslate.getLanguage() != Language.OT) {
106             this.loadLanguageFromGithub();
107         } else {
108             LOGGER.log(LogLevelUtil.CONSOLE_INFORM, () -> I18nUtil.valueByKey("LOG_I18N_DEFAULT_LOADED"));
109         }
110     }
111 
112     private void logFileNotFound(IOException eGithub) throws IOException {
113         if (this.propertiesLanguageToTranslate.isEmpty()) {
114             LOGGER.log(LogLevelUtil.CONSOLE_INFORM, "Language file not found, text to translate loaded from local", eGithub);
115         } else if (this.propertiesRoot.isEmpty()) {
116             throw new IOException("Reference language not found");
117         }
118     }
119     
120     private void loadRootFromGithub() throws IOException, URISyntaxException {
121         try {
122             String pageSourceRoot = this.connectionUtil.getSourceLineFeed(
123                 this.propertiesUtil.getProperties().getProperty("github.webservice.i18n.root")
124             );
125             
126             String pageSourceRootFixed = Pattern.compile(LINE_FEED).matcher(Matcher.quoteReplacement(pageSourceRoot)).replaceAll(LINE_FEED_ESCAPE);
127             
128             this.propertiesRoot.load(new StringReader(pageSourceRootFixed));
129             
130             LOGGER.log(LogLevelUtil.CONSOLE_INFORM, () -> I18nUtil.valueByKey("LOG_I18N_ROOT_LOADED"));
131             
132         } catch (IOException e) {
133             
134             var uri = ClassLoader.getSystemResource("i18n/jsql.properties").toURI();
135             var path = Paths.get(uri);
136             byte[] root = Files.readAllBytes(path);
137             var rootI18n = new String(root, StandardCharsets.UTF_8);
138             String rootI18nFixed = Pattern.compile(LINE_FEED).matcher(Matcher.quoteReplacement(rootI18n)).replaceAll(LINE_FEED_ESCAPE);
139             
140             this.propertiesRoot.load(new StringReader(rootI18nFixed));
141             LOGGER.log(LogLevelUtil.CONSOLE_INFORM, "Reference language loaded from local");
142             
143             LOGGER.log(LogLevelUtil.IGNORE, e);
144         }
145     }
146     
147     private void loadLanguageFromGithub() throws IOException, URISyntaxException {
148         try {
149             String pageSourceLanguage = this.connectionUtil.getSourceLineFeed(
150                 String.format(
151                     "%sjsql_%s.properties",
152                     this.propertiesUtil.getProperties().getProperty("github.webservice.i18n.locale"),
153                     this.dialogTranslate.getLanguage().getLabelLocale()
154                 )
155             );
156             
157             this.propertiesLanguageToTranslate.load(new StringReader(pageSourceLanguage));
158             
159             LOGGER.log(
160                 LogLevelUtil.CONSOLE_INFORM,
161                 "{} {}",
162                 () -> I18nUtil.valueByKey("LOG_I18N_TEXT_LOADED"),
163                 this.dialogTranslate::getLanguage
164             );
165         } catch (IOException e) {
166             
167             var uri = ClassLoader.getSystemResource(String.format(
168                     "i18n/jsql_%s.properties",
169                     this.dialogTranslate.getLanguage().getLabelLocale()
170                 ))
171                 .toURI();
172             
173             var path = Paths.get(uri);
174             byte[] root = Files.readAllBytes(path);
175             var localeI18n = new String(root, StandardCharsets.UTF_8);
176             String localeI18nFixed = Pattern.compile(LINE_FEED).matcher(localeI18n).replaceAll(LINE_FEED_ESCAPE);
177             
178             this.propertiesLanguageToTranslate.load(new StringReader(localeI18nFixed));
179             LOGGER.log(
180                 LogLevelUtil.CONSOLE_INFORM,
181                 String.format(
182                     "%s translation loaded from local",
183                     this.dialogTranslate.getLanguage()
184                 )
185             );
186             
187             LOGGER.log(LogLevelUtil.IGNORE, e);
188         }
189     }
190 }