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