OSDN Git Service

perf: add logger to catch process
[delesterandomselector/DelesteRandomSelector.git] / src / com / ranfa / main / DelesteRandomSelector.java
1 package com.ranfa.main;
2
3 import java.awt.BorderLayout;
4 import java.awt.EventQueue;
5 import java.awt.Font;
6 import java.nio.file.Files;
7 import java.nio.file.Paths;
8 import java.util.ArrayList;
9 import java.util.Random;
10 import java.util.concurrent.CompletableFuture;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
13 import java.util.function.BiConsumer;
14
15 import javax.swing.DefaultComboBoxModel;
16 import javax.swing.JButton;
17 import javax.swing.JCheckBox;
18 import javax.swing.JComboBox;
19 import javax.swing.JFrame;
20 import javax.swing.JLabel;
21 import javax.swing.JOptionPane;
22 import javax.swing.JPanel;
23 import javax.swing.JScrollPane;
24 import javax.swing.JSpinner;
25 import javax.swing.JTextArea;
26 import javax.swing.border.EmptyBorder;
27
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import com.jgoodies.forms.layout.ColumnSpec;
32 import com.jgoodies.forms.layout.FormLayout;
33 import com.jgoodies.forms.layout.FormSpecs;
34 import com.jgoodies.forms.layout.RowSpec;
35 import com.ranfa.lib.CheckVersion;
36 import com.ranfa.lib.EstimateAlbumTypeCycle;
37 import com.ranfa.lib.Scraping;
38 import com.ranfa.lib.SettingJSONProperty;
39 import com.ranfa.lib.Settings;
40 import com.ranfa.lib.Song;
41 import com.ranfa.lib.TwitterIntegration;
42 import com.ranfa.lib.Version;
43
44 @Version(major = 2, minor = 0, patch = 3)
45 public class DelesteRandomSelector extends JFrame {
46
47         private static ArrayList<Song> selectedSongsList = new ArrayList<>();
48
49         private JPanel contentPane;
50         private JPanel panelNorth;
51         private JPanel panelWest;
52         private JLabel labelVersion;
53         private JLabel labelTitle;
54         private JLabel labelDifficulty;
55         private JLabel labelLevel;
56         private JSpinner spinnerLevel;
57         private JCheckBox checkMoreLv;
58         private JCheckBox checkLessLv;
59         private JPanel panelEast;
60         private JPanel panelCentre;
61         private JButton btnImport;
62         private JButton btnStart;
63         private JButton btnExit;
64         private JComboBox comboDifficultySelect;
65         private JLabel labelLvCaution;
66         private JComboBox comboAttribute;
67         private SettingJSONProperty property = new SettingJSONProperty();
68         private JButton btnTwitterIntegration;
69         private String[] integratorArray;
70         private boolean integratorBool = false;
71         private JTextArea textArea;
72         private JScrollPane scrollPane;
73         private CompletableFuture<Void> softwareUpdateFuture = null;
74         private CompletableFuture<Void> albumTypeEstimateFuture = null;
75         private String albumType = Messages.MSGAlbumTypeBeingCalculated.toString();
76         private Logger logger = LoggerFactory.getLogger(DelesteRandomSelector.class);
77
78         /**
79          * Launch the application.
80          */
81         public static void main(String[] args) {
82                 EventQueue.invokeLater(() -> {
83                         try {
84                                 DelesteRandomSelector frame = new DelesteRandomSelector();
85                                 frame.setVisible(true);
86                         } catch (Exception e) {
87                                 e.printStackTrace();
88                         }
89                 });
90         }
91
92         /**
93          * log file prefix:
94          *  this.getClass() + ":[LEVEL]: " +
95          */
96
97         /**
98          * Create the frame.
99          */
100         public DelesteRandomSelector() {
101                 boolean isFirst = !Scraping.databaseExists();
102                 if(isFirst) {
103                         JOptionPane.showMessageDialog(this, Messages.MSGDatabaseNotExist.toString());
104                         if(!Scraping.writeToJson(Scraping.getWholeData())) {
105                                 JOptionPane.showMessageDialog(this, "Exception:NullPointerException\nCannot Keep up! Please re-download this Application!");
106                                 throw new NullPointerException("FATAL: cannot continue!");
107                         }
108                 }
109                 ExecutorService es = Executors.newWorkStealingPool();
110                 CompletableFuture<ArrayList<Song>> getFromJsonFuture = CompletableFuture.supplyAsync(() -> Scraping.getFromJson(), es);
111                 CompletableFuture<ArrayList<Song>> getWholeDataFuture = CompletableFuture.supplyAsync(() -> Scraping.getWholeData(), es);
112                 if(!Settings.fileExists() && !Settings.writeDownJSON()) {
113                         JOptionPane.showMessageDialog(this, "Exception:NullPointerException\nCannot Keep up! Please re-download this Application!");
114                         throw new NullPointerException("FATAL: cannot continue!");
115                 }
116                 this.logger.debug("Loading settings...");
117                 this.property.setCheckLibraryUpdates(Settings.needToCheckLibraryUpdates());
118                 this.property.setCheckVersion(Settings.needToCheckVersion());
119                 this.property.setWindowWidth(Settings.getWindowWidth());
120                 this.property.setWindowHeight(Settings.getWindowHeight());
121                 this.property.setSongLimit(Settings.getSongsLimit());
122                 this.property.setSaveScoreLog(Settings.saveScoreLog());
123                 this.logger.debug("Load settings done.");
124                 this.logger.debug("Version check: {}", this.property.isCheckVersion());
125                 this.logger.debug("Library update check: {}", this.property.isCheckLibraryUpdates());
126                 this.logger.debug("Window Width: {}", this.property.getWindowWidth());
127                 this.logger.debug("Window Height: {}", this.property.getWindowHeight());
128                 this.logger.debug("Song Limit: {}", this.property.getSongLimit());
129                 this.logger.debug("SaveScoreLog: {}", this.property.isSaveScoreLog());
130                 EstimateAlbumTypeCycle.Initialization();
131                 if(Files.exists(Paths.get("generated/albumCycle.json"))) {
132                         this.albumType = EstimateAlbumTypeCycle.getCurrentCycle();
133                 }
134                 if(this.property.isCheckVersion()) {
135                         this.softwareUpdateFuture = CompletableFuture.runAsync(() -> CheckVersion.needToBeUpdated(), es);
136                 }
137                 BiConsumer<ArrayList<Song>, ArrayList<Song>> updateConsumer = (list1, list2) -> {
138                         this.logger.info("Checking database updates...");
139                         if(list1.size() > list2.size()) {
140                                 long time = System.currentTimeMillis();
141                                 this.logger.info("{} Update detected.", (list1.size() - list2.size()));
142                                 Scraping.writeToJson(list1);
143                                 this.logger.info("Update completed in {} ms", (System.currentTimeMillis() - time));
144                                 this.logger.info("Updated database size: {}", list1.size());
145                         } else {
146                                 this.logger.info("database is up-to-date.");
147                         }
148                 };
149                 Runnable setEnabled = () -> {
150                         try {
151                                 Thread.sleep(1000);
152                         } catch (InterruptedException e1) {
153                                 this.logger.error("Thread has been interrupted during waiting cooldown.", e1);
154                         }
155                         this.btnImport.setEnabled(true);
156                         this.btnImport.setText(Messages.MSGNarrowingDownSongs.toString());
157                 };
158                 getWholeDataFuture.thenAcceptAsync(list -> this.logger.info("Scraping data size:" + list.size()), es);
159                 getFromJsonFuture.thenAcceptAsync(list -> this.logger.info("Currently database size:" + list.size()), es);
160                 if(this.property.isCheckLibraryUpdates()) {
161                         CompletableFuture<Void> updatedFuture = getWholeDataFuture.thenAcceptBothAsync(getFromJsonFuture, updateConsumer, es);
162                         updatedFuture.thenRunAsync(setEnabled, es);
163                 }
164                 this.logger.debug("Version: {}", CheckVersion.getVersion());
165                 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
166                 this.setBounds(100, 100, this.property.getWindowWidth(), this.property.getWindowHeight());
167                 // this.setBounds(100, 100, 640, 360);
168                 this.contentPane = new JPanel();
169                 this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
170                 this.setContentPane(this.contentPane);
171                 this.contentPane.setLayout(new BorderLayout(0, 0));
172
173                 this.panelNorth = new JPanel();
174                 this.contentPane.add(this.panelNorth, BorderLayout.NORTH);
175                 this.panelNorth.setLayout(new FormLayout(new ColumnSpec[] {
176                                 ColumnSpec.decode("max(302dlu;default)"),
177                                 FormSpecs.RELATED_GAP_COLSPEC,
178                                 ColumnSpec.decode("40px"),},
179                                 new RowSpec[] {
180                                                 RowSpec.decode("20px"),}));
181
182                 this.labelTitle = new JLabel(Messages.MSGTitle.toString());
183                 this.labelTitle.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 16));
184                 this.panelNorth.add(this.labelTitle, "1, 1, center, top");
185
186                 this.labelVersion = new JLabel(CheckVersion.getVersion());
187                 this.labelVersion.setFont(new Font("SansSerif", Font.BOLD, 12));
188                 this.panelNorth.add(this.labelVersion, "3, 1, right, top");
189
190                 this.panelWest = new JPanel();
191                 this.contentPane.add(this.panelWest, BorderLayout.WEST);
192                 this.panelWest.setLayout(new FormLayout(new ColumnSpec[] {
193                                 FormSpecs.LABEL_COMPONENT_GAP_COLSPEC,
194                                 ColumnSpec.decode("112px:grow"),},
195                                 new RowSpec[] {
196                                                 FormSpecs.LINE_GAP_ROWSPEC,
197                                                 RowSpec.decode("19px"),
198                                                 FormSpecs.RELATED_GAP_ROWSPEC,
199                                                 RowSpec.decode("max(12dlu;default)"),
200                                                 FormSpecs.RELATED_GAP_ROWSPEC,
201                                                 RowSpec.decode("max(12dlu;default)"),
202                                                 FormSpecs.RELATED_GAP_ROWSPEC,
203                                                 RowSpec.decode("12dlu"),
204                                                 FormSpecs.RELATED_GAP_ROWSPEC,
205                                                 RowSpec.decode("max(12dlu;default)"),
206                                                 FormSpecs.RELATED_GAP_ROWSPEC,
207                                                 RowSpec.decode("max(12dlu;default)"),
208                                                 FormSpecs.RELATED_GAP_ROWSPEC,
209                                                 RowSpec.decode("max(12dlu;default)"),
210                                                 FormSpecs.RELATED_GAP_ROWSPEC,
211                                                 RowSpec.decode("max(52dlu;default)"),}));
212
213                 this.labelDifficulty = new JLabel(Messages.MSGSelectDifficulty.toString());
214                 this.labelDifficulty.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
215                 this.panelWest.add(this.labelDifficulty, "2, 2, center, default");
216
217                 this.comboDifficultySelect = new JComboBox();
218                 this.comboDifficultySelect.setFont(new Font("Dialog", Font.BOLD, 12));
219                 this.comboDifficultySelect.setModel(new DefaultComboBoxModel(new String[] {Messages.MSGNonSelected.toString(), "DEBUT", "REGULAR", "PRO", "MASTER", "MASTER+", "ⓁMASTER+", "LIGHT", "TRICK", "PIANO", "FORTE", "WITCH"}));
220                 this.panelWest.add(this.comboDifficultySelect, "2, 4, fill, default");
221
222                 this.comboAttribute = new JComboBox();
223                 this.comboAttribute.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
224                 this.comboAttribute.setModel(new DefaultComboBoxModel(new String[] {Messages.MSGNonSelected.toString(), "全タイプ", "キュート", "クール", "パッション"}));
225                 this.panelWest.add(this.comboAttribute, "2, 6, fill, default");
226
227                 this.labelLevel = new JLabel(Messages.MSGSongLevel.toString());
228                 this.labelLevel.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
229                 this.panelWest.add(this.labelLevel, "2, 8, center, default");
230
231                 this.spinnerLevel = new JSpinner();
232                 this.panelWest.add(this.spinnerLevel, "2, 10");
233
234                 this.checkLessLv = new JCheckBox(Messages.MSGBelowSpecificLevel.toString());
235                 this.checkLessLv.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
236                 this.panelWest.add(this.checkLessLv, "2, 12");
237
238                 this.checkMoreLv = new JCheckBox(Messages.MSGOverSpecificLevel.toString());
239                 this.checkMoreLv.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
240                 this.panelWest.add(this.checkMoreLv, "2, 14");
241
242                 this.labelLvCaution = new JLabel(Messages.MSGLevelCheckboxInfo.toString());
243                 this.labelLvCaution.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
244                 this.panelWest.add(this.labelLvCaution, "2, 16, fill, fill");
245
246                 this.panelEast = new JPanel();
247                 this.contentPane.add(this.panelEast, BorderLayout.EAST);
248                 this.panelEast.setLayout(new FormLayout(new ColumnSpec[] {
249                                 ColumnSpec.decode("98px"),},
250                                 new RowSpec[] {
251                                                 RowSpec.decode("26px"),
252                                                 FormSpecs.RELATED_GAP_ROWSPEC,
253                                                 RowSpec.decode("max(36dlu;default)"),
254                                                 FormSpecs.RELATED_GAP_ROWSPEC,
255                                                 FormSpecs.DEFAULT_ROWSPEC,
256                                                 FormSpecs.RELATED_GAP_ROWSPEC,
257                                                 RowSpec.decode("max(30dlu;default)"),
258                                                 FormSpecs.RELATED_GAP_ROWSPEC,
259                                                 RowSpec.decode("max(15dlu;default)"),
260                                                 FormSpecs.RELATED_GAP_ROWSPEC,
261                                                 RowSpec.decode("max(11dlu;default)"),
262                                                 FormSpecs.RELATED_GAP_ROWSPEC,
263                                                 FormSpecs.DEFAULT_ROWSPEC,
264                                                 FormSpecs.RELATED_GAP_ROWSPEC,
265                                                 FormSpecs.DEFAULT_ROWSPEC,
266                                                 FormSpecs.RELATED_GAP_ROWSPEC,
267                                                 FormSpecs.DEFAULT_ROWSPEC,}));
268
269                 this.btnImport = new JButton(Messages.MSGUpdatingDatabase.toString());
270                 this.btnImport.setEnabled(false);
271                 this.btnImport.addActionListener(e -> {
272                         ArrayList<Song> fromJson = Scraping.getFromJson();
273                         ArrayList<Song> specificlevelList = Scraping.getSpecificLevelSongs(fromJson, (Integer)DelesteRandomSelector.this.spinnerLevel.getValue(), DelesteRandomSelector.this.checkLessLv.isSelected(), DelesteRandomSelector.this.checkMoreLv.isSelected());
274                         ArrayList<Song> specificDifficultyList = Scraping.getSpecificDifficultySongs(specificlevelList, DelesteRandomSelector.this.comboDifficultySelect.getSelectedItem().toString());
275                         ArrayList<Song> specificAttributeList = Scraping.getSpecificAttributeSongs(specificDifficultyList, DelesteRandomSelector.this.comboAttribute.getSelectedItem().toString());
276                         ArrayList<Song> specificTypeList = Scraping.getSpecificAlbumTypeSongs(specificAttributeList, EstimateAlbumTypeCycle.getCurrentCycle());
277                         if(!selectedSongsList.isEmpty()) {
278                                 selectedSongsList.clear();
279                         }
280                         selectedSongsList.addAll((DelesteRandomSelector.this.comboDifficultySelect.getSelectedItem().equals(Scraping.MASTERPLUS) || DelesteRandomSelector.this.comboDifficultySelect.getSelectedItem().equals(Scraping.LEGACYMASTERPLUS)) ? specificTypeList : specificAttributeList);
281                         DelesteRandomSelector.this.logger.info("Songs are selected.We are Ready to go.");
282                         JOptionPane.showMessageDialog(null, Messages.MSGCompleteNarrowDown.toString());
283                 });
284                 this.btnImport.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
285                 this.panelEast.add(this.btnImport, "1, 3, fill, fill");
286
287                 this.btnStart = new JButton(Messages.MSGCalcStart.toString());
288                 this.btnStart.addActionListener(e -> {
289                         Random random = new Random(System.currentTimeMillis());
290                         String paneString = "";
291                         DelesteRandomSelector.this.integratorArray = new String[DelesteRandomSelector.this.property.getSongLimit()];
292                         for(int i = 0; i < DelesteRandomSelector.this.property.getSongLimit(); i++) {
293                                 int randomInt = random.nextInt(selectedSongsList.size());
294                                 String typeString = DelesteRandomSelector.this.comboDifficultySelect.getSelectedItem().equals(Scraping.MASTERPLUS) || DelesteRandomSelector.this.comboDifficultySelect.getSelectedItem().equals(Scraping.LEGACYMASTERPLUS) ? EstimateAlbumTypeCycle.getCurrentCycle() : "";
295                                 paneString = paneString + (i + 1) + Messages.MSGNumberOfSongs.toString() + " " + selectedSongsList.get(randomInt).getAttribute() + " [" + selectedSongsList.get(randomInt).getDifficulty() + "]「" + selectedSongsList.get(randomInt).getName() + "」!(Lv:" + selectedSongsList.get(randomInt).getLevel() + " " + typeString + ")\n\n";
296                                 DelesteRandomSelector.this.integratorArray[i] = selectedSongsList.get(randomInt).getName() + "(Lv" + selectedSongsList.get(randomInt).getLevel() + ")\n";
297                         }
298                         paneString = paneString + Messages.MSGThisPhrase.toString() + DelesteRandomSelector.this.property.getSongLimit() + Messages.MSGPlayPhrase.toString();
299                         DelesteRandomSelector.this.textArea.setText(paneString);
300                         DelesteRandomSelector.this.integratorBool = true;
301                         DelesteRandomSelector.this.logger.info("show up completed.");
302                 });
303                 this.btnStart.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
304                 this.panelEast.add(this.btnStart, "1, 7, fill, fill");
305
306                 this.btnTwitterIntegration = new JButton(Messages.MSGTwitterIntegration.toString());
307                 this.btnTwitterIntegration.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 11));
308                 this.btnTwitterIntegration.addActionListener(e -> {
309                         boolean authorizationStatus = TwitterIntegration.authorization();
310                         String updatedStatus = Messages.MSGUsingThisAppPhrase.toString();
311                         int lengthLimit = updatedStatus.length();
312                         boolean isBroken = false;
313                         if(!DelesteRandomSelector.this.integratorBool) {
314                                 JOptionPane.showMessageDialog(null, Messages.MSGNotPlayYet.toString());
315                                 return;
316                         }
317                         for (String element : DelesteRandomSelector.this.integratorArray) {
318                                 updatedStatus = updatedStatus + element;
319                                 lengthLimit += element.length();
320                                 if(lengthLimit > 69) {
321                                         isBroken = true;
322                                         break;
323                                 }
324                         }
325                         if(isBroken) {
326                                 updatedStatus = updatedStatus + Messages.MSGTwitterPlayOtherwisePhrase.toString() + "\n#DelesteRandomSelector #デレステ ";
327                         } else {
328                                 updatedStatus = updatedStatus + Messages.MSGTwitterPlayOnlyPhrase.toString() + "\n#DelesteRandomSelector #デレステ ";
329                         }
330                         DelesteRandomSelector.this.logger.info("status message constructed.");
331                         lengthLimit = updatedStatus.length();
332                         if(authorizationStatus) {
333                                 int option = JOptionPane.showConfirmDialog(null, Messages.MSGTwitterIntegrationConfirm.toString() + updatedStatus + Messages.MSGStringLength.toString() + lengthLimit);
334                                 DelesteRandomSelector.this.logger.info("user seletced: " + option);
335                                 switch(option) {
336                                 case JOptionPane.OK_OPTION:
337                                         TwitterIntegration.PostTwitter(updatedStatus);
338                                         DelesteRandomSelector.this.logger.info("Success to update the status.");
339                                         JOptionPane.showMessageDialog(null, Messages.MSGCompletePost.toString());
340                                         break;
341                                 case JOptionPane.NO_OPTION:
342                                         DelesteRandomSelector.this.logger.info("There is no will to post.");
343                                         break;
344                                 case JOptionPane.CANCEL_OPTION:
345                                         DelesteRandomSelector.this.logger.info("The Operation was canceled by user.");
346                                         break;
347                                 default:
348                                         break;
349                                 }
350                         } else {
351                                 DelesteRandomSelector.this.logger.info("seems to reject the permission.it should need try again.");
352                         }
353                 });
354                 this.panelEast.add(this.btnTwitterIntegration, "1, 11");
355
356                 this.btnExit = new JButton(Messages.MSGTerminate.toString());
357                 this.btnExit.addActionListener(e -> {
358                         if(DelesteRandomSelector.this.softwareUpdateFuture.isDone() || DelesteRandomSelector.this.albumTypeEstimateFuture.isDone()) {
359                                 DelesteRandomSelector.this.logger.info("Requested Exit by Button");
360                                 System.exit(0);
361                         } else {
362                                 JOptionPane.showMessageDialog(null, Messages.MSGInternalYpdateNotDoneYet.toString());
363                         }
364                 });
365                 this.btnExit.setFont(new Font("UD デジタル 教科書体 NP-B", Font.BOLD, 13));
366                 this.panelEast.add(this.btnExit, "1, 13");
367
368                 this.panelCentre = new JPanel();
369                 this.contentPane.add(this.panelCentre, BorderLayout.CENTER);
370                 this.panelCentre.setLayout(new BorderLayout(0, 0));
371
372                 this.textArea = new JTextArea();
373                 this.textArea.setText(Messages.MSGNarrowDownProcedure.toString() + this.property.getSongLimit() + Messages.MSGCurrentAlbumType.toString() + this.albumType);
374                 this.textArea.setEditable(false);
375
376                 this.scrollPane = new JScrollPane(this.textArea);
377                 this.panelCentre.add(this.scrollPane, BorderLayout.CENTER);
378                 if(isFirst || !this.property.isCheckLibraryUpdates()) {
379                         setEnabled.run();
380                 }
381         }
382
383 }