house keeping
[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     jvFileChooser.setDialogTitle(MessageManager
100             .getString("label.save_as_biojs_html"));
101     jvFileChooser.setDialogTitle("save as BioJs HTML");
102     jvFileChooser.setToolTipText(MessageManager.getString("action.save"));
103
104     int fileChooserOpt = jvFileChooser.showSaveDialog(null);
105     if (fileChooserOpt == JalviewFileChooser.APPROVE_OPTION)
106     {
107       jalview.bin.Cache.setProperty("LAST_DIRECTORY", jvFileChooser
108               .getSelectedFile().getParent());
109       selectedFile = jvFileChooser.getSelectedFile().getPath();
110     }
111     else
112     {
113       throw new NoFileSelectedException("No file was selected.");
114     }
115     return selectedFile;
116   }
117
118
119   public static String getBioJsTemplateAsString()
120           throws IOException
121   {
122     InputStreamReader isReader = null;
123     BufferedReader buffReader = null;
124     StringBuilder sb = new StringBuilder();
125     Objects.requireNonNull(getCurrentBJSTemplateFile(),
126             "BioJsTemplate File not initialized!");
127     @SuppressWarnings("deprecation")
128     URL url = getCurrentBJSTemplateFile().toURL();
129     if (url != null)
130     {
131       try
132       {
133         isReader = new InputStreamReader(url.openStream());
134         buffReader = new BufferedReader(isReader);
135         String line;
136         String lineSeparator = System.getProperty("line.separator");
137         while ((line = buffReader.readLine()) != null)
138         {
139           sb.append(line).append(lineSeparator);
140         }
141
142       } catch (Exception ex)
143       {
144         ex.printStackTrace();
145       } finally
146       {
147         if (isReader != null)
148         {
149           isReader.close();
150         }
151
152         if (buffReader != null)
153         {
154           buffReader.close();
155         }
156       }
157     }
158     return sb.toString();
159   }
160
161   public static void refreshBioJSVersionsInfo(String dirName)
162           throws URISyntaxException
163   {
164     File directory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
165     Objects.requireNonNull(dirName, "dirName MUST not be null!");
166     Objects.requireNonNull(directory, "directory MUST not be null!");
167     TreeMap<String, File> versionFileMap = new TreeMap<String, File>();
168
169     for (File file : directory.listFiles())
170     {
171       if (file.isFile())
172       {
173         String fileName = file.getName().substring(0,
174                 file.getName().lastIndexOf("."));
175         String fileMeta[] = fileName.split("_");
176         if (fileMeta.length > 2)
177         {
178           setCurrentBJSTemplateFile(file);
179           versionFileMap.put(fileMeta[2], file);
180         }
181         else if (fileMeta.length > 1)
182         {
183           versionFileMap.put(fileMeta[1], file);
184         }
185       }
186     }
187     if (getCurrentBJSTemplateFile() == null && versionFileMap.size() > 0)
188     {
189       setCurrentBJSTemplateFile(versionFileMap.lastEntry().getValue());
190     }
191     setBioJsMSAVersions(versionFileMap);
192   }
193
194   public static void updateBioJS()
195   {
196     Thread updateThread = new Thread()
197     {
198       public void run()
199       {
200         try
201         {
202           String gitRepoPkgJson = getURLContentAsString(BJS_TEMPLATE_GIT_REPO);
203           if (gitRepoPkgJson != null)
204           {
205             BioJSRepositoryPojo release = new BioJSRepositoryPojo(
206                     gitRepoPkgJson);
207             syncUpdates(BJS_TEMPLATES_LOCAL_DIRECTORY, release);
208             refreshBioJSVersionsInfo(BJS_TEMPLATES_LOCAL_DIRECTORY);
209           }
210         } catch (URISyntaxException e)
211         {
212           e.printStackTrace();
213         }
214       }
215     };
216     updateThread.start();
217
218   }
219
220
221   public static void syncUpdates(String localDir, BioJSRepositoryPojo repo)
222   {
223     for (BioJSReleasePojo bjsRelease : repo.getReleases())
224     {
225       String releaseUrl = bjsRelease.getUrl();
226       String releaseVersion = bjsRelease.getVersion();
227       String releaseFile = "BioJsMSA_" + releaseVersion + ".txt";
228       if (releaseVersion.equals(repo.getLatestReleaseVersion()))
229       {
230         releaseFile = "Latest_BioJsMSA_" + releaseVersion + ".txt";
231       }
232
233       File biojsDirectory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
234       if (!biojsDirectory.exists())
235       {
236         if (!biojsDirectory.mkdirs())
237         {
238           System.out.println("Couldn't create local directory : "
239                   + BJS_TEMPLATES_LOCAL_DIRECTORY);
240           return;
241         }
242       }
243
244       File file = new File(BJS_TEMPLATES_LOCAL_DIRECTORY + releaseFile);
245       if (!file.exists())
246       {
247
248         PrintWriter out = null;
249         try
250         {
251           out = new java.io.PrintWriter(new java.io.FileWriter(file));
252           out.print(getURLContentAsString(releaseUrl));
253         } catch (IOException e)
254         {
255           e.printStackTrace();
256         } finally
257         {
258           if (out != null)
259           {
260             out.flush();
261             out.close();
262           }
263         }
264       }
265     }
266
267   }
268
269   public static String getURLContentAsString(String url)
270           throws OutOfMemoryError
271   {
272     StringBuilder responseStrBuilder = null;
273     InputStream is = null;
274     try
275     {
276       URL resourceUrl = new URL(url);
277       is = new BufferedInputStream(resourceUrl.openStream());
278       BufferedReader br = new BufferedReader(new InputStreamReader(is));
279       responseStrBuilder = new StringBuilder();
280       String lineContent;
281
282       while ((lineContent = br.readLine()) != null)
283       {
284         responseStrBuilder.append(lineContent).append("\n");
285       }
286     } catch (OutOfMemoryError er)
287     {
288       er.printStackTrace();
289     } catch (Exception ex)
290     {
291       ex.printStackTrace();
292     } finally
293     {
294       if (is != null)
295       {
296         try
297         {
298           is.close();
299         } catch (IOException e)
300         {
301           e.printStackTrace();
302         }
303       }
304     }
305     return responseStrBuilder == null ? null : responseStrBuilder
306             .toString();
307   }
308
309   public static File getCurrentBJSTemplateFile()
310   {
311     return currentBJSTemplateFile;
312   }
313
314   public static void setCurrentBJSTemplateFile(File currentBJSTemplateFile)
315   {
316     BioJsHTMLOutput.currentBJSTemplateFile = currentBJSTemplateFile;
317   }
318
319   public static TreeMap<String, File> getBioJsMSAVersions()
320   {
321     return bioJsMSAVersions;
322   }
323
324   public static void setBioJsMSAVersions(
325           TreeMap<String, File> bioJsMSAVersions)
326   {
327     BioJsHTMLOutput.bioJsMSAVersions = bioJsMSAVersions;
328   }
329
330 }