List of usage examples for org.w3c.dom Document importNode
public Node importNode(Node importedNode, boolean deep) throws DOMException;
From source file:com.adaptris.core.services.jdbc.XmlPayloadTranslatorImpl.java
protected List<Element> createListFromResultSet(DocumentBuilder builder, Document doc, JdbcResultSet rs) throws SQLException { List<Element> results = new ArrayList<Element>(); List<String> elementNames = new ArrayList<>(); boolean firstRecord = true; for (JdbcResultRow row : rs.getRows()) { Element elementRow = doc.createElement(getColumnNameStyle().format(ELEMENT_NAME_ROW)); // let's go through and build up the element names we need once. if (firstRecord) { firstRecord = false;//from w w w . j ava2 s . c o m elementNames = createElementNames(row); } for (int i = 0; i < row.getFieldCount(); i++) { String columnName = row.getFieldName(i); String value = toString(row, i); Element node = doc.createElement(elementNames.get(i)); if (isXmlColumn(columnName)) { try { Document xmlColumn = null; xmlColumn = builder.parse(createInputSource(value)); node.appendChild(doc.importNode(xmlColumn.getFirstChild(), true)); } catch (Exception e) { if (isDisplayColumnErrors()) { log.warn("Failed to parse column {} as an XML Document, treating as text.", columnName); log.trace("Failed to parse column {} as an XML Document", columnName, e); } node.appendChild(createTextNode(doc, value, isCdataColumn(columnName))); } } else { node.appendChild(createTextNode(doc, value, isCdataColumn(columnName))); } elementRow.appendChild(node); } results.add(elementRow); } return results; }
From source file:com.sap.research.roo.addon.nwcloud.NWCloudOperationsImpl.java
/** * This function adds a given XML node to the build plugins section of "pom.xml". * /* www .j ava 2s . c o m*/ * @param pluginXML org.w3c.dom.Node storing the XML of the build plugin definition to add to "pom.xml" */ public void addRawBuildPlugin(Node pluginXML) { if (pluginXML != null) { // Read "pom.xml" and store reference to root Element Document document = XmlUtils.readXml(fileManager.getInputStream(this.getPOM().getPath())); Element root = document.getDocumentElement(); // Get build plugins Element in POM Element pluginsElement = XmlUtils.findFirstElement("/project/build/plugins", root); if (pluginsElement != null) { // Append the build plugin passed via parameter pluginXML to the build plugins element of POM Node plugin = document.importNode(pluginXML, true); pluginsElement.appendChild(plugin); // Fetch artifactID of added build plugin, create description of change, and update "pom.xml" NodeList childNodes = plugin.getChildNodes(); String addedArtifactID = null; for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child != null) { if (child.getNodeName() != null) { if (child.getNodeName().equals("artifactId")) { if (child.getTextContent() != null) { addedArtifactID = child.getTextContent(); } } } } } String descriptionOfChange = null; if (addedArtifactID != null) { descriptionOfChange = "Added raw build plugin: " + addedArtifactID; } else { descriptionOfChange = "Added a raw build plugin"; } fileManager.createOrUpdateTextFileIfRequired(this.getPOM().getPath(), XmlUtils.nodeToString(document), descriptionOfChange, true); } else { this.log.warning( "NWCloud-AddOn: The build plugins element could not be found in the POM and thus, no new plugin element can be added to it."); } } else { this.log.warning( "NWCloud-AddOn: The given XML element that should be added to the build plugins section of the POM was null."); } }
From source file:eu.europa.esig.dss.xades.signature.CounterSignatureBuilder.java
/** * This method incorporates a given countersignature value in the current signature XML DOM. * * @param counterSignatureValue/*from w w w. j a v a 2 s. c o m*/ * @return */ @Override public DSSDocument signDocument(final byte[] counterSignatureValue) { if (!built) { build(); } unsignedSignaturePropertiesDom = toCounterSignXadesSignature.getUnsignedSignaturePropertiesDom(); final Document ownerDocument = toCounterSignXadesSignature.getSignatureElement().getOwnerDocument(); if (unsignedSignaturePropertiesDom == null) { Element unsignedPropertiesDom = toCounterSignXadesSignature.getUnsignedPropertiesDom(); if (unsignedPropertiesDom == null) { final Element qualifyingPropertiesDom = toCounterSignXadesSignature.getQualifyingPropertiesDom(); // TODO-Vin (15/09/2014): add null check unsignedPropertiesDom = DSSXMLUtils.addElement(ownerDocument, qualifyingPropertiesDom, XAdES, XADES_UNSIGNED_PROPERTIES); } unsignedSignaturePropertiesDom = DSSXMLUtils.addElement(ownerDocument, unsignedPropertiesDom, XAdES, XADES_UNSIGNED_SIGNATURE_PROPERTIES); } final Element counterSignatureElement = DSSXMLUtils.addElement(ownerDocument, unsignedSignaturePropertiesDom, XAdES, XADES_COUNTER_SIGNATURE); final String signatureValueBase64Encoded = Base64.encodeBase64String(counterSignatureValue); final Text signatureValueNode = documentDom.createTextNode(signatureValueBase64Encoded); signatureValueDom.appendChild(signatureValueNode); final Node importedNode = ownerDocument.importNode(documentDom.getFirstChild(), true); counterSignatureElement.appendChild(importedNode); final byte[] documentBytes = DSSXMLUtils.transformDomToByteArray(ownerDocument); final InMemoryDocument inMemoryDocument = new InMemoryDocument(documentBytes); inMemoryDocument.setMimeType(MimeType.XML); return inMemoryDocument; }
From source file:com.enonic.esl.xml.XMLTool.java
/** * <p/> A generic method that builds the xml block of arbitrary depth. All fields starting with a specified prefix and an '_' character * followed element names separated by '_' characters are translated to nested xml elements where the prefix names the top specified * with the root element. The last element can be specified with one of the following prefix and suffixes: <ul> <li>@ (prefix) - * element text will be set as an attribute to the parent element <li>_CDATA (suffix) - element text will be wrapped in a CDATA element * <li>_XHTML (suffix) - element text will be turned into XHTML elements </ul> When reaching one of the prefix and suffixes, the element * creating process will terminate for this field. </p> <p/> <p>Elements already created with the same path will be reused.</p> <p/> * <p>Example:<br> The key 'contentdata_foo_bar_zot_CDATA' with the value '<b>alpha</b>' will transform into the following xml: * <pre>//from w w w. jav a 2 s . co m * <contentdata> * <foo> * <bar> * <zot> * <[!CDATA[<b><b>alpha</b></b>]]> * </zot> * </bar> * </foo> * </contentdata> * </pre> * </p> */ public static void buildSubTree(Document doc, Element rootElement, String prefix, ExtendedMap items) throws XMLToolException { for (Object o : items.keySet()) { String key = (String) o; String[] values = items.getStringArray(key); StringTokenizer keyTokenizer = new StringTokenizer(key, "_"); if (prefix.equals(keyTokenizer.nextToken())) { Element tmpRoot = rootElement; while (keyTokenizer.hasMoreTokens()) { String keyToken = keyTokenizer.nextToken(); if ("CDATA".equals(keyToken)) { String data = values[0]; data = StringUtil.replaceAll(data, "\r\n", "\n"); createCDATASection(doc, tmpRoot, data); break; } else if ("XML".equals(keyToken)) { String xmlDoc = values[0]; Document tempDoc = domparse(xmlDoc); tmpRoot.appendChild(doc.importNode(tempDoc.getDocumentElement(), true)); break; } else if ("XHTML".equals(keyToken)) { createXHTMLNodes(doc, tmpRoot, values[0], true); break; } else if ("FILEITEM".equals(keyToken)) { FileItem fileItem = items.getFileItem(key); tmpRoot.setAttribute("field", fileItem.getFieldName()); } else if (keyToken.charAt(0) == '@') { if (values.length == 1) { tmpRoot.setAttribute(keyToken.substring(1), items.getString(key)); } else { Element parentElem = (Element) tmpRoot.getParentNode(); String elementName = tmpRoot.getTagName(); Element[] elements = getElements(parentElem, elementName); for (int i = 0; i < elements.length && i < values.length; i++) { elements[i].setAttribute(keyToken.substring(1), values[i]); } if (elements.length < values.length) { for (int i = elements.length; i < values.length; i++) { Element element = createElement(doc, parentElem, elementName); element.setAttribute(keyToken.substring(1), values[i]); } } } break; } else { if (!keyTokenizer.hasMoreTokens() && values.length > 1) { Element[] elements = getElements(tmpRoot, keyToken); for (int i = 0; i < elements.length && i < values.length; i++) { createTextNode(doc, elements[i], values[i]); } if (elements.length < values.length) { for (int i = elements.length; i < values.length; i++) { createElement(doc, tmpRoot, keyToken, values[i]); } } } else { Element elem = getElement(tmpRoot, keyToken); if (elem == null) { tmpRoot = createElement(doc, tmpRoot, keyToken); } else { tmpRoot = elem; } if (!keyTokenizer.hasMoreTokens()) { createTextNode(doc, tmpRoot, items.getString(key)); break; } } } } } } }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
private static void copyNodeWithoutNamespace(Document document, Node parentNode, Node sourceNode) { Node destinationNode;/* w w w .jav a 2s .co m*/ if (sourceNode instanceof Document) { destinationNode = parentNode; } else { if (sourceNode instanceof Element) { String localName = XMLUtils.getLocalName(sourceNode); destinationNode = document.createElement(localName); // Copy attributes NamedNodeMap attributes = sourceNode.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node sourceAttribute = attributes.item(i); String prefix = XMLUtils.getPrefix(sourceAttribute); if (!prefix.equalsIgnoreCase("xmlns")) { ((Element) destinationNode).setAttribute(XMLUtils.getLocalName(sourceAttribute), sourceAttribute.getNodeValue()); } } } else { destinationNode = document.importNode(sourceNode, false); } parentNode.appendChild(destinationNode); } NodeList childNodes = sourceNode.getChildNodes(); int len = childNodes.getLength(); for (int i = 0; i < len; i++) { XMLUtils.copyNodeWithoutNamespace(document, destinationNode, childNodes.item(i)); } }
From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java
/** * Pull data files (pdb and images) for a given experiment * @param fileTreeXmlPath Path to XML file representing the project file tree * @param workflowXmlPath Path to XML file representing the experiment workflow * @param dataDirPath Path to directory used to store data files * @throws SAXException//from w ww . ja v a2 s .c om * @throws IOException * @throws XPathExpressionException * @throws ParserConfigurationException * @throws TransformerException */ private void pullDataFilesForExperiment(String fileTreeXmlPath, String workflowXmlPath, String dataDirPath) throws SAXException, IOException, XPathExpressionException, ParserConfigurationException, TransformerException { if (outputToConsole) System.out.println("Copying analysis data files..."); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document fileTreeDoc = docBuilder.parse(fileTreeXmlPath); fileTreeDoc = Utils.normalizeXmlDoc(fileTreeDoc); Element fileTreeRootElt = (Element) fileTreeDoc.getDocumentElement().getChildNodes().item(0); String dirPath = fileTreeRootElt.getAttribute("absolutePath"); XPathReader xreader = new XPathReader(fileTreeDoc); //load XML representation of experiment workflow Document docWorkflow = docBuilder.parse(workflowXmlPath); docWorkflow = Utils.normalizeXmlDoc(docWorkflow); Element workflowRootElt = (Element) docWorkflow.getDocumentElement(); //find main structure for display in Jmol Element jmolElt = pullJmolFile(fileTreeDoc, fileTreeRootElt, xreader, dataDirPath, dirPath); if (jmolElt != null) workflowRootElt.appendChild(docWorkflow.importNode(jmolElt, true)); //find analysis data NodeList matchingFiles = (NodeList) xreader.read("//file[AVUs/AVU[@id='" + FileMetadata.FILE_CLASS + "' and text()='" + FileMetadata.FILE_CLASS_ANALYSIS.toUpperCase() + "']]", XPathConstants.NODESET); //add publication information //Element dirNode = (Element)fileTreeDoc.getDocumentElement().getFirstChild(); //dirNode.setAttribute("publisher", workflowRootElt.getAttribute("publisher")); //dirNode.setAttribute("publicationDate", workflowRootElt.getAttribute("publicationDate")); //analysis data if (matchingFiles != null && matchingFiles.getLength() > 0) { Element dataElt = docWorkflow.createElement("analysis"); workflowRootElt.appendChild(dataElt); Element imgElt = docWorkflow.createElement("images"); Element pdbElt = docWorkflow.createElement("structures"); Element csvElts = docWorkflow.createElement("spreadsheets"); Element otherDataElts = docWorkflow.createElement("unknowns"); dataElt.appendChild(imgElt); dataElt.appendChild(csvElts); dataElt.appendChild(pdbElt); dataElt.appendChild(otherDataElts); PlotGenerator plotTool = new PlotGenerator(); for (int f = 0; f < matchingFiles.getLength(); f++) { Element fileNode = (Element) matchingFiles.item(f); String dataFilePath = fileNode.getAttribute("absolutePath"); //copy file String dataFileNewName = dataFilePath.substring(dirPath.length() + 1) .replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_"); String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName; Files.copy(Paths.get(dataFilePath), Paths.get(dataFileDestPath), StandardCopyOption.REPLACE_EXISTING); //set read permissions if (!Utils.isWindows()) { HashSet<PosixFilePermission> permissions = new HashSet<PosixFilePermission>(); permissions.add(PosixFilePermission.OWNER_READ); permissions.add(PosixFilePermission.OWNER_WRITE); permissions.add(PosixFilePermission.OWNER_EXECUTE); permissions.add(PosixFilePermission.GROUP_READ); permissions.add(PosixFilePermission.OTHERS_READ); Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions); } //read file AVUs NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dataFilePath + "']/AVUs/AVU", XPathConstants.NODESET); MetadataAVUList avuList = new MetadataAVUList(); if (avuNodes != null) { for (int a = 0; a < avuNodes.getLength(); a++) { Element avuNode = (Element) avuNodes.item(a); avuList.add(new MetadataAVU(avuNode.getAttribute("id").toUpperCase(), avuNode.getFirstChild().getNodeValue())); } } //add reference in XML doc String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION); String format = fileNode.getAttribute("format"); if (IBIOMESFileGroup.isJmolFile(format)) { Element jmolFileElt = docWorkflow.createElement("structure"); jmolFileElt.setAttribute("path", dataFileNewName); if (description != null && description.length() > 0) jmolFileElt.setAttribute("description", description); pdbElt.appendChild(jmolFileElt); } else if (format.equals(LocalFile.FORMAT_CSV)) { Element csvElt = docWorkflow.createElement("spreadsheet"); csvElt.setAttribute("path", dataFileNewName); if (description != null && description.length() > 0) csvElt.setAttribute("description", description); csvElts.appendChild(csvElt); //try to generate plot and save image try { String imgPath = dataFileNewName + "_plot.png"; String plotType = generatePlotForCSV(plotTool, dataFileDestPath, avuList, dataFileDestPath + "_plot", "png"); csvElt.setAttribute("plotPath", imgPath); if (outputToConsole) { if (plotType == null) plotType = ""; else plotType += " "; System.out.println("\t" + plotType + "plot generated for " + dataFileNewName); } } catch (Exception e) { if (outputToConsole) System.out.println( "Warning: Plot for '" + dataFileDestPath + "' could not be generated."); try { if (IBIOMESConfiguration.getInstance().isOutputErrorStackToConsole()) e.printStackTrace(); } catch (Exception e1) { } } } else if (IBIOMESFileGroup.isImageFile(format)) { Element imgFileElt = docWorkflow.createElement("image"); imgFileElt.setAttribute("path", dataFileNewName); if (description != null && description.length() > 0) imgFileElt.setAttribute("description", description); imgElt.appendChild(imgFileElt); } else { Element otherFileElt = docWorkflow.createElement("unknown"); otherFileElt.setAttribute("path", dataFileNewName); if (description != null && description.length() > 0) otherFileElt.setAttribute("description", description); imgElt.appendChild(otherDataElts); } } } //update XML files File outputXmlAvusFile = new File(fileTreeXmlPath); if (outputXmlAvusFile.exists()) outputXmlAvusFile.delete(); File outputXmlWorkflowFile = new File(workflowXmlPath); if (outputXmlWorkflowFile.exists()) outputXmlWorkflowFile.delete(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(fileTreeDoc); StreamResult result = null; result = new StreamResult(fileTreeXmlPath); transformer.transform(source, result); source = new DOMSource(docWorkflow); result = null; result = new StreamResult(outputXmlWorkflowFile); transformer.transform(source, result); }
From source file:com.enonic.vertical.adminweb.CategoryHandlerServlet.java
private Document buildContentARsFromCategoryARs(Document categoryAccessRights) { Document doc = XMLTool.createDocument("accessrights"); Element accessRights = doc.getDocumentElement(); accessRights.setAttribute("type", String.valueOf(AccessRight.CONTENT)); NodeList categoryAccessRightList = categoryAccessRights.getDocumentElement().getChildNodes(); for (int i = 0; i < categoryAccessRightList.getLength(); i++) { Element categoryAccessRight = (Element) categoryAccessRightList.item(i); Element contentAccessRight = buildContentARFromCategoryAR(categoryAccessRight); accessRights.appendChild(doc.importNode(contentAccessRight, true)); }//ww w. j a v a2 s . c o m return doc; }
From source file:de.mpg.escidoc.services.transformation.Util.java
/** * Execute the GET-method.// www .j av a 2 s.c om * @param client * @param queryUrl * @param documentBuilder * @param document * @param element * @return true if the array contains the format object, else false */ private static void executeGetMethod(HttpClient client, String queryUrl, DocumentBuilder documentBuilder, Document document, Element element) { String previousUrl = null; try { logger.info("queryURL from executeGetMethod " + queryUrl); GetMethod method = new GetMethod(queryUrl); ProxyHelper.executeMethod(client, method); if (method.getStatusCode() == 200) { String[] results = method.getResponseBodyAsString().split("\n"); for (String result : results) { if (!"".equals(result.trim())) { String detailsUrl = result.split("\\|")[1]; // if there is an alternative name, take only the first occurrence if (!detailsUrl.equalsIgnoreCase(previousUrl)) { GetMethod detailMethod = new GetMethod(detailsUrl + "?format=rdf"); previousUrl = detailsUrl; if (logger.isDebugEnabled()) { logger.info(detailMethod.getPath()); logger.info(detailMethod.getQueryString()); } ProxyHelper.setProxy(client, detailsUrl); client.executeMethod(detailMethod); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getPath() + "\n" + detailMethod.getResponseBodyAsString()); } } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); } }
From source file:com.github.lindenb.jvarkit.tools.ensembl.VcfEnsemblVepRest.java
@Override protected Collection<Throwable> doVcfToVcf(final String inputName, final VcfIterator vcfIn, final VariantContextWriter out) throws IOException { final java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder(); final SequenceOntologyTree soTree = SequenceOntologyTree.getInstance(); VCFHeader header = vcfIn.getHeader(); List<VariantContext> buffer = new ArrayList<>(this.batchSize + 1); VCFHeader h2 = new VCFHeader(header); addMetaData(h2);//from w w w . ja v a2 s . c o m if (!xmlBase64) { h2.addMetaDataLine(new VCFInfoHeaderLine(TAG, VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String, "VEP Transcript Consequences. Format :(biotype|cdnaStart|cdnaEnd|cdsStart|cdsEnd|geneId|geneSymbol|geneSymbolSource|hgnc|strand|transcript|variantAllele|so_acns)")); } else { h2.addMetaDataLine( new VCFInfoHeaderLine(TAG, 1, VCFHeaderLineType.String, "VEP xml answer encoded as base 64")); } out.writeHeader(h2); SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header); for (;;) { VariantContext ctx = null; if (vcfIn.hasNext()) { buffer.add((ctx = progress.watch(vcfIn.next()))); } if (ctx == null || buffer.size() >= this.batchSize) { if (!buffer.isEmpty()) { if (!xmlBase64) { Opt opt = vep(buffer); for (VariantContext ctx2 : buffer) { VariantContextBuilder vcb = new VariantContextBuilder(ctx2); final String inputStr = createInputContext(ctx2); Data mydata = null; for (Data data : opt.getData()) { if (!inputStr.equals(data.getInput())) continue; mydata = data; break; } if (mydata == null) { LOG.info("No Annotation found for " + inputStr); out.add(ctx2); continue; } List<String> infoList = new ArrayList<>(); List<TranscriptConsequences> csql = mydata.getTranscriptConsequences(); for (int i = 0; i < csql.size(); ++i) { TranscriptConsequences csq = csql.get(i); StringBuilder sb = new StringBuilder(); sb.append(empty(csq.getBiotype())).append("|").append(empty(csq.getCdnaStart())) .append("|").append(empty(csq.getCdnaEnd())).append("|") .append(empty(csq.getCdsStart())).append("|").append(empty(csq.getCdsEnd())) .append("|").append(empty(csq.getGeneId())).append("|") .append(empty(csq.getGeneSymbol())).append("|") .append(empty(csq.getGeneSymbolSource())).append("|") .append(empty(csq.getHgncId())).append("|").append(empty(csq.getStrand())) .append("|").append(empty(csq.getTranscriptId())).append("|") .append(empty(csq.getVariantAllele())).append("|"); List<String> terms = csq.getConsequenceTerms(); for (int j = 0; j < terms.size(); ++j) { if (j > 0) sb.append("&"); SequenceOntologyTree.Term term = soTree.getTermByLabel(terms.get(j)); if (term == null) { sb.append(terms.get(j)); LOG.warn("No SO:Term found for " + terms.get(j)); } else { sb.append(term.getAcn()); } } infoList.add(sb.toString()); } if (!infoList.isEmpty()) { vcb.attribute(TAG, infoList); } out.add(vcb.make()); } } //end of not(XML base 64) else { Document opt = vepxml(buffer); Element root = opt.getDocumentElement(); if (!root.getNodeName().equals("opt")) throw new IOException("Bad root node " + root.getNodeName()); for (VariantContext ctx2 : buffer) { String inputStr = createInputContext(ctx2); Document newdom = null; //loop over <data/> for (Node dataNode = root.getFirstChild(); dataNode != null; dataNode = dataNode .getNextSibling()) { if (dataNode.getNodeType() != Node.ELEMENT_NODE) continue; Attr att = Element.class.cast(dataNode).getAttributeNode("input"); if (att == null) { LOG.warn("no @input in <data/>"); continue; } if (!att.getValue().equals(inputStr)) continue; if (newdom == null) { newdom = this.documentBuilder.newDocument(); newdom.appendChild(newdom.createElement("opt")); } newdom.getDocumentElement().appendChild(newdom.importNode(dataNode, true)); } if (newdom == null) { LOG.warn("No Annotation found for " + inputStr); out.add(ctx2); continue; } StringWriter sw = new StringWriter(); try { this.xmlSerializer.transform(new DOMSource(newdom), new StreamResult(sw)); } catch (TransformerException err) { throw new IOException(err); } VariantContextBuilder vcb = new VariantContextBuilder(ctx2); vcb.attribute(TAG, base64Encoder.encodeToString(sw.toString().getBytes()) .replaceAll("[\\s=]", "")); out.add(vcb.make()); } } //end of XML base 64 } if (ctx == null) break; buffer.clear(); } if (out.checkError()) break; } progress.finish(); return RETURN_OK; }
From source file:com.enonic.vertical.engine.handlers.SectionHandler.java
public void updateSection(User user, Document doc) throws VerticalUpdateException, VerticalSecurityException { Element elem = doc.getDocumentElement(); int sectionKey = Integer.parseInt(elem.getAttribute("key")); boolean ordered = isSectionOrdered(sectionKey); CommonHandler commonHandler = getCommonHandler(); try {/* w ww.j av a2 s. co m*/ commonHandler.updateEntities(doc, null); } catch (ProcessElementException pee) { // NOTE!! Ignored exception. Never thrown. VerticalEngineLogger.fatalEngine(this.getClass(), 0, "Ignored exception: %t", pee); } Element sectionElem = null; try { // Remove old content types for this section removeContentTypesForSection(sectionKey); sectionElem = doc.getDocumentElement(); Element contentTypesElem = XMLTool.getElement(sectionElem, "contenttypes"); Element[] contentTypes = XMLTool.getElements(contentTypesElem, "contenttype"); TIntArrayList contentTypeKeys = new TIntArrayList(); for (Element contentType : contentTypes) { contentTypeKeys.add(Integer.parseInt(contentType.getAttribute("key"))); } // Set the new ones setContentTypesForSection(sectionKey, contentTypeKeys.toArray()); // Apply the filter applySectionFilter(sectionKey); // set section content order if section is ordered if (!ordered && "true".equals(sectionElem.getAttribute("ordered"))) { int[] contentKeys = getContentKeysBySection(sectionKey); for (int i = 0; i < contentKeys.length; i++) { updateSectionContent(user, sectionKey, contentKeys[i], i + 1, true, null); } } else if (ordered && "false".equals(sectionElem.getAttribute("ordered"))) { int[] contentKeys = getContentKeysBySection(sectionKey); for (int contentKey : contentKeys) { updateSectionContent(user, sectionKey, contentKey, 0, true, null); } } } catch (VerticalCreateException vce) { String message = "Failed to create section contenttype filter: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 1, message, vce); } catch (VerticalRemoveException vre) { String message = "Failed to create section contenttype filter: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 1, message, vre); } // set section access rights SecurityHandler securityHandler = getSecurityHandler(); Element accessrightsElem = XMLTool.getElement(elem, "accessrights"); if (accessrightsElem != null) { accessrightsElem.setAttribute("key", sectionElem.getAttribute("key")); Document tempDoc = XMLTool.createDocument(); tempDoc.appendChild(tempDoc.importNode(accessrightsElem, true)); securityHandler.updateAccessRights(user, tempDoc); } }