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.AlignFrame;
28 import jalview.gui.IProgressIndicator;
29 import jalview.gui.OOMWarning;
30 import jalview.json.binding.biojs.BioJSReleasePojo;
31 import jalview.json.binding.biojs.BioJSRepositoryPojo;
32 import jalview.util.MessageManager;
34 import java.io.BufferedInputStream;
35 import java.io.BufferedReader;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.InputStreamReader;
40 import java.io.PrintWriter;
41 import java.net.URISyntaxException;
43 import java.util.Objects;
44 import java.util.TreeMap;
46 public class BioJsHTMLOutput
48 private AlignmentViewPanel ap;
50 private long pSessionId;
52 private IProgressIndicator pIndicator;
54 private boolean headless;
56 private static File currentBJSTemplateFile;
58 private static TreeMap<String, File> bioJsMSAVersions;
60 public static final String DEFAULT_DIR = System.getProperty("user.home")
61 + File.separatorChar + ".biojs_templates" + File.separatorChar;
63 public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = jalview.bin.Cache
64 .getDefault("biojs_template_directory", DEFAULT_DIR);
66 public static final String BJS_TEMPLATE_GIT_REPO = jalview.bin.Cache
68 "biojs_template_git_repo",
69 "https://raw.githubusercontent.com/jalview/exporter-templates/master/biojs/package.json");
71 public BioJsHTMLOutput(AlignmentViewPanel ap,
72 IProgressIndicator pIndicator)
77 this.pSessionId = System.currentTimeMillis();
78 this.pIndicator = pIndicator;
79 this.headless = (System.getProperty("java.awt.headless") != null && System
80 .getProperty("java.awt.headless").equals("true"));
84 public void exportJalviewAlignmentAsBioJsHtmlFile()
86 String outputFile = null;
89 outputFile = getOutputFile();
90 AlignExportSettingI exportSettings = new AlignExportSettingI()
93 public boolean isExportHiddenSequences()
99 public boolean isExportHiddenColumns()
105 public boolean isExportAnnotations()
111 public boolean isExportFeatures()
117 public boolean isExportGroups()
123 public boolean isCancelled()
129 AlignmentExportData exportData = AlignFrame
130 .getAlignmentForExport(FileFormat.Json,
131 ap.getAlignViewport(), exportSettings);
132 String bioJSON = new FormatAdapter(ap, exportData.getSettings())
133 .formatSequences(FileFormat.Json, exportData
134 .getAlignment(), exportData.getOmitHidden(),
135 exportData.getStartEndPostions(), ap
136 .getAlignViewport().getColumnSelection());
138 String bioJSTemplateString = getBioJsTemplateAsString();
139 String generatedBioJsWithJalviewAlignmentAsJson = bioJSTemplateString
140 .replaceAll("#sequenceData#", bioJSON).toString();
142 PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(
144 out.print(generatedBioJsWithJalviewAlignmentAsJson);
147 jalview.util.BrowserLauncher.openURL("file:///" + outputFile);
148 if (pIndicator != null && !headless)
150 pIndicator.setProgressBar(MessageManager.formatMessage(
151 "status.export_complete", "BioJS"), pSessionId);
153 } catch (NoFileSelectedException ex)
155 // do noting if no file was selected
156 } catch (OutOfMemoryError err)
158 System.out.println("########################\n" + "OUT OF MEMORY "
159 + outputFile + "\n" + "########################");
160 new OOMWarning("Creating Image for " + outputFile, err);
161 } catch (Exception e)
163 pIndicator.setProgressBar(MessageManager.formatMessage(
164 "info.error_creating_file", "HTML"), pSessionId);
169 public String getOutputFile() throws NoFileSelectedException
171 String selectedFile = null;
172 if (pIndicator != null && !headless)
174 pIndicator.setProgressBar(MessageManager.formatMessage(
175 "status.waiting_for_user_to_select_output_file", "HTML"),
179 JalviewFileChooser jvFileChooser = new JalviewFileChooser(
180 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
181 new String[] { "html" }, new String[] { "HTML files" },
183 jvFileChooser.setFileView(new JalviewFileView());
185 jvFileChooser.setDialogTitle(MessageManager
186 .getString("label.save_as_biojs_html"));
187 jvFileChooser.setToolTipText(MessageManager.getString("action.save"));
189 int fileChooserOpt = jvFileChooser.showSaveDialog(null);
190 if (fileChooserOpt == JalviewFileChooser.APPROVE_OPTION)
192 jalview.bin.Cache.setProperty("LAST_DIRECTORY", jvFileChooser
193 .getSelectedFile().getParent());
194 selectedFile = jvFileChooser.getSelectedFile().getPath();
198 pIndicator.setProgressBar(MessageManager.formatMessage(
199 "status.cancelled_image_export_operation", "BioJS"),
201 throw new NoFileSelectedException("No file was selected.");
206 public static String getBioJsTemplateAsString() throws IOException
208 InputStreamReader isReader = null;
209 BufferedReader buffReader = null;
210 StringBuilder sb = new StringBuilder();
211 Objects.requireNonNull(getCurrentBJSTemplateFile(),
212 "BioJsTemplate File not initialized!");
213 @SuppressWarnings("deprecation")
214 URL url = getCurrentBJSTemplateFile().toURL();
219 isReader = new InputStreamReader(url.openStream());
220 buffReader = new BufferedReader(isReader);
222 String lineSeparator = System.getProperty("line.separator");
223 while ((line = buffReader.readLine()) != null)
225 sb.append(line).append(lineSeparator);
228 } catch (Exception ex)
230 ex.printStackTrace();
233 if (isReader != null)
238 if (buffReader != null)
244 return sb.toString();
247 public static void refreshBioJSVersionsInfo(String dirName)
248 throws URISyntaxException
250 File directory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
251 Objects.requireNonNull(dirName, "dirName MUST not be null!");
252 Objects.requireNonNull(directory, "directory MUST not be null!");
253 TreeMap<String, File> versionFileMap = new TreeMap<String, File>();
255 for (File file : directory.listFiles())
259 String fileName = file.getName().substring(0,
260 file.getName().lastIndexOf("."));
261 String fileMeta[] = fileName.split("_");
262 if (fileMeta.length > 2)
264 setCurrentBJSTemplateFile(file);
265 versionFileMap.put(fileMeta[2], file);
267 else if (fileMeta.length > 1)
269 versionFileMap.put(fileMeta[1], file);
273 if (getCurrentBJSTemplateFile() == null && versionFileMap.size() > 0)
275 setCurrentBJSTemplateFile(versionFileMap.lastEntry().getValue());
277 setBioJsMSAVersions(versionFileMap);
280 public static void updateBioJS()
282 Thread updateThread = new Thread()
289 String gitRepoPkgJson = getURLContentAsString(BJS_TEMPLATE_GIT_REPO);
290 if (gitRepoPkgJson != null)
292 BioJSRepositoryPojo release = new BioJSRepositoryPojo(
294 syncUpdates(BJS_TEMPLATES_LOCAL_DIRECTORY, release);
295 refreshBioJSVersionsInfo(BJS_TEMPLATES_LOCAL_DIRECTORY);
297 } catch (URISyntaxException e)
303 updateThread.start();
307 public static void syncUpdates(String localDir, BioJSRepositoryPojo repo)
309 for (BioJSReleasePojo bjsRelease : repo.getReleases())
311 String releaseUrl = bjsRelease.getUrl();
312 String releaseVersion = bjsRelease.getVersion();
313 String releaseFile = "BioJsMSA_" + releaseVersion + ".txt";
314 if (releaseVersion.equals(repo.getLatestReleaseVersion()))
316 releaseFile = "Latest_BioJsMSA_" + releaseVersion + ".txt";
319 File biojsDirectory = new File(BJS_TEMPLATES_LOCAL_DIRECTORY);
320 if (!biojsDirectory.exists())
322 if (!biojsDirectory.mkdirs())
324 System.out.println("Couldn't create local directory : "
325 + BJS_TEMPLATES_LOCAL_DIRECTORY);
330 File file = new File(BJS_TEMPLATES_LOCAL_DIRECTORY + releaseFile);
334 PrintWriter out = null;
337 out = new java.io.PrintWriter(new java.io.FileWriter(file));
338 out.print(getURLContentAsString(releaseUrl));
339 } catch (IOException e)
355 public static String getURLContentAsString(String url)
356 throws OutOfMemoryError
358 StringBuilder responseStrBuilder = null;
359 InputStream is = null;
362 URL resourceUrl = new URL(url);
363 is = new BufferedInputStream(resourceUrl.openStream());
364 BufferedReader br = new BufferedReader(new InputStreamReader(is));
365 responseStrBuilder = new StringBuilder();
368 while ((lineContent = br.readLine()) != null)
370 responseStrBuilder.append(lineContent).append("\n");
372 } catch (OutOfMemoryError er)
374 er.printStackTrace();
375 } catch (Exception ex)
377 ex.printStackTrace();
385 } catch (IOException e)
391 return responseStrBuilder == null ? null : responseStrBuilder
395 public static File getCurrentBJSTemplateFile()
397 return currentBJSTemplateFile;
400 public static void setCurrentBJSTemplateFile(File currentBJSTemplateFile)
402 BioJsHTMLOutput.currentBJSTemplateFile = currentBJSTemplateFile;
405 public static TreeMap<String, File> getBioJsMSAVersions()
407 return bioJsMSAVersions;
410 public static void setBioJsMSAVersions(
411 TreeMap<String, File> bioJsMSAVersions)
413 BioJsHTMLOutput.bioJsMSAVersions = bioJsMSAVersions;