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