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.bin.Cache;
26 import jalview.datamodel.AlignmentExportData;
27 import jalview.exceptions.NoFileSelectedException;
28 import jalview.gui.AlignFrame;
29 import jalview.gui.IProgressIndicator;
30 import jalview.gui.OOMWarning;
31 import jalview.json.binding.biojs.BioJSReleasePojo;
32 import jalview.json.binding.biojs.BioJSRepositoryPojo;
33 import jalview.util.ImageMaker;
34 import jalview.util.MessageManager;
36 import java.io.BufferedInputStream;
37 import java.io.BufferedReader;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.io.InputStreamReader;
42 import java.io.PrintWriter;
43 import java.net.URISyntaxException;
45 import java.util.Objects;
46 import java.util.TreeMap;
48 public class BioJsHTMLOutput
50 private AlignmentViewPanel ap;
52 private long pSessionId;
54 private IProgressIndicator pIndicator;
56 private boolean headless;
58 private static File currentBJSTemplateFile;
60 private static TreeMap<String, File> bioJsMSAVersions;
62 public static final String DEFAULT_DIR = System.getProperty("user.home")
63 + File.separatorChar + ".biojs_templates" + File.separatorChar;
65 public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = jalview.bin.Cache
66 .getDefault("biojs_template_directory", DEFAULT_DIR);
68 public static final String BJS_TEMPLATE_GIT_REPO = jalview.bin.Cache
70 "biojs_template_git_repo",
71 "https://raw.githubusercontent.com/jalview/exporter-templates/master/biojs/package.json");
73 public BioJsHTMLOutput(AlignmentViewPanel ap,
74 IProgressIndicator pIndicator)
79 this.pSessionId = System.currentTimeMillis();
80 this.pIndicator = pIndicator;
81 this.headless = (System.getProperty("java.awt.headless") != null && System
82 .getProperty("java.awt.headless").equals("true"));
86 public void exportJalviewAlignmentAsBioJsHtmlFile()
88 String outputFile = null;
91 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 = AlignFrame
132 .getAlignmentForExport(FileFormat.Json,
133 ap.getAlignViewport(), exportSettings);
134 String bioJSON = new FormatAdapter(ap, exportData.getSettings())
135 .formatSequences(FileFormat.Json, 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 pIndicator.setProgressBar(MessageManager.formatMessage(
166 "info.error_creating_file", "HTML"), pSessionId);
171 public String getOutputFile() throws NoFileSelectedException
173 String selectedFile = null;
174 if (pIndicator != null && !headless)
176 pIndicator.setProgressBar(MessageManager.formatMessage(
177 "status.waiting_for_user_to_select_output_file", "HTML"),
181 JalviewFileChooser jvFileChooser = new JalviewFileChooser(
182 Cache.getProperty("LAST_DIRECTORY"), ImageMaker.HTML_EXTENSION,
183 ImageMaker.HTML_EXTENSION, ImageMaker.HTML_EXTENSION);
184 jvFileChooser.setFileView(new JalviewFileView());
186 jvFileChooser.setDialogTitle(MessageManager
187 .getString("label.save_as_biojs_html"));
188 jvFileChooser.setToolTipText(MessageManager.getString("action.save"));
190 int fileChooserOpt = jvFileChooser.showSaveDialog(null);
191 if (fileChooserOpt == JalviewFileChooser.APPROVE_OPTION)
193 Cache.setProperty("LAST_DIRECTORY", jvFileChooser
194 .getSelectedFile().getParent());
195 selectedFile = jvFileChooser.getSelectedFile().getPath();
199 pIndicator.setProgressBar(MessageManager.formatMessage(
200 "status.cancelled_image_export_operation", "BioJS"),
202 throw new NoFileSelectedException("No file was selected.");
207 public static String getBioJsTemplateAsString() throws IOException
209 InputStreamReader isReader = null;
210 BufferedReader buffReader = null;
211 StringBuilder sb = new StringBuilder();
212 Objects.requireNonNull(getCurrentBJSTemplateFile(),
213 "BioJsTemplate File not initialized!");
214 @SuppressWarnings("deprecation")
215 URL url = getCurrentBJSTemplateFile().toURL();
220 isReader = new InputStreamReader(url.openStream());
221 buffReader = new BufferedReader(isReader);
223 String lineSeparator = System.getProperty("line.separator");
224 while ((line = buffReader.readLine()) != null)
226 sb.append(line).append(lineSeparator);
229 } catch (Exception ex)
231 ex.printStackTrace();
234 if (isReader != null)
239 if (buffReader != null)
245 return sb.toString();
248 public static void refreshBioJSVersionsInfo(String dirName)
249 throws URISyntaxException
251 File directory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
252 Objects.requireNonNull(dirName, "dirName MUST not be null!");
253 Objects.requireNonNull(directory, "directory MUST not be null!");
254 TreeMap<String, File> versionFileMap = new TreeMap<String, File>();
256 for (File file : directory.listFiles())
260 String fileName = file.getName().substring(0,
261 file.getName().lastIndexOf("."));
262 String fileMeta[] = fileName.split("_");
263 if (fileMeta.length > 2)
265 setCurrentBJSTemplateFile(file);
266 versionFileMap.put(fileMeta[2], file);
268 else if (fileMeta.length > 1)
270 versionFileMap.put(fileMeta[1], file);
274 if (getCurrentBJSTemplateFile() == null && versionFileMap.size() > 0)
276 setCurrentBJSTemplateFile(versionFileMap.lastEntry().getValue());
278 setBioJsMSAVersions(versionFileMap);
281 public static void updateBioJS()
283 Thread updateThread = new Thread()
290 String gitRepoPkgJson = getURLContentAsString(BJS_TEMPLATE_GIT_REPO);
291 if (gitRepoPkgJson != null)
293 BioJSRepositoryPojo release = new BioJSRepositoryPojo(
295 syncUpdates(BJS_TEMPLATES_LOCAL_DIRECTORY, release);
296 refreshBioJSVersionsInfo(BJS_TEMPLATES_LOCAL_DIRECTORY);
298 } catch (URISyntaxException e)
304 updateThread.start();
308 public static void syncUpdates(String localDir, BioJSRepositoryPojo repo)
310 for (BioJSReleasePojo bjsRelease : repo.getReleases())
312 String releaseUrl = bjsRelease.getUrl();
313 String releaseVersion = bjsRelease.getVersion();
314 String releaseFile = "BioJsMSA_" + releaseVersion + ".txt";
315 if (releaseVersion.equals(repo.getLatestReleaseVersion()))
317 releaseFile = "Latest_BioJsMSA_" + releaseVersion + ".txt";
320 File biojsDirectory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
321 if (!biojsDirectory.exists())
323 if (!biojsDirectory.mkdirs())
325 System.out.println("Couldn't create local directory : "
326 + BJS_TEMPLATES_LOCAL_DIRECTORY);
331 File file = new File(BJS_TEMPLATES_LOCAL_DIRECTORY + releaseFile);
335 PrintWriter out = null;
338 out = new java.io.PrintWriter(new java.io.FileWriter(file));
339 out.print(getURLContentAsString(releaseUrl));
340 } catch (IOException e)
356 public static String getURLContentAsString(String url)
357 throws OutOfMemoryError
359 StringBuilder responseStrBuilder = null;
360 InputStream is = null;
363 URL resourceUrl = new URL(url);
364 is = new BufferedInputStream(resourceUrl.openStream());
365 BufferedReader br = new BufferedReader(new InputStreamReader(is));
366 responseStrBuilder = new StringBuilder();
369 while ((lineContent = br.readLine()) != null)
371 responseStrBuilder.append(lineContent).append("\n");
373 } catch (OutOfMemoryError er)
375 er.printStackTrace();
376 } catch (Exception ex)
378 ex.printStackTrace();
386 } catch (IOException e)
392 return responseStrBuilder == null ? null : responseStrBuilder
396 public static File getCurrentBJSTemplateFile()
398 return currentBJSTemplateFile;
401 public static void setCurrentBJSTemplateFile(File currentBJSTemplateFile)
403 BioJsHTMLOutput.currentBJSTemplateFile = currentBJSTemplateFile;
406 public static TreeMap<String, File> getBioJsMSAVersions()
408 return bioJsMSAVersions;
411 public static void setBioJsMSAVersions(
412 TreeMap<String, File> bioJsMSAVersions)
414 BioJsHTMLOutput.bioJsMSAVersions = bioJsMSAVersions;