JAL-1641 fixed broken functionalities after refactor
[jalview.git] / src / jalview / io / BioJsHTMLOutput.java
1 package jalview.io;
2
3 import jalview.api.AlignmentViewPanel;
4 import jalview.datamodel.AlignmentExportData;
5 import jalview.exceptions.NoFileSelectedException;
6 import jalview.json.binding.v1.BioJSReleasePojo;
7 import jalview.json.binding.v1.BioJSRepositoryPojo;
8 import jalview.util.MessageManager;
9
10 import java.io.BufferedInputStream;
11 import java.io.BufferedReader;
12 import java.io.File;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.io.InputStreamReader;
16 import java.io.PrintWriter;
17 import java.net.URISyntaxException;
18 import java.net.URL;
19 import java.util.Objects;
20 import java.util.TreeMap;
21
22
23 public class BioJsHTMLOutput
24 {
25   private AlignmentViewPanel ap;
26
27   private static File currentBJSTemplateFile;
28
29   private static TreeMap<String, File> bioJsMSAVersions;
30
31   public static final String DEFAULT_DIR = System.getProperty("user.home")
32           + File.separatorChar + ".biojs_templates" + File.separatorChar;
33
34   public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = jalview.bin.Cache
35           .getDefault("biojs_template_directory", DEFAULT_DIR);
36
37   public static final String BJS_TEMPLATE_GIT_REPO = jalview.bin.Cache
38           .getDefault(
39                   "biojs_template_git_repo",
40                   "https://raw.githubusercontent.com/tcofoegbu/bjs-template/master/package.json");
41
42   public BioJsHTMLOutput(AlignmentViewPanel ap)
43   {
44     if (ap != null)
45     {
46       this.ap = ap;
47     }
48   }
49
50   public void exportJalviewAlignmentAsBioJsHtmlFile()
51   {
52     try
53     {
54       String outputFile = getOutputFile();
55       // String jalviewAlignmentJson = JSONFile.getJSONData(ap);
56       AlignmentExportData exportData = jalview.gui.AlignFrame
57               .getAlignmentForExport(
58               JSONFile.FILE_DESC, ap.getAlignViewport());
59       if (exportData.getSettings().isCancelled())
60       {
61         return;
62       }
63       String jalviewAlignmentJson = new FormatAdapter(ap,
64               exportData.getSettings()).formatSequences(JSONFile.FILE_DESC,
65               exportData.getAlignment(), exportData.getOmitHidden(),
66               exportData.getStartEndPostions(), ap.getAlignViewport()
67                       .getColumnSelection());
68
69       String bioJSTemplateString = getBioJsTemplateAsString();
70       String generatedBioJsWithJalviewAlignmentAsJson = bioJSTemplateString
71               .replaceAll(
72 "#sequenceData#", jalviewAlignmentJson)
73               .toString();
74
75       PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(
76               outputFile));
77       out.print(generatedBioJsWithJalviewAlignmentAsJson);
78       out.flush();
79       out.close();
80       jalview.util.BrowserLauncher.openURL("file:///" + outputFile);
81     } catch (NoFileSelectedException ex)
82     {
83       // do noting if no file was selected
84     } catch (Exception e)
85     {
86       e.printStackTrace();
87     }
88   }
89
90   public String getOutputFile() throws NoFileSelectedException
91   {
92     String selectedFile = null;
93     JalviewFileChooser jvFileChooser = new JalviewFileChooser(
94             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
95             { "html" }, new String[]
96             { "HTML files" }, "HTML files");
97     jvFileChooser.setFileView(new JalviewFileView());
98
99     // TODO uncomment when supported by MassageManager
100     jvFileChooser.setDialogTitle(MessageManager
101             .getString("label.save_as_biojs_html"));
102     jvFileChooser.setDialogTitle("save as BioJs HTML");
103     jvFileChooser.setToolTipText(MessageManager.getString("action.save"));
104
105     int fileChooserOpt = jvFileChooser.showSaveDialog(null);
106     if (fileChooserOpt == JalviewFileChooser.APPROVE_OPTION)
107     {
108       jalview.bin.Cache.setProperty("LAST_DIRECTORY", jvFileChooser
109               .getSelectedFile().getParent());
110       selectedFile = jvFileChooser.getSelectedFile().getPath();
111     }
112     else
113     {
114       throw new NoFileSelectedException("No file was selected.");
115     }
116     return selectedFile;
117   }
118
119
120   public static String getBioJsTemplateAsString()
121           throws IOException
122   {
123     InputStreamReader isReader = null;
124     BufferedReader buffReader = null;
125     StringBuilder sb = new StringBuilder();
126     Objects.requireNonNull(getCurrentBJSTemplateFile(),
127             "BioJsTemplate File not initialized!");
128     @SuppressWarnings("deprecation")
129     URL url = getCurrentBJSTemplateFile().toURL();
130     if (url != null)
131     {
132       try
133       {
134         isReader = new InputStreamReader(url.openStream());
135         buffReader = new BufferedReader(isReader);
136         String line;
137         String lineSeparator = System.getProperty("line.separator");
138         while ((line = buffReader.readLine()) != null)
139         {
140           sb.append(line).append(lineSeparator);
141         }
142
143       } catch (Exception ex)
144       {
145         ex.printStackTrace();
146       } finally
147       {
148         if (isReader != null)
149         {
150           isReader.close();
151         }
152
153         if (buffReader != null)
154         {
155           buffReader.close();
156         }
157       }
158     }
159     return sb.toString();
160   }
161
162   public static void refreshBioJSVersionsInfo(String dirName)
163           throws URISyntaxException
164   {
165     File directory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
166     Objects.requireNonNull(dirName, "dirName MUST not be null!");
167     Objects.requireNonNull(directory, "directory MUST not be null!");
168     TreeMap<String, File> versionFileMap = new TreeMap<String, File>();
169
170     for (File file : directory.listFiles())
171     {
172       if (file.isFile())
173       {
174         String fileName = file.getName().substring(0,
175                 file.getName().lastIndexOf("."));
176         String fileMeta[] = fileName.split("_");
177         if (fileMeta.length > 2)
178         {
179           setCurrentBJSTemplateFile(file);
180           versionFileMap.put(fileMeta[2], file);
181         }
182         else if (fileMeta.length > 1)
183         {
184           versionFileMap.put(fileMeta[1], file);
185         }
186       }
187     }
188     if (getCurrentBJSTemplateFile() == null && versionFileMap.size() > 0)
189     {
190       setCurrentBJSTemplateFile(versionFileMap.lastEntry().getValue());
191     }
192     setBioJsMSAVersions(versionFileMap);
193   }
194
195   public static void updateBioJS()
196   {
197     Thread updateThread = new Thread()
198     {
199       public void run()
200       {
201         try
202         {
203           String gitRepoPkgJson = getURLContentAsString(BJS_TEMPLATE_GIT_REPO);
204           BioJSRepositoryPojo release = new BioJSRepositoryPojo(
205                   gitRepoPkgJson);
206           syncUpdates(BJS_TEMPLATES_LOCAL_DIRECTORY, release);
207           refreshBioJSVersionsInfo(BJS_TEMPLATES_LOCAL_DIRECTORY);
208         } catch (URISyntaxException e)
209         {
210           e.printStackTrace();
211         }
212       }
213     };
214     updateThread.start();
215
216   }
217
218
219   public static void syncUpdates(String localDir, BioJSRepositoryPojo repo)
220   {
221     for (BioJSReleasePojo bjsRelease : repo.getReleases())
222     {
223       String releaseUrl = bjsRelease.getUrl();
224       String releaseVersion = bjsRelease.getVersion();
225       String releaseFile = "BioJsMSA_" + releaseVersion + ".txt";
226       if (releaseVersion.equals(repo.getLatestReleaseVersion()))
227       {
228         releaseFile = "Latest_BioJsMSA_" + releaseVersion + ".txt";
229       }
230
231       File biojsDirectory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
232       if (!biojsDirectory.exists())
233       {
234         if (!biojsDirectory.mkdirs())
235         {
236           System.out.println("Couldn't create local directory : "
237                   + BJS_TEMPLATES_LOCAL_DIRECTORY);
238           return;
239         }
240       }
241
242       File file = new File(BJS_TEMPLATES_LOCAL_DIRECTORY + releaseFile);
243       if (!file.exists())
244       {
245
246         PrintWriter out = null;
247         try
248         {
249           out = new java.io.PrintWriter(new java.io.FileWriter(file));
250           out.print(getURLContentAsString(releaseUrl));
251         } catch (IOException e)
252         {
253           e.printStackTrace();
254         } finally
255         {
256           if (out != null)
257           {
258             out.flush();
259             out.close();
260           }
261         }
262       }
263     }
264
265   }
266
267   public static String getURLContentAsString(String url)
268           throws OutOfMemoryError
269   {
270     StringBuilder responseStrBuilder = null;
271     InputStream is = null;
272     try
273     {
274       URL resourceUrl = new URL(url);
275       is = new BufferedInputStream(resourceUrl.openStream());
276       BufferedReader br = new BufferedReader(new InputStreamReader(is));
277       responseStrBuilder = new StringBuilder();
278       String lineContent;
279
280       while ((lineContent = br.readLine()) != null)
281       {
282         responseStrBuilder.append(lineContent).append("\n");
283       }
284     } catch (OutOfMemoryError er)
285     {
286       er.printStackTrace();
287     } catch (Exception ex)
288     {
289       ex.printStackTrace();
290     } finally
291     {
292       if (is != null)
293       {
294         try
295         {
296           is.close();
297         } catch (IOException e)
298         {
299           e.printStackTrace();
300         }
301       }
302     }
303     return responseStrBuilder == null ? null : responseStrBuilder
304             .toString();
305   }
306
307   public static File getCurrentBJSTemplateFile()
308   {
309     return currentBJSTemplateFile;
310   }
311
312   public static void setCurrentBJSTemplateFile(File currentBJSTemplateFile)
313   {
314     BioJsHTMLOutput.currentBJSTemplateFile = currentBJSTemplateFile;
315   }
316
317   public static TreeMap<String, File> getBioJsMSAVersions()
318   {
319     return bioJsMSAVersions;
320   }
321
322   public static void setBioJsMSAVersions(
323           TreeMap<String, File> bioJsMSAVersions)
324   {
325     BioJsHTMLOutput.bioJsMSAVersions = bioJsMSAVersions;
326   }
327
328 }