Merge branch 'releases/Release_2_10_Branch'
[jalview.git] / src / jalview / io / BioJsHTMLOutput.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.exceptions.NoFileSelectedException;
24 import jalview.gui.AlignmentPanel;
25 import jalview.gui.OOMWarning;
26 import jalview.json.binding.biojs.BioJSReleasePojo;
27 import jalview.json.binding.biojs.BioJSRepositoryPojo;
28 import jalview.util.MessageManager;
29
30 import java.io.BufferedInputStream;
31 import java.io.BufferedReader;
32 import java.io.File;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.io.PrintWriter;
37 import java.net.URISyntaxException;
38 import java.net.URL;
39 import java.util.Objects;
40 import java.util.TreeMap;
41
42 public class BioJsHTMLOutput extends HTMLOutput
43 {
44
45   private static File currentBJSTemplateFile;
46
47   private static TreeMap<String, File> bioJsMSAVersions;
48
49   public static final String DEFAULT_DIR = System.getProperty("user.home")
50           + File.separatorChar + ".biojs_templates" + File.separatorChar;
51
52   public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = jalview.bin.Cache
53           .getDefault("biojs_template_directory", DEFAULT_DIR);
54
55   public static final String BJS_TEMPLATE_GIT_REPO = jalview.bin.Cache
56           .getDefault(
57                   "biojs_template_git_repo",
58                   "https://raw.githubusercontent.com/jalview/exporter-templates/master/biojs/package.json");
59
60   public BioJsHTMLOutput(AlignmentPanel ap)
61   {
62     super(ap);
63   }
64
65   @Override
66   public void exportHTML(String outputFile)
67   {
68     exportStarted();
69     try
70     {
71       if (outputFile == null)
72       {
73         outputFile = getOutputFile();
74       }
75       generatedFile = new File(outputFile);
76     } catch (NoFileSelectedException e)
77     {
78       setProgressMessage(MessageManager.formatMessage(
79               "status.cancelled_image_export_operation", "BioJS MSA"));
80       return;
81     } catch (Exception e)
82     {
83       setProgressMessage(MessageManager.formatMessage(
84               "info.error_creating_file", "BioJS MSA"));
85       e.printStackTrace();
86       return;
87     }
88     new Thread(this).start();
89
90   }
91
92
93
94   public static void refreshVersionInfo(String dirName)
95           throws URISyntaxException
96   {
97     File directory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
98     Objects.requireNonNull(dirName, "dirName MUST not be null!");
99     Objects.requireNonNull(directory, "directory MUST not be null!");
100     TreeMap<String, File> versionFileMap = new TreeMap<String, File>();
101
102     for (File file : directory.listFiles())
103     {
104       if (file.isFile())
105       {
106         String fileName = file.getName().substring(0,
107                 file.getName().lastIndexOf("."));
108         String fileMeta[] = fileName.split("_");
109         if (fileMeta.length > 2)
110         {
111           setCurrentBJSTemplateFile(file);
112           versionFileMap.put(fileMeta[2], file);
113         }
114         else if (fileMeta.length > 1)
115         {
116           versionFileMap.put(fileMeta[1], file);
117         }
118       }
119     }
120     if (getCurrentBJSTemplateFile() == null && versionFileMap.size() > 0)
121     {
122       setCurrentBJSTemplateFile(versionFileMap.lastEntry().getValue());
123     }
124     setBioJsMSAVersions(versionFileMap);
125   }
126
127   public static void updateBioJS()
128   {
129     Thread updateThread = new Thread()
130     {
131       @Override
132       public void run()
133       {
134         try
135         {
136           String gitRepoPkgJson = getURLContentAsString(BJS_TEMPLATE_GIT_REPO);
137           if (gitRepoPkgJson != null)
138           {
139             BioJSRepositoryPojo release = new BioJSRepositoryPojo(
140                     gitRepoPkgJson);
141             syncUpdates(BJS_TEMPLATES_LOCAL_DIRECTORY, release);
142             refreshVersionInfo(BJS_TEMPLATES_LOCAL_DIRECTORY);
143           }
144         } catch (URISyntaxException e)
145         {
146           e.printStackTrace();
147         }
148       }
149     };
150     updateThread.start();
151
152   }
153
154   public static void syncUpdates(String localDir, BioJSRepositoryPojo repo)
155   {
156     for (BioJSReleasePojo bjsRelease : repo.getReleases())
157     {
158       String releaseUrl = bjsRelease.getUrl();
159       String releaseVersion = bjsRelease.getVersion();
160       String releaseFile = "BioJsMSA_" + releaseVersion + ".txt";
161       if (releaseVersion.equals(repo.getLatestReleaseVersion()))
162       {
163         releaseFile = "Latest_BioJsMSA_" + releaseVersion + ".txt";
164       }
165
166       File biojsDirectory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
167       if (!biojsDirectory.exists())
168       {
169         if (!biojsDirectory.mkdirs())
170         {
171           System.out.println("Couldn't create local directory : "
172                   + BJS_TEMPLATES_LOCAL_DIRECTORY);
173           return;
174         }
175       }
176
177       File file = new File(BJS_TEMPLATES_LOCAL_DIRECTORY + releaseFile);
178       if (!file.exists())
179       {
180
181         PrintWriter out = null;
182         try
183         {
184           out = new java.io.PrintWriter(new java.io.FileWriter(file));
185           out.print(getURLContentAsString(releaseUrl));
186         } catch (IOException e)
187         {
188           e.printStackTrace();
189         } finally
190         {
191           if (out != null)
192           {
193             out.flush();
194             out.close();
195           }
196         }
197       }
198     }
199
200   }
201
202   public static String getURLContentAsString(String url)
203           throws OutOfMemoryError
204   {
205     StringBuilder responseStrBuilder = null;
206     InputStream is = null;
207     try
208     {
209       URL resourceUrl = new URL(url);
210       is = new BufferedInputStream(resourceUrl.openStream());
211       BufferedReader br = new BufferedReader(new InputStreamReader(is));
212       responseStrBuilder = new StringBuilder();
213       String lineContent;
214
215       while ((lineContent = br.readLine()) != null)
216       {
217         responseStrBuilder.append(lineContent).append("\n");
218       }
219     } catch (OutOfMemoryError er)
220     {
221       er.printStackTrace();
222     } catch (Exception ex)
223     {
224       ex.printStackTrace();
225     } finally
226     {
227       if (is != null)
228       {
229         try
230         {
231           is.close();
232         } catch (IOException e)
233         {
234           e.printStackTrace();
235         }
236       }
237     }
238     return responseStrBuilder == null ? null : responseStrBuilder
239             .toString();
240   }
241
242   public static File getCurrentBJSTemplateFile()
243   {
244     return currentBJSTemplateFile;
245   }
246
247   public static void setCurrentBJSTemplateFile(File currentBJSTemplateFile)
248   {
249     BioJsHTMLOutput.currentBJSTemplateFile = currentBJSTemplateFile;
250   }
251
252   public static TreeMap<String, File> getBioJsMSAVersions()
253   {
254     return bioJsMSAVersions;
255   }
256
257   public static void setBioJsMSAVersions(
258           TreeMap<String, File> bioJsMSAVersions)
259   {
260     BioJsHTMLOutput.bioJsMSAVersions = bioJsMSAVersions;
261   }
262
263   @Override
264   public boolean isEmbedData()
265   {
266     return true;
267   }
268
269   @Override
270   public boolean isLaunchInBrowserAfterExport()
271   {
272     return true;
273   }
274
275   @Override
276   public File getExportedFile()
277   {
278     return generatedFile;
279   }
280
281   @Override
282   public void run()
283   {
284     try
285     {
286       String bioJSON = getBioJSONData();
287       String bioJSTemplateString = HTMLOutput
288               .readFileAsString(getCurrentBJSTemplateFile());
289       String generatedBioJsWithJalviewAlignmentAsJson = bioJSTemplateString
290               .replaceAll("#sequenceData#", bioJSON).toString();
291
292       PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(
293               generatedFile));
294       out.print(generatedBioJsWithJalviewAlignmentAsJson);
295       out.flush();
296       out.close();
297       setProgressMessage(MessageManager.formatMessage(
298               "status.export_complete", "BioJS"));
299       exportCompleted();
300
301     } catch (OutOfMemoryError err)
302     {
303       System.out.println("########################\n" + "OUT OF MEMORY "
304               + generatedFile + "\n" + "########################");
305       new OOMWarning("Creating Image for " + generatedFile, err);
306     } catch (Exception e)
307     {
308       setProgressMessage(MessageManager.formatMessage(
309               "info.error_creating_file", "HTML"));
310       e.printStackTrace();
311     }
312
313   }
314
315 }