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