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