Search in sources :

Example 1 with DepictionGenerator

use of org.openscience.cdk.depict.DepictionGenerator in project MassBank-web by MassBank.

the class Inspector method main.

public static void main(String[] arguments) throws Exception {
    if (arguments.length == 2) {
        String input = FileUtils.readFileToString(new File(arguments[0]), StandardCharsets.UTF_8);
        Validator.hasNonStandardChars(input);
        Set<String> config = new HashSet<String>();
        config.add("legacy");
        Record record = Validator.validate(input, "", config);
        if (record == null) {
            logger.error("Error in " + arguments[0] + ". Exiting...");
            System.exit(1);
        } else {
            logger.trace("Validation passed for " + arguments[0] + ".");
        }
        String accession = record.ACCESSION();
        String shortname = record.RECORD_TITLE().get(0) + " Mass Spectrum";
        // find InChIKey in CH_LINK
        String inchikey = record.CH_LINK().get("INCHIKEY");
        String keywords = accession + ", " + shortname + ", " + (inchikey != null ? inchikey + ", " : "") + "mass spectrum, MassBank record, mass spectrometry, mass spectral library";
        String description = "This MassBank Record with Accession " + accession + " contains the " + record.AC_MASS_SPECTROMETRY_MS_TYPE() + " mass spectrum" + " of '" + record.RECORD_TITLE().get(0) + "'" + (inchikey != null ? " with the InChIKey '" + inchikey + "'" : "") + ".";
        String recordstring = record.createRecordString();
        String structureddata = record.createStructuredData();
        IAtomContainer mol = record.CH_SMILES_obj();
        String svg = new DepictionGenerator().withAtomColors().depict(mol).toSvgStr(Depiction.UNITS_PX);
        String css = "<style>\n" + getResourceFileAsString("massbank.css") + "\n" + getResourceFileAsString("Common.css") + "\n" + getResourceFileAsString("st.css") + "\n" + "</style>\n";
        String js = "<script type=\"text/javascript\">\n" + getResourceFileAsString("Common.js") + "\n" + getResourceFileAsString("d3.v3.min.js") + "\n" + getResourceFileAsString("st.min.js") + "\n" + getResourceFileAsString("massbank_specktackle.js") + "\n" + "</script>\n";
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + "	<title>" + shortname + "</title>\n" + "	<meta charset=\"UTF-8\">\n" + "	<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\">\n" + // "	<link rel=\"stylesheet\" href=\"https://www.w3schools.com/lib/w3-theme-grey.css\">\n" +
        "	<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n" + "	<!-- 	hier anpassen -->\n" + "	<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" + "	<meta name=\"variableMeasured\" content=\"m/z\">\n" + structureddata + "\n" + css + "\n" + "</head>\n");
        sb.append("<body class=\"w3-theme-gradient\">\n" + js + "\n" + "  	<header class=\"w3-container w3-top w3-text-dark-grey w3-grey\">\n" + "		<div class=\"w3-bar\">\n" + "			<div class=\"w3-left\">\n" + "				<h1>\n" + "					<b>MassBank Record: " + accession + "</b>\n" + "				</h1>\n" + "			</div>\n" + "	<div class=\"w3-padding\">\n" + "		<h3><b>" + record.RECORD_TITLE1() + "</b></h3>\n" + "			<div class=\"w3-row w3-padding-small\">\n" + "				<div class=\"w3-twothird w3-text-grey w3-small w3-padding-small\">\n" + "					Mass Spectrum\n" + "					<div id=\"spectrum_canvas\" peaks=\"" + record.createPeakListForSpectrumViewer() + "\" style=\"height:200px; width:600px; max-width:100%; background-color:white\"></div>\n" + "				</div>\n" + "				<div class=\"w3-third w3-text-grey w3-small w3-padding-small\">\n" + "					Chemical Structure<br>\n" + svg + "\n" + "				</div>\n" + "			</div>\n" + "	</div>\n" + "	<div class=\"monospace w3-padding w3-small\" style=\"height:auto;margin:auto\">\n" + "		<hr>\n" + recordstring + "\n" + "	</div>\n" + "</body>\n" + "</html>");
        File file = new File(arguments[1]);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(sb.toString());
        }
    } else {
        logger.error("Input and output file required. Exiting...");
    }
}
Also used : IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) FileWriter(java.io.FileWriter) Record(massbank.Record) File(java.io.File) HashSet(java.util.HashSet) DepictionGenerator(org.openscience.cdk.depict.DepictionGenerator) BufferedWriter(java.io.BufferedWriter)

Example 2 with DepictionGenerator

use of org.openscience.cdk.depict.DepictionGenerator in project MassBank-web by MassBank.

the class RecordDisplay method doGet.

// @id  https://massbank.eu/MassBank/RecordDisplay.jsp?id=WA001202&dsn=Waters
// measurementTechnique LC-ESI-Q
// "biologicalRole": [
// {
// "@type": "DefinedTerm",
// "@id": "http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#C66892",
// "inDefinedTermSet":
// {
// "@type":"DefinedTermSet",
// "@id":"http://data.bioontology.org/ontologies/NCIT/submissions/69/download?apikey=8b5b7825-538d-40e0-9e9e-5ab9274a9aeb",
// "name": "National Cancer Institute Thesaurus"
// },
// "termCode": "C66892",
// "name": "natural product",
// "url": "http://bioportal.bioontology.org/ontologies/NCIT?p=classes&conceptid=http%3A%2F%2Fncicb.nci.nih.gov%2Fxml%2Fowl%2FEVS%2FThesaurus.owl%23C66892"
// }
// ]
// }
// case "AUTHORS":
// //sb.append(tag + ": " + value + "\n");
// String[] authorTokens	= value.split(", ");
// 
// // check which tokens are authors
// int lastAuthorIdx	= -1;
// for(int i = 0; i < authorTokens.length; i++){
// // check if string is author like 'Akimoto AV'
// boolean isAuthor	= authorTokens[i].matches("\\w+ \\w+");
// if(isAuthor){
// // 2nd word is initials?
// String[] initials	= authorTokens[i].split(" ")[1].split("");
// for(int j = 0; j < initials.length; j++)
// if(!Character.isUpperCase(initials[j].toCharArray()[0])){
// isAuthor	= false;
// break;
// }
// }
// if(isAuthor){
// lastAuthorIdx	= i;
// }
// }
// 
// // create affiliation
// int numberOfAuthors	= lastAuthorIdx + 1;
// String affiliation	= String.join(", ", Arrays.copyOfRange(authorTokens, numberOfAuthors, authorTokens.length));
// 
// // create authors
// String[] authors	= new String[numberOfAuthors];
// for(int i = 0; i < numberOfAuthors; i++)
// authors[i]	=
// "<span property=\"schema:author\" typeof=\"schema:Person\">" +
// "<span property=\"schema:name\">" + authorTokens[i] + "</span>" +
// //((affiliation.length() > 0) ?"<span property=\"schema:affiliation\" style=\"visibility:hidden\">" + affiliation + "</span>" : "") +
// ((affiliation.length() > 0) ?"<span property=\"schema:affiliation\" style=\"display:none\">" + affiliation + "</span>" : "") +
// "</span>";
// 
// // paste
// sb.append(tag + ": ");
// sb.append(String.join(", ", authors));
// if(affiliation.length() > 0)
// sb.append(", " + affiliation);
// sb.append("\n");
// break;
// case "CH$CDK_DEPICT_SMILES":
// case "CH$CDK_DEPICT_GENERIC_SMILES":
// case "CH$CDK_DEPICT_STRUCTURE_SMILES":
// ClickablePreviewImageData clickablePreviewImageData2	= StructureToSvgStringGenerator.createClickablePreviewImage(
// tag, null, value,
// tmpFileFolder, tmpUrlFolder,
// 80, 200, 436
// );
// if(clickablePreviewImageData2 != null)
// sb.append(tag + ": " + clickablePreviewImageData2.getMediumClickablePreviewLink("CH$CDK_DEPICT_SMILES", value));
// else
// sb.append(tag + ": " + value + "\n");
// break;
// // AC$INSTRUMENT
// case "AC$INSTRUMENT_TYPE":
// // TODO property="schema:measurementTechnique"
// sb.append(tag + ": <span property=\"schema:measurementTechnique\">" + value + "</span>\n");
// instrumentType	= value;
// break;
// 
// if(recordTitle == null)
// recordTitle	= "NA";
// 
// String shortName	= recordTitle.split(";")[0].trim();
// 
// ClickablePreviewImageData clickablePreviewImageData	= StructureToSvgStringGenerator.createClickablePreviewImage(
// accession, inchi, smiles, tmpFileFolder, tmpUrlFolder,
// 80, 200, 436
// );
// String svgMedium	= null;
// if(clickablePreviewImageData != null)
// svgMedium	= clickablePreviewImageData.getMediumClickableImage();
// 
// // meta data
// String[] compoundClasses	= compoundClass.split("; ");
// String compoundClass2	= compoundClasses[0];
// if(compoundClass2.equals("NA") && compoundClasses.length > 1)	compoundClass2	= compoundClasses[1];
// 
// String description	=
// "This MassBank Record with Accession " + accession +
// " contains the " + msType + " mass spectrum" +
// " of '" + name + "'" +
// (inchiKey			!= null		? " with the InChIKey '" + inchiKey + "'"					: "") +
// (!compoundClass2.equals("N/A")	? " with the compound class '" + compoundClass2 + "'"	: "") +
// "." +
// " The mass spectrum was acquired on a " + instrumentType +
// //" with " + (ionization != null	? ionization											: "") +
// " with " + ionMode + " ionisation" +
// (fragmentation		!= null		? " using " + fragmentation + " fragmentation"			: "") +
// (collisionEnergy	!= null		? " with the collision energy '" + collisionEnergy + "'": "") +
// (collisionEnergy	!= null		? " at a resolution of " + resolution					: "") +
// (splash				!= null		? " and has the SPLASH '" + splash + "'"				: "") +
// ".";
// 
// // record
// String recordString	= sb.toString();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // preprocess request
    Record record = null;
    try {
        // get parameters
        String accession = null;
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = (String) request.getParameter(key);
            switch(key) {
                case "id":
                    accession = val;
                    break;
                default:
                    logger.warn("unused argument " + key + "=" + val);
            }
        }
        // error handling
        if ("".equals(accession))
            accession = null;
        if (accession == null) {
            String errormsg = "missing argument 'id'.";
            logger.error(errormsg);
            String redirectUrl = "/NoRecordPage" + "?error=" + errormsg;
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }
        // load record for display
        DatabaseManager dbMan = new DatabaseManager("MassBank");
        record = dbMan.getAccessionData(accession);
        dbMan.closeConnection();
        if (record == null) {
            String errormsg = "retrieval of '" + accession + "' from database failed";
            logger.error(errormsg);
            String redirectUrl = "/NoRecordPage" + "?id=" + accession + "&error=" + errormsg;
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }
        if (record.DEPRECATED()) {
            logger.trace("Show deprecated record " + accession + ".");
            String shortname = "DEPRECATED RECORD " + accession;
            request.setAttribute("short_name", shortname);
            request.setAttribute("description", shortname);
            request.setAttribute("accession", accession);
            request.setAttribute("isDeprecated", true);
            request.setAttribute("record_title", accession + " has been deprecated.");
            request.setAttribute("recordstring", "<pre>\nACCESSION: " + accession + "\nDEPRECATED: " + record.DEPRECATED_CONTENT() + "\n<pre>");
            request.setAttribute("author", "MassBank");
        } else {
            logger.trace("Show record " + accession + ".");
            String shortname = record.RECORD_TITLE().get(0) + " Mass Spectrum";
            request.setAttribute("short_name", shortname);
            // find InChIKey in CH_LINK
            String inchikey = record.CH_LINK().get("INCHIKEY");
            String description = "This MassBank Record with Accession " + accession + " contains the " + record.AC_MASS_SPECTROMETRY_MS_TYPE() + " mass spectrum" + " of '" + record.RECORD_TITLE().get(0) + "'" + (inchikey != null ? " with the InChIKey '" + inchikey + "'" : "") + // (splash				!= null		? " and has the SPLASH '" + splash + "'"				: "") +
            ".";
            request.setAttribute("description", description);
            String keywords = accession + ", " + shortname + ", " + (inchikey != null ? inchikey + ", " : "") + "mass spectrum, MassBank record, mass spectrometry, mass spectral library";
            request.setAttribute("keywords", keywords);
            String author = record.AUTHORS();
            request.setAttribute("author", author);
            String recordstring = record.createRecordString();
            String structureddata = record.createStructuredData();
            IAtomContainer mol = record.CH_SMILES_obj();
            String svg = new DepictionGenerator().withAtomColors().withMolTitle().withTitleColor(Color.black).depict(mol).toSvgStr(Depiction.UNITS_PX);
            // adjust svg to fit nicely in RecordDisplay page
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            factory.setValidating(false);
            factory.setFeature("http://xml.org/sax/features/namespaces", false);
            factory.setFeature("http://xml.org/sax/features/validation", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            Document svgDoc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(svg)));
            Element svgNode = (Element) svgDoc.getElementsByTagName("svg").item(0);
            NamedNodeMap attr = svgNode.getAttributes();
            attr.getNamedItem("width").setTextContent("100%");
            attr.getNamedItem("height").setTextContent("200px");
            svgNode.setAttribute("preserveAspectRatio", "xMinYMin meet");
            StringWriter writer = new StringWriter();
            TransformerFactory.newInstance().newTransformer().transform(new DOMSource(svgDoc), new StreamResult(writer));
            svg = writer.getBuffer().toString();
            request.setAttribute("peaklist", record.createPeakListData());
            request.setAttribute("accession", accession);
            request.setAttribute("record_title", record.RECORD_TITLE1());
            request.setAttribute("recordstring", recordstring);
            request.setAttribute("structureddata", structureddata);
            request.setAttribute("svg", svg);
        }
        request.getRequestDispatcher("/RecordDisplay.jsp").forward(request, response);
    } catch (Exception e) {
        throw new ServletException("Cannot load record", e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NamedNodeMap(org.w3c.dom.NamedNodeMap) DatabaseManager(massbank.db.DatabaseManager) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) DepictionGenerator(org.openscience.cdk.depict.DepictionGenerator) ServletException(javax.servlet.ServletException) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader)

Aggregations

DepictionGenerator (org.openscience.cdk.depict.DepictionGenerator)2 IAtomContainer (org.openscience.cdk.interfaces.IAtomContainer)2 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 StringReader (java.io.StringReader)1 StringWriter (java.io.StringWriter)1 HashSet (java.util.HashSet)1 ServletException (javax.servlet.ServletException)1 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)1 DOMSource (javax.xml.transform.dom.DOMSource)1 StreamResult (javax.xml.transform.stream.StreamResult)1 Record (massbank.Record)1 DatabaseManager (massbank.db.DatabaseManager)1 Document (org.w3c.dom.Document)1 Element (org.w3c.dom.Element)1 NamedNodeMap (org.w3c.dom.NamedNodeMap)1 InputSource (org.xml.sax.InputSource)1