List of usage examples for org.jdom2 Element setAttribute
public Element setAttribute(final String name, final String value)
This sets an attribute value for this element.
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.elements.token.Mtext.java
License:Open Source License
@Override public Element render(FormulaElement parent, List<FormulaElement> siblings) { Element span = new Element("span"); span.setAttribute("class", "mtext"); span.setText(value.trim());// w w w. j av a 2s . c om return span; }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.FormulaConverter.java
License:Open Source License
/** * Parses a JDOM HTML Document for formula entries, sets an id to refer to it in the future. * * @param document JDOM HTML Document to parse * @return Map of formulas, keys: given id, values: corresponding latex formula code from the document *//* w w w. j a va 2s . co m*/ public Map<Integer, String> extractFormulas(Document document) { Map<Integer, String> formulas = new HashMap<>(); List<Element> foundElements = xpath.evaluate(document); if (foundElements.size() > 0) { int id = 0; for (Element element : foundElements) { formulas.put(id, element.getValue()); // mark formula number element.setAttribute("id", FORMULA_ID_PREFIX + id); id++; } } return formulas; }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.FormulaConverter.java
License:Open Source License
/** * Replaces all formulas with the html representation of the mapped formula objects * * @param doc JDOM Document where to replace the formulas * @param formulaMap Map of the indexed Formula Objects * @return JDOM Document with replaced formulas *//*w w w . j a v a 2 s . c om*/ public Document replaceFormulas(Document doc, Map<Integer, Formula> formulaMap) { List<Element> foundFormulas = xpath.evaluate(doc); if (foundFormulas.size() > 0) { Map<String, Element> formulaMarkupMap = new HashMap<>(); // Initialize markup map for (Element element : foundFormulas) { formulaMarkupMap.put(element.getAttribute("id").getValue(), element); } // Replace all found formulas Iterator<Integer> formulaIterator = formulaMap.keySet().iterator(); while (formulaIterator.hasNext()) { Integer id = formulaIterator.next(); Element formulaMarkupRoot = formulaMarkupMap.get(FORMULA_ID_PREFIX + id); Formula formula = formulaMap.get(id); formulaMarkupRoot.removeAttribute("class"); formulaMarkupRoot.removeContent(); formulaMarkupRoot.setName("div"); Element div = (Element) formulaMarkupRoot.getParent(); div.setName("div"); div.setAttribute("class", "formula"); // Potentially there's text inside the paragraph... List<Text> texts = div.getContent(Filters.textOnly()); if (texts.isEmpty() == false) { String textString = ""; for (Text text : texts) { textString += text.getText(); } Element textSpan = new Element("span"); textSpan.setAttribute("class", "text"); textSpan.setText(textString); div.addContent(textSpan); List<Content> content = div.getContent(); content.removeAll(texts); } if (generateDebugMarkup) { div.setAttribute("style", "border: 1px solid black;"); // Header Element h4 = new Element("h4"); h4.setText("DEBUG - Formula #" + formula.getId()); div.addContent(h4); // Render LaTeX source Element latexPre = new Element("pre"); latexPre.setAttribute("class", "debug-latex"); latexPre.setText(formula.getLatexCode()); div.addContent(latexPre); // Render MathML markup Element mathmlPre = new Element("pre"); mathmlPre.setAttribute("class", "debug-mathml"); mathmlPre.setText(formula.getMathMl()); div.addContent(mathmlPre); // Render HTML Markup Element htmlPre = new Element("pre"); htmlPre.setAttribute("class", "debug-html"); XMLOutputter xmlOutputter = new XMLOutputter(); xmlOutputter.setFormat(Format.getRawFormat()); htmlPre.setText(xmlOutputter.outputString(formula.getHtml())); div.addContent(htmlPre); } // Set formula into formulaMarkupRoot.addContent(formula.getHtml()); } } return doc; }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.ImageFormulaConverter.java
License:Open Source License
/** * Takes a single LaTeX formula and converts it to an image in PNG format * * @param id formula's number inside the document * @param latexFormula LaTeX formula/* www. j a va 2 s. co m*/ * @return Formula object with resulting image file path set */ @Override public Formula parse(int id, String latexFormula) { Formula formula = super.parseToMathML(id, latexFormula); logger.debug("parse() entered..."); if (formula.isInvalid() == false) { try { final org.w3c.dom.Document doc = MathMLParserSupport.parseString(formula.getMathMl()); final File outFile = Files.createTempFile(tempDirPath, "formula", ".png").toFile(); formula.setImageFilePath(outFile.toPath()); // Generate Html Image tag Element imageTag = new Element("img"); imageTag.setAttribute("src", formula.getImageFilePath().getFileName().toString()); imageTag.setAttribute("alt", FORMULA_ID_PREFIX + formula.getId()); formula.setHtml(imageTag); final MutableLayoutContext params = new LayoutContextImpl( LayoutContextImpl.getDefaultLayoutContext()); params.setParameter(Parameter.MATHSIZE, 25f); // convert to image net.sourceforge.jeuclid.converter.Converter imageConverter = net.sourceforge.jeuclid.converter.Converter .getInstance(); imageConverter.convert(doc, outFile, "image/png", params); logger.debug("Image file created at: " + outFile.toPath().toAbsolutePath().toString()); } catch (SAXException e1) { logger.error(e1.getMessage(), e1); } catch (ParserConfigurationException e2) { logger.error(e2.getMessage(), e2); } catch (IOException e3) { logger.error(e3.getMessage(), e3); } } else { formula.setHtml(renderInvalidFormulaSource(formula)); } return formula; }
From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java
License:Apache License
/** * Create/update the schema.xml file for the given core according to the core definition. * * @param engine the engine configuration */// w w w.jav a 2 s . co m private void createSchemaXml(SolrCoreConfiguration engine) throws MarmottaException { log.info("generating schema.xml for search program {}", engine.getName()); SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING); File schemaTemplate = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "schema-template.xml"); File schemaFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "schema.xml"); try { Document doc = parser.build(schemaTemplate); Element schemaNode = doc.getRootElement(); Element fieldsNode = schemaNode.getChild("fields"); if (!schemaNode.getName().equals("schema") || fieldsNode == null) throw new MarmottaException(schemaTemplate + " is an invalid SOLR schema file"); schemaNode.setAttribute("name", engine.getName()); Program<Value> program = engine.getProgram(); for (FieldMapping<?, Value> fieldMapping : program.getFields()) { String fieldName = fieldMapping.getFieldName(); String solrType = null; try { solrType = solrProgramService.getSolrFieldType(fieldMapping.getFieldType().toString()); } catch (MarmottaException e) { solrType = null; } if (solrType == null) { log.error("field {} has an invalid field type; ignoring field definition", fieldName); continue; } Element fieldElement = new Element("field"); fieldElement.setAttribute("name", fieldName); fieldElement.setAttribute("type", solrType); // Set the default properties fieldElement.setAttribute("stored", "true"); fieldElement.setAttribute("indexed", "true"); fieldElement.setAttribute("multiValued", "true"); // FIXME: Hardcoded Stuff! if (solrType.equals("location")) { fieldElement.setAttribute("indexed", "true"); fieldElement.setAttribute("multiValued", "false"); } // Handle extra field configuration final Map<String, String> fieldConfig = fieldMapping.getFieldConfig(); if (fieldConfig != null) { for (Map.Entry<String, String> attr : fieldConfig.entrySet()) { if (SOLR_FIELD_OPTIONS.contains(attr.getKey())) { fieldElement.setAttribute(attr.getKey(), attr.getValue()); } } } fieldsNode.addContent(fieldElement); if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_COPY_FIELD_OPTION)) { String[] copyFields = fieldConfig.get(SOLR_COPY_FIELD_OPTION).split("\\s*,\\s*"); for (String copyField : copyFields) { if (copyField.trim().length() > 0) { // ignore 'empty' fields Element copyElement = new Element("copyField"); copyElement.setAttribute("source", fieldName); copyElement.setAttribute("dest", copyField.trim()); schemaNode.addContent(copyElement); } } } else { Element copyElement = new Element("copyField"); copyElement.setAttribute("source", fieldName); copyElement.setAttribute("dest", "lmf.text_all"); schemaNode.addContent(copyElement); } //for suggestions, copy all fields to lmf.spellcheck (used for spellcheck and querying); //only facet is a supported type at the moment if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) { String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION); if (suggestionType.equals("facet")) { Element copyElement = new Element("copyField"); copyElement.setAttribute("source", fieldName); copyElement.setAttribute("dest", "lmf.spellcheck"); schemaNode.addContent(copyElement); } else { log.error("suggestionType " + suggestionType + " not supported"); } } } if (!schemaFile.exists() || schemaFile.canWrite()) { FileOutputStream out = new FileOutputStream(schemaFile); XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent(" ")); xo.output(doc, out); out.close(); } else { log.error("schema file {} is not writable", schemaFile); } } catch (JDOMException e) { throw new MarmottaException("parse error while parsing SOLR schema template file " + schemaTemplate, e); } catch (IOException e) { throw new MarmottaException("I/O error while parsing SOLR schema template file " + schemaTemplate, e); } }
From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java
License:Apache License
/** * Create/update the solrconfig.xml file for the given core according to the core configuration. * * @param engine the solr core configuration *//* www.j a v a 2 s. com*/ private void createSolrConfigXml(SolrCoreConfiguration engine) throws MarmottaException { File configTemplate = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "solrconfig-template.xml"); File configFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "solrconfig.xml"); try { SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING); Document solrConfig = parser.build(configTemplate); FileOutputStream out = new FileOutputStream(configFile); // Configure suggestion service: add fields to suggestion handler Program<Value> program = engine.getProgram(); for (Element handler : solrConfig.getRootElement().getChildren("requestHandler")) { if (handler.getAttribute("class").getValue().equals(SuggestionRequestHandler.class.getName())) { for (Element lst : handler.getChildren("lst")) { if (lst.getAttribute("name").getValue().equals("defaults")) { //set suggestion fields for (FieldMapping<?, Value> fieldMapping : program.getFields()) { String fieldName = fieldMapping.getFieldName(); final Map<String, String> fieldConfig = fieldMapping.getFieldConfig(); if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) { String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION); if (suggestionType.equals("facet")) { Element field_elem = new Element("str"); field_elem.setAttribute("name", SuggestionRequestParams.SUGGESTION_FIELD); field_elem.setText(fieldName); lst.addContent(field_elem); } else { log.error("suggestionType " + suggestionType + " not supported"); } } } } } } } XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent(" ")); xo.output(solrConfig, out); out.close(); } catch (JDOMException e) { throw new MarmottaException("parse error while parsing SOLR schema template file " + configTemplate, e); } catch (IOException e) { throw new MarmottaException("I/O error while parsing SOLR schema template file " + configTemplate, e); } }
From source file:ataraxis.passwordmanager.XMLHandler.java
License:Open Source License
/** * Create a new account-Element// w w w. ja va 2s. c o m * * @param entry the AccountEntry * @throws JDOMException by Errors with JDOM * @throws EntryDoesNotExistException */ private void createAccountElement(AccountEntry entry) throws JDOMException, EntryDoesNotExistException { // create Element sub-structure Element newAccountElement = new Element("account"); newAccountElement.setAttribute("id", entry.getId()); Element newName = new Element("name"); newName.setText(entry.getName()); Element newPass = new Element("password"); newPass.setText(entry.getPassword()); Element newLink = new Element("link"); newLink.setText(entry.getLink()); Element newComment = new Element("comment"); newComment.setText(entry.getComment()); // put newPWElement together newAccountElement.addContent(newName); newAccountElement.addContent(newPass); newAccountElement.addContent(newLink); newAccountElement.addContent(newComment); // add parent if (entry.getParentEntry() == null) { s_rootElement.addContent(newAccountElement); } else { try { Element parrent = getElement(entry.getParentEntry().getId()); parrent.addContent(newAccountElement); } catch (JDOMException e) { logger.fatal(e); throw new EntryDoesNotExistException("No such parent"); } } }
From source file:ataraxis.passwordmanager.XMLHandler.java
License:Open Source License
/** * Create a group-Element//from ww w.j av a 2 s . co m * * @param GroupName the Name of the Group (== Element ID) */ private void createGroupElement(String GroupName) { // Create Element Element newGroupElement = new Element("group"); newGroupElement.setAttribute("id", GroupName); // add to root s_doc.getRootElement().addContent(newGroupElement); }
From source file:ataraxis.passwordmanager.XMLHandler.java
License:Open Source License
/** * Rename a Entry.// www. jav a 2 s. c om * * @param currentName Name of an existing entry * @param newName new Name * @throws EntryDoesNotExistException if currentName does not exist * @throws EntryAlreadyExistException if new Name allready exist * @throws StorageException when save fails */ public void renameElementId(String currentName, String newName) throws EntryDoesNotExistException, EntryAlreadyExistException, StorageException { if (currentName == null || newName == null || currentName.trim().equals("") || newName.trim().equals("")) { throw new IllegalArgumentException("entry can not be null"); } if (!existID(currentName)) { throw new EntryDoesNotExistException("entry not found " + currentName); } if (existID(newName)) { throw new EntryAlreadyExistException("entry exist already " + newName); } try { Element element = getElement(currentName); element.setAttribute("id", newName); savePasswords(); } catch (JDOMException e) { logger.fatal(e.getMessage()); throw new StorageException(e); } }
From source file:backtesting.BackTesterNinety.java
private static void SaveSettings(BTSettings settings) { BufferedWriter output = null; try {//from www . j a v a 2s . c o m Element rootElement = new Element("Settings"); Document doc = new Document(rootElement); rootElement.setAttribute("start", settings.startDate.toString()); rootElement.setAttribute("end", settings.endDate.toString()); rootElement.setAttribute("capital", Double.toString(settings.capital)); rootElement.setAttribute("leverage", Double.toString(settings.leverage)); rootElement.setAttribute("reinvest", Boolean.toString(settings.reinvest)); XMLOutputter xmlOutput = new XMLOutputter(); File fileSettings = new File("backtest/cache/_settings.xml"); fileSettings.createNewFile(); FileOutputStream oFile = new FileOutputStream(fileSettings, false); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, oFile); } catch (IOException ex) { Logger.getLogger(BackTesterNinety.class.getName()).log(Level.SEVERE, null, ex); } finally { if (output != null) { try { output.close(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } }