2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.api.AlignExportSettingI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.AlignmentExportData;
26 import jalview.exceptions.NoFileSelectedException;
27 import jalview.gui.IProgressIndicator;
28 import jalview.gui.OOMWarning;
29 import jalview.json.binding.biojs.BioJSReleasePojo;
30 import jalview.json.binding.biojs.BioJSRepositoryPojo;
31 import jalview.util.MessageManager;
33 import java.io.BufferedInputStream;
34 import java.io.BufferedReader;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.InputStreamReader;
39 import java.io.PrintWriter;
40 import java.net.URISyntaxException;
42 import java.util.Objects;
43 import java.util.TreeMap;
45 public class BioJsHTMLOutput
47 private AlignmentViewPanel ap;
49 private long pSessionId;
51 private IProgressIndicator pIndicator;
53 private boolean headless;
55 private static File currentBJSTemplateFile;
57 private static TreeMap<String, File> bioJsMSAVersions;
59 public static final String DEFAULT_DIR = System.getProperty("user.home")
60 + File.separatorChar + ".biojs_templates" + File.separatorChar;
62 public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = jalview.bin.Cache
63 .getDefault("biojs_template_directory", DEFAULT_DIR);
65 public static final String BJS_TEMPLATE_GIT_REPO = jalview.bin.Cache
67 "biojs_template_git_repo",
68 "https://raw.githubusercontent.com/jalview/exporter-templates/master/biojs/package.json");
70 public BioJsHTMLOutput(AlignmentViewPanel ap,
71 IProgressIndicator pIndicator)
76 this.pSessionId = System.currentTimeMillis();
77 this.pIndicator = pIndicator;
78 this.headless = (System.getProperty("java.awt.headless") != null && System
79 .getProperty("java.awt.headless").equals("true"));
83 public void exportJalviewAlignmentAsBioJsHtmlFile(String outputFile)
85 // String outputFile = null;
88 if (outputFile == null)
90 outputFile = getOutputFile();
92 AlignExportSettingI exportSettings = new AlignExportSettingI()
95 public boolean isExportHiddenSequences()
101 public boolean isExportHiddenColumns()
107 public boolean isExportAnnotations()
113 public boolean isExportFeatures()
119 public boolean isExportGroups()
125 public boolean isCancelled()
131 AlignmentExportData exportData = jalview.gui.AlignFrame
132 .getAlignmentForExport(JSONFile.FILE_DESC,
133 ap.getAlignViewport(), exportSettings);
134 String bioJSON = new FormatAdapter(ap, exportData.getSettings())
135 .formatSequences(JSONFile.FILE_DESC, exportData
136 .getAlignment(), exportData.getOmitHidden(),
137 exportData.getStartEndPostions(), ap
138 .getAlignViewport().getColumnSelection());
140 String bioJSTemplateString = getBioJsTemplateAsString();
141 String generatedBioJsWithJalviewAlignmentAsJson = bioJSTemplateString
142 .replaceAll("#sequenceData#", bioJSON).toString();
144 PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(
146 out.print(generatedBioJsWithJalviewAlignmentAsJson);
149 jalview.util.BrowserLauncher.openURL("file:///" + outputFile);
150 if (pIndicator != null && !headless)
152 pIndicator.setProgressBar(MessageManager.formatMessage(
153 "status.export_complete", "BioJS"), pSessionId);
155 } catch (NoFileSelectedException ex)
157 // do noting if no file was selected
158 } catch (OutOfMemoryError err)
160 System.out.println("########################\n" + "OUT OF MEMORY "
161 + outputFile + "\n" + "########################");
162 new OOMWarning("Creating Image for " + outputFile, err);
163 } catch (Exception e)
165 if (pIndicator != null && !headless)
167 pIndicator.setProgressBar(MessageManager.formatMessage(
168 "info.error_creating_file", "HTML"), pSessionId);
174 public String getOutputFile() throws NoFileSelectedException
176 String selectedFile = null;
177 if (pIndicator != null && !headless)
179 pIndicator.setProgressBar(MessageManager.formatMessage(
180 "status.waiting_for_user_to_select_output_file", "HTML"),
184 JalviewFileChooser jvFileChooser = new JalviewFileChooser(
185 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
186 new String[] { "html" }, new String[] { "HTML files" },
188 jvFileChooser.setFileView(new JalviewFileView());
190 jvFileChooser.setDialogTitle(MessageManager
191 .getString("label.save_as_biojs_html"));
192 jvFileChooser.setToolTipText(MessageManager.getString("action.save"));
194 int fileChooserOpt = jvFileChooser.showSaveDialog(null);
195 if (fileChooserOpt == JalviewFileChooser.APPROVE_OPTION)
197 jalview.bin.Cache.setProperty("LAST_DIRECTORY", jvFileChooser
198 .getSelectedFile().getParent());
199 selectedFile = jvFileChooser.getSelectedFile().getPath();
203 pIndicator.setProgressBar(MessageManager.formatMessage(
204 "status.cancelled_image_export_operation", "BioJS"),
206 throw new NoFileSelectedException("No file was selected.");
211 public static String getBioJsTemplateAsString() throws IOException
213 InputStreamReader isReader = null;
214 BufferedReader buffReader = null;
215 StringBuilder sb = new StringBuilder();
216 Objects.requireNonNull(getCurrentBJSTemplateFile(),
217 "BioJsTemplate File not initialized!");
218 @SuppressWarnings("deprecation")
219 URL url = getCurrentBJSTemplateFile().toURL();
224 isReader = new InputStreamReader(url.openStream());
225 buffReader = new BufferedReader(isReader);
227 String lineSeparator = System.getProperty("line.separator");
228 while ((line = buffReader.readLine()) != null)
230 sb.append(line).append(lineSeparator);
233 } catch (Exception ex)
235 ex.printStackTrace();
238 if (isReader != null)
243 if (buffReader != null)
249 return sb.toString();
252 public static void refreshBioJSVersionsInfo(String dirName)
253 throws URISyntaxException
255 File directory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
256 Objects.requireNonNull(dirName, "dirName MUST not be null!");
257 Objects.requireNonNull(directory, "directory MUST not be null!");
258 TreeMap<String, File> versionFileMap = new TreeMap<String, File>();
260 for (File file : directory.listFiles())
264 String fileName = file.getName().substring(0,
265 file.getName().lastIndexOf("."));
266 String fileMeta[] = fileName.split("_");
267 if (fileMeta.length > 2)
269 setCurrentBJSTemplateFile(file);
270 versionFileMap.put(fileMeta[2], file);
272 else if (fileMeta.length > 1)
274 versionFileMap.put(fileMeta[1], file);
278 if (getCurrentBJSTemplateFile() == null && versionFileMap.size() > 0)
280 setCurrentBJSTemplateFile(versionFileMap.lastEntry().getValue());
282 setBioJsMSAVersions(versionFileMap);
285 public static void updateBioJS()
287 Thread updateThread = new Thread()
294 String gitRepoPkgJson = getURLContentAsString(BJS_TEMPLATE_GIT_REPO);
295 if (gitRepoPkgJson != null)
297 BioJSRepositoryPojo release = new BioJSRepositoryPojo(
299 syncUpdates(BJS_TEMPLATES_LOCAL_DIRECTORY, release);
300 refreshBioJSVersionsInfo(BJS_TEMPLATES_LOCAL_DIRECTORY);
302 } catch (URISyntaxException e)
308 updateThread.start();
312 public static void syncUpdates(String localDir, BioJSRepositoryPojo repo)
314 for (BioJSReleasePojo bjsRelease : repo.getReleases())
316 String releaseUrl = bjsRelease.getUrl();
317 String releaseVersion = bjsRelease.getVersion();
318 String releaseFile = "BioJsMSA_" + releaseVersion + ".txt";
319 if (releaseVersion.equals(repo.getLatestReleaseVersion()))
321 releaseFile = "Latest_BioJsMSA_" + releaseVersion + ".txt";
324 File biojsDirectory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
325 if (!biojsDirectory.exists())
327 if (!biojsDirectory.mkdirs())
329 System.out.println("Couldn't create local directory : "
330 + BJS_TEMPLATES_LOCAL_DIRECTORY);
335 File file = new File(BJS_TEMPLATES_LOCAL_DIRECTORY + releaseFile);
339 PrintWriter out = null;
342 out = new java.io.PrintWriter(new java.io.FileWriter(file));
343 out.print(getURLContentAsString(releaseUrl));
344 } catch (IOException e)
360 public static String getURLContentAsString(String url)
361 throws OutOfMemoryError
363 StringBuilder responseStrBuilder = null;
364 InputStream is = null;
367 URL resourceUrl = new URL(url);
368 is = new BufferedInputStream(resourceUrl.openStream());
369 BufferedReader br = new BufferedReader(new InputStreamReader(is));
370 responseStrBuilder = new StringBuilder();
373 while ((lineContent = br.readLine()) != null)
375 responseStrBuilder.append(lineContent).append("\n");
377 } catch (OutOfMemoryError er)
379 er.printStackTrace();
380 } catch (Exception ex)
382 ex.printStackTrace();
390 } catch (IOException e)
396 return responseStrBuilder == null ? null : responseStrBuilder
400 public static File getCurrentBJSTemplateFile()
402 return currentBJSTemplateFile;
405 public static void setCurrentBJSTemplateFile(File currentBJSTemplateFile)
407 BioJsHTMLOutput.currentBJSTemplateFile = currentBJSTemplateFile;
410 public static TreeMap<String, File> getBioJsMSAVersions()
412 return bioJsMSAVersions;
415 public static void setBioJsMSAVersions(
416 TreeMap<String, File> bioJsMSAVersions)
418 BioJsHTMLOutput.bioJsMSAVersions = bioJsMSAVersions;