List of usage examples for org.w3c.dom Element getParentNode
public Node getParentNode();
From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java
private void moveMenuItemDown(HttpServletRequest request, HttpServletResponse response, HttpSession session, ExtendedMap formItems) throws VerticalAdminException { String menuXML = (String) session.getAttribute("menuxml"); Document doc = XMLTool.domparse(menuXML); String xpath = "/model/menuitems-to-list//menuitem[@key = '" + formItems.getString("key") + "']"; Element movingMenuItemElement = (Element) XMLTool.selectNode(doc, xpath); Element parentElement = (Element) movingMenuItemElement.getParentNode(); Node nextSiblingElement = movingMenuItemElement.getNextSibling(); movingMenuItemElement = (Element) parentElement.removeChild(movingMenuItemElement); doc.importNode(movingMenuItemElement, true); if (nextSiblingElement != null) { // spool forward... for (nextSiblingElement = nextSiblingElement.getNextSibling(); (nextSiblingElement != null && nextSiblingElement .getNodeType() != Node.ELEMENT_NODE); nextSiblingElement = nextSiblingElement .getNextSibling()) { }/*from w ww .j a va 2 s . c o m*/ if (nextSiblingElement != null) { parentElement.insertBefore(movingMenuItemElement, nextSiblingElement); } else { parentElement.appendChild(movingMenuItemElement); } } else { // This is the bottom element, move it to the top parentElement.insertBefore(movingMenuItemElement, parentElement.getFirstChild()); } session.setAttribute("menuxml", XMLTool.documentToString(doc)); MultiValueMap queryParams = new MultiValueMap(); queryParams.put("page", formItems.get("page")); queryParams.put("op", "browse"); queryParams.put("keepxml", "yes"); queryParams.put("highlight", formItems.get("key")); queryParams.put("menukey", formItems.get("menukey")); queryParams.put("parentmi", formItems.get("parentmi")); queryParams.put("subop", "shiftmenuitems"); queryParams.put("move_menuitem", formItems.getString("move_menuitem", "")); queryParams.put("move_from_parent", formItems.getString("move_from_parent", "")); queryParams.put("move_to_parent", formItems.getString("move_to_parent", "")); redirectClientToAdminPath("adminpage", queryParams, request, response); }
From source file:de.betterform.xml.xforms.model.submission.Submission.java
private void submitReplaceEmbedXForms(Map response) throws XFormsException { // check for targetid String targetid = getXFormsAttribute(TARGETID_ATTRIBUTE); String resource = getResource(); Map eventInfo = new HashMap(); String error = null;//w w w .ja v a2 s .c om if (targetid == null) { error = "targetId"; } else if (resource == null) { error = "resource"; } if (error != null && error.length() > 0) { eventInfo.put(XFormsConstants.ERROR_TYPE, "no " + error + "defined for submission resource"); this.container.dispatch(this.target, XFormsEventNames.SUBMIT_ERROR, eventInfo); return; } Document result = getResponseAsDocument(response); Node embedElement = result.getDocumentElement(); if (resource.indexOf("#") != -1) { // detected a fragment so extract that from our result Document String fragmentid = resource.substring(resource.indexOf("#") + 1); if (fragmentid.indexOf("?") != -1) { fragmentid = fragmentid.substring(0, fragmentid.indexOf("?")); } embedElement = DOMUtil.getById(result, fragmentid); } Element embeddedNode = null; if (LOGGER.isDebugEnabled()) { LOGGER.debug("get target element for id: " + targetid); } Element targetElem = this.container.getElementById(targetid); DOMResult domResult = new DOMResult(); //Test if targetElem exist. if (targetElem != null) { // destroy existing embedded form within targetNode if (targetElem.hasChildNodes()) { // destroyembeddedModels(targetElem); Initializer.disposeUIElements(targetElem); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("destroyed any existing ui elements for target elem"); } // import referenced embedded form into host document embeddedNode = (Element) this.container.getDocument().importNode(embedElement, true); //import namespaces NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(), (Element) embeddedNode); // keep original targetElem id within hostdoc embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id")); //copy all Attributes that might have been on original mountPoint to embedded node DOMUtil.copyAttributes(targetElem, embeddedNode, null); targetElem.getParentNode().replaceChild(embeddedNode, targetElem); //create model for it Initializer.initializeUIElements(model, embeddedNode, null, null); try { CachingTransformerService transformerService = new CachingTransformerService( new ClasspathResourceResolver("unused")); // TODO: MUST BE GENERIFIED USING USERAGENT MECHANISM //TODO: check exploded mode!!! String path = getClass().getResource("/META-INF/resources/xslt/xhtml.xsl").getPath(); //String xslFilePath = "file:" + path; transformerService.getTransformer(new URI(path)); XSLTGenerator generator = new XSLTGenerator(); generator.setTransformerService(transformerService); generator.setStylesheetURI(new URI(path)); generator.setInput(embeddedNode); generator.setOutput(domResult); generator.generate(); } catch (TransformerException e) { throw new XFormsException( "Transformation error while executing 'Submission.submitReplaceEmbedXForms'", e); } catch (URISyntaxException e) { throw new XFormsException( "Malformed URI throwed URISyntaxException in 'Submission.submitReplaceEmbedXForms'", e); } } // Map eventInfo = constructEventInfo(response); OutputStream outputStream = new ByteArrayOutputStream(); try { DOMUtil.prettyPrintDOM(domResult.getNode(), outputStream); } catch (TransformerException e) { throw new XFormsException(e); } eventInfo.put(EMBEDNODE, outputStream.toString()); eventInfo.put("embedTarget", targetid); eventInfo.put("embedXForms", true); // dispatch xforms-submit-done this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, eventInfo); }
From source file:loci.formats.in.LIFReader.java
private void translateSingleROIs(Element imageNode, int image) throws FormatException { if (imageROIs[image] != null) return;/* w w w . j ava 2s . com*/ NodeList children = getNodes(imageNode, "ROI"); if (children == null) return; children = getNodes((Element) children.item(0), "Children"); if (children == null) return; children = getNodes((Element) children.item(0), "Element"); if (children == null) return; imageROIs[image] = new ROI[children.getLength()]; for (int r = 0; r < children.getLength(); r++) { NodeList rois = getNodes((Element) children.item(r), "ROISingle"); Element roiNode = (Element) rois.item(0); ROI roi = new ROI(); String type = roiNode.getAttribute("RoiType"); if (type != null && !type.trim().isEmpty()) { roi.type = Integer.parseInt(type.trim()); } String color = roiNode.getAttribute("Color"); if (color != null && !color.trim().isEmpty()) { roi.color = Long.parseLong(color.trim()); } Element parent = (Element) roiNode.getParentNode(); parent = (Element) parent.getParentNode(); roi.name = parent.getAttribute("Name"); NodeList vertices = getNodes(roiNode, "P"); double sizeX = physicalSizeXs.get(image); double sizeY = physicalSizeYs.get(image); for (int v = 0; v < vertices.getLength(); v++) { Element vertex = (Element) vertices.item(v); String xx = vertex.getAttribute("X"); String yy = vertex.getAttribute("Y"); if (xx != null && !xx.trim().isEmpty()) { roi.x.add(parseDouble(xx.trim()) / sizeX); } if (yy != null && !yy.trim().isEmpty()) { roi.y.add(parseDouble(yy.trim()) / sizeY); } } Element transform = (Element) getNodes(roiNode, "Transformation").item(0); roi.rotation = parseDouble(transform.getAttribute("Rotation")); Element scaling = (Element) getNodes(transform, "Scaling").item(0); roi.scaleX = parseDouble(scaling.getAttribute("XScale")); roi.scaleY = parseDouble(scaling.getAttribute("YScale")); Element translation = (Element) getNodes(transform, "Translation").item(0); roi.transX = parseDouble(translation.getAttribute("X")) / sizeX; roi.transY = parseDouble(translation.getAttribute("Y")) / sizeY; imageROIs[image][r] = roi; } }
From source file:com.icesoft.faces.component.style.OutputStyleRenderer.java
public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException { validateParameters(facesContext, uiComponent, OutputStyle.class); try {//from www .j ava 2 s .co m DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent); if (!domContext.isInitialized()) { OutputStyle outputStyle = (OutputStyle) uiComponent; Element styleEle = buildCssElement(domContext); String href = outputStyle.getHref(); styleEle.setAttribute(HTML.HREF_ATTR, getResourceURL(facesContext, href)); domContext.setRootNode(styleEle); int browserType = browserType(facesContext, uiComponent); if (browserType != DEFAULT_TYPE) { if (href.endsWith(CSS_EXTENTION)) { int i = href.indexOf(CSS_EXTENTION); if (i > 0) { String start = href.substring(0, i); Element ieStyleEle = buildCssElement(domContext); String extention = IE_EXTENTION; if (browserType == SAFARI) { extention = SAFARI_EXTENTION; } if (browserType == DT) { extention = DT_EXTENTION; } if (browserType == IE_7) { extention = IE_7_EXTENTION; } if (browserType == IE_8) { extention = IE_8_EXTENSION; } if (browserType == SAFARI_MOBILE) { extention = SAFARI_MOBILE_EXTENTION; } if (browserType == OPERA) { extention = OPERA_EXTENTION; } if (browserType == OPERA_MOBILE) { extention = OPERA_MOBILE_EXTENTION; } String browserSpecificFilename = useSpecific(facesContext, start, extention); if (browserSpecificFilename != null) { // W3C spec: To make a style sheet preferred, set the rel attribute to "stylesheet" and name the style sheet with the title attribute ieStyleEle.setAttribute(HTML.TITLE_ATTR, extention); String hrefURL = CoreUtils.resolveResourceURL(facesContext, browserSpecificFilename); ieStyleEle.setAttribute(HTML.HREF_ATTR, hrefURL); styleEle.getParentNode().appendChild(ieStyleEle); } } else { throw new RuntimeException("OutputStyle file attribute is too short. " + "Needs at least one character before .css. Current Value is [" + href + "]"); } } else { Matcher matcher = Pattern .compile(".*javax\\.faces\\.resource/((.*)\\.css)(\\..*)?\\?ln=([^&]*)(&.*|$)") .matcher(href); if (matcher.matches()) { Element ieStyleEle = buildCssElement(domContext); String extension = browserType >= 0 && browserType < extensions.length ? extensions[browserType] : IE_EXTENTION; ieStyleEle.setAttribute(HTML.TITLE_ATTR, extension); String hrefURL = new StringBuffer(matcher.group(0)).insert(matcher.end(2), extension) .toString(); ieStyleEle.setAttribute(HTML.HREF_ATTR, hrefURL); String resourceName = new StringBuffer(matcher.group(1)) .insert(matcher.end(2) - matcher.start(2), extension).toString(); Resource resource = facesContext.getApplication().getResourceHandler() .createResource(resourceName, matcher.group(4)); if (resource != null) { styleEle.getParentNode().appendChild(ieStyleEle); } } } } } domContext.stepOver(); } catch (Exception e) { log.error("Error in OutputStyleRenderer", e); } }
From source file:lcmc.data.VMSXML.java
/** Modify xml of the domain. */ public Node modifyDomainXML(final String domainName, final Map<String, String> parametersMap) { final String configName = namesConfigsMap.get(domainName); if (configName == null) { return null; }//from w w w .j a va 2 s .c o m final Node domainNode = getDomainNode(domainName); if (domainNode == null) { return null; } final XPath xpath = XPathFactory.newInstance().newXPath(); final Map<String, String> paths = new HashMap<String, String>(); paths.put(VM_PARAM_MEMORY, "memory"); paths.put(VM_PARAM_CURRENTMEMORY, "currentMemory"); paths.put(VM_PARAM_VCPU, "vcpu"); paths.put(VM_PARAM_BOOTLOADER, "bootloader"); paths.put(VM_PARAM_BOOT, "os/boot"); paths.put(VM_PARAM_BOOT_2, "os/boot"); paths.put(VM_PARAM_TYPE, "os/type"); paths.put(VM_PARAM_TYPE_ARCH, "os/type"); paths.put(VM_PARAM_TYPE_MACHINE, "os/type"); paths.put(VM_PARAM_INIT, "os/init"); paths.put(VM_PARAM_LOADER, "os/loader"); paths.put(VM_PARAM_CPU_MATCH, "cpu"); paths.put(VM_PARAM_ACPI, "features"); paths.put(VM_PARAM_APIC, "features"); paths.put(VM_PARAM_PAE, "features"); paths.put(VM_PARAM_HAP, "features"); paths.put(VM_PARAM_ON_POWEROFF, "on_poweroff"); paths.put(VM_PARAM_ON_REBOOT, "on_reboot"); paths.put(VM_PARAM_ON_CRASH, "on_crash"); paths.put(VM_PARAM_EMULATOR, "devices/emulator"); final Document doc = domainNode.getOwnerDocument(); try { for (final String param : parametersMap.keySet()) { final String path = paths.get(param); if (path == null) { continue; } final NodeList nodes = (NodeList) xpath.evaluate(path, domainNode, XPathConstants.NODESET); Element node = (Element) nodes.item(0); if (node == null) { continue; } if (VM_PARAM_BOOT_2.equals(param)) { if (nodes.getLength() > 1) { node = (Element) nodes.item(1); } else { node = (Element) node.getParentNode().appendChild(doc.createElement(OS_BOOT_NODE)); } } String value = parametersMap.get(param); if (VM_PARAM_MEMORY.equals(param) || VM_PARAM_CURRENTMEMORY.equals(param)) { value = Long.toString(Tools.convertToKilobytes(value)); } if (VM_PARAM_CPU_MATCH.equals(param) || VM_PARAM_ACPI.equals(param) || VM_PARAM_APIC.equals(param) || VM_PARAM_PAE.equals(param) || VM_PARAM_HAP.equals(param)) { domainNode.removeChild(node); } else if (VM_PARAM_BOOT.equals(param)) { node.setAttribute(OS_BOOT_NODE_DEV, value); } else if (VM_PARAM_BOOT_2.equals(param)) { if (value == null || "".equals(value)) { node.getParentNode().removeChild(node); } else { node.setAttribute(OS_BOOT_NODE_DEV, value); } } else if (VM_PARAM_TYPE_ARCH.equals(param)) { node.setAttribute("arch", value); } else if (VM_PARAM_TYPE_MACHINE.equals(param)) { node.setAttribute("machine", value); } else if (VM_PARAM_CPU_MATCH.equals(param)) { if ("".equals(value)) { node.getParentNode().removeChild(node); } else { node.setAttribute("match", value); } } else if (VM_PARAM_CPUMATCH_TOPOLOGY_THREADS.equals(param)) { node.setAttribute("threads", value); } else { final Node n = getChildNode(node, "#text"); if (n == null) { node.appendChild(doc.createTextNode(value)); } else { n.setNodeValue(value); } } } addCPUMatchNode(doc, domainNode, parametersMap); addFeatures(doc, domainNode, parametersMap); } catch (final javax.xml.xpath.XPathExpressionException e) { Tools.appError("could not evaluate: ", e); return null; } return domainNode; }
From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java
/** * Updates web services configuration file. * /* ww w . j a v a 2 s . co m*/ * @param className to export. * @param annotationMetadata values from web service class to set in * configuration file. * @return true if annotation from className has to be updated because of * changes in package or class name. */ private boolean updateConfiguration(JavaType className, AnnotationMetadata annotationMetadata) { StringAttributeValue serviceName = (StringAttributeValue) annotationMetadata .getAttribute(new JavaSymbolName("serviceName")); Validate.isTrue(serviceName != null && StringUtils.isNotBlank(serviceName.getValue()), "Annotation attribute 'serviceName' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED); StringAttributeValue address = (StringAttributeValue) annotationMetadata .getAttribute(new JavaSymbolName(ADDRESS2)); Validate.isTrue(address != null && StringUtils.isNotBlank(address.getValue()), "Annotation attribute 'address' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED); StringAttributeValue fullyQualifiedTypeName = (StringAttributeValue) annotationMetadata .getAttribute(new JavaSymbolName("fullyQualifiedTypeName")); Validate.notNull(fullyQualifiedTypeName, "Annotation attribute 'fullyQualifiedTypeName' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED); Validate.isTrue(fullyQualifiedTypeName != null && StringUtils.isNotBlank(fullyQualifiedTypeName.getValue()), "Annotation attribute 'fullyQualifiedTypeName' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED); BooleanAttributeValue exported = (BooleanAttributeValue) annotationMetadata .getAttribute(new JavaSymbolName("exported")); Validate.isTrue(exported != null, "Annotation attribute 'exported' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED); String cxfXmlPath = getCxfConfigAbsoluteFilePath(); boolean updateFullyQualifiedTypeName = false; // Check if class name and annotation class name are different. if (fullyQualifiedTypeName != null && !className.getFullyQualifiedTypeName().contentEquals(fullyQualifiedTypeName.getValue())) { updateFullyQualifiedTypeName = true; } if (getFileManager().exists(cxfXmlPath)) { MutableFile cxfXmlMutableFile = getFileManager().updateFile(cxfXmlPath); Document cxfXml = getInputDocument(cxfXmlMutableFile.getInputStream()); Element root = cxfXml.getDocumentElement(); // Check if service exists in configuration file. boolean updateService = true; // 1) Check if class and id exists in bean. Element classAndIdService = XmlUtils .findFirstElement("/beans/bean[@id='" + serviceName.getValue().concat(IMPL) + "' and @class='" + className.getFullyQualifiedTypeName() + "']", root); // Service is already published. if (classAndIdService != null) { logger.log(Level.FINE, THE_SERVICE + serviceName.getValue() + "' is already set in cxf config file."); updateService = false; } if (updateService) { // 2) Check if class exists or it hasn't changed. Element classService = null; if (updateFullyQualifiedTypeName) { // Check if exists with class name. classService = XmlUtils.findFirstElement( "/beans/bean[@class='" + className.getFullyQualifiedTypeName() + "']", root); if (classService != null) { // Update bean with new Id attribute. Element updateClassService = classService; String idValue = classService.getAttribute("id"); if (!StringUtils.isNotBlank(idValue) || !idValue.contentEquals(serviceName.getValue().concat(IMPL))) { updateClassService.setAttribute("id", serviceName.getValue().concat(IMPL)); classService.getParentNode().replaceChild(updateClassService, classService); logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + HAS_UPDATED); } } else { // Check if exists with fullyQualifiedTypeName. classService = XmlUtils.findFirstElement( "/beans/bean[@class='" + fullyQualifiedTypeName.getValue() + "']", root); if (classService != null) { Element updateClassService = classService; String idValue = classService.getAttribute("id"); updateClassService.setAttribute(CLASS, className.getFullyQualifiedTypeName()); if (!StringUtils.isNotBlank(idValue) || !idValue.contentEquals(serviceName.getValue().concat(IMPL))) { updateClassService.setAttribute("id", serviceName.getValue().concat(IMPL)); logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + HAS_UPDATED); } classService.getParentNode().replaceChild(updateClassService, classService); logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + "' has updated 'class' attribute in cxf config file."); } } } else { // Check if exists with class name. classService = XmlUtils.findFirstElement( "/beans/bean[@class='" + className.getFullyQualifiedTypeName() + "']", root); if (classService != null) { // Update bean with new Id attribute. Element updateClassService = classService; String idValue = classService.getAttribute("id"); if (!StringUtils.isNotBlank(idValue) || !idValue.contentEquals(serviceName.getValue().concat(IMPL))) { updateClassService.setAttribute("id", serviceName.getValue().concat(IMPL)); classService.getParentNode().replaceChild(updateClassService, classService); logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + HAS_UPDATED); } } } // 3) Check if id exists. Element idService = XmlUtils .findFirstElement("/beans/bean[@id='" + serviceName.getValue().concat(IMPL) + "']", root); if (idService != null) { // Update bean with new class attribute. Element updateIdService = idService; String classNameAttribute = idService.getAttribute(CLASS); if (!StringUtils.isNotBlank(classNameAttribute) || !classNameAttribute.contentEquals(className.getFullyQualifiedTypeName())) { updateIdService.setAttribute(CLASS, className.getFullyQualifiedTypeName()); idService.getParentNode().replaceChild(updateIdService, idService); logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + "' has updated 'class' attribute in cxf config file."); } } Element bean; // Check id and class values to create a new bean. if (classService == null && idService == null) { bean = cxfXml.createElement("bean"); bean.setAttribute("id", serviceName.getValue().concat(IMPL)); bean.setAttribute(CLASS, className.getFullyQualifiedTypeName()); root.appendChild(bean); } } boolean updateEndpoint = true; // Check if endpoint exists in the configuration file. Element jaxwsBean = XmlUtils.findFirstElement("/beans/endpoint[@address='/" + address.getValue() + "' and @id='" + serviceName.getValue() + "']", root); // 1) Check if exists with id and address. if (jaxwsBean != null) { logger.log(Level.FINE, "The endpoint '" + serviceName.getValue() + "' is already set in cxf config file."); updateEndpoint = false; } if (updateEndpoint) { // 2) Check if exists a bean with annotation address value and // updates id attribute with annotation serviceName value. Element addressEndpoint = XmlUtils .findFirstElement("/beans/endpoint[@address='/" + address.getValue() + "']", root); if (addressEndpoint != null) { // Update bean with new Id attribute. Element updateAddressEndpoint = addressEndpoint; String idAttribute = addressEndpoint.getAttribute("id"); if (!StringUtils.isNotBlank(idAttribute) || !idAttribute.contentEquals(serviceName.getValue())) { updateAddressEndpoint.setAttribute("id", serviceName.getValue()); updateAddressEndpoint.setAttribute("implementor", "#".concat(serviceName.getValue()).concat(IMPL)); addressEndpoint.getParentNode().replaceChild(updateAddressEndpoint, addressEndpoint); logger.log(Level.INFO, "The endpoint bean '" + serviceName.getValue() + HAS_UPDATED); } } Element idEndpoint = XmlUtils .findFirstElement("/beans/endpoint[@id='" + serviceName.getValue() + "']", root); // 3) Check if exists a bean with annotation address value in id // attribute and updates address attribute with annotation // address // value. if (idEndpoint != null) { // Update bean with new Id attribute. Element updateIdEndpoint = idEndpoint; String addressAttribute = idEndpoint.getAttribute(ADDRESS2); if (!StringUtils.isNotBlank(addressAttribute) || !addressAttribute.contentEquals("/".concat(address.getValue()))) { updateIdEndpoint.setAttribute(ADDRESS2, "/".concat(address.getValue())); idEndpoint.getParentNode().replaceChild(updateIdEndpoint, idEndpoint); logger.log(Level.INFO, "The endpoint bean '" + serviceName.getValue() + "' has updated 'address' attribute in cxf config file."); } } Element endpoint; // Check values to create new endpoint bean. if (addressEndpoint == null && idEndpoint == null) { endpoint = cxfXml.createElement("jaxws:endpoint"); endpoint.setAttribute("id", serviceName.getValue()); endpoint.setAttribute("implementor", "#".concat(serviceName.getValue()).concat(IMPL)); endpoint.setAttribute(ADDRESS2, "/".concat(address.getValue())); root.appendChild(endpoint); } } // Update configuration file. if (updateService || updateEndpoint) { XmlUtils.writeXml(cxfXmlMutableFile.getOutputStream(), cxfXml); } } return updateFullyQualifiedTypeName; }
From source file:act.installer.pubchem.PubchemParser.java
/** * Incrementally parses a stream of XML events from a PubChem file, extracting the next available PC-Compound entry * as a Chemical object.//from w w w . j a va 2 s .co m * @param eventReader The xml event reader we are parsing the XML from * @return The constructed chemical * @throws XMLStreamException * @throws XPathExpressionException */ public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader) throws XMLStreamException, JaxenException { Document bufferDoc = null; Element currentElement = null; StringBuilder textBuffer = null; /* With help from * http://stackoverflow.com/questions/7998733/loading-local-chunks-in-dom-while-parsing-a-large-xml-file-in-sax-java */ while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch (event.getEventType()) { case XMLStreamConstants.START_ELEMENT: String eventName = event.asStartElement().getName().getLocalPart(); if (COMPOUND_DOC_TAG.equals(eventName)) { // Create a new document if we've found the start of a compound object. bufferDoc = documentBuilder.newDocument(); currentElement = bufferDoc.createElement(eventName); bufferDoc.appendChild(currentElement); } else if (currentElement != null) { // Wait until we've found a compound entry to start slurping up data. // Create a new child element and push down the current pointer when we find a new node. Element newElement = bufferDoc.createElement(eventName); currentElement.appendChild(newElement); currentElement = newElement; } // If we aren't in a PC-Compound tree, we just let the elements pass by. break; case XMLStreamConstants.CHARACTERS: if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree. continue; } Characters chars = event.asCharacters(); // Ignore only whitespace strings, which just inflate the size of the DOM. Text coalescing makes this safe. if (chars.isWhiteSpace()) { continue; } // Rely on the XMLEventStream to coalesce consecutive text events. Text textNode = bufferDoc.createTextNode(chars.getData()); currentElement.appendChild(textNode); break; case XMLStreamConstants.END_ELEMENT: if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree. continue; } eventName = event.asEndElement().getName().getLocalPart(); Node parentNode = currentElement.getParentNode(); if (parentNode instanceof Element) { currentElement = (Element) parentNode; } else if (parentNode instanceof Document && eventName.equals(COMPOUND_DOC_TAG)) { // We're back at the top of the node stack! Convert the buffered document into a Chemical. PubchemEntry entry = extractPCCompoundFeatures(bufferDoc); if (entry != null) { return entry.asChemical(); } else { // Skip this entry if we can't process it correctly by resetting the world and continuing on. bufferDoc = null; currentElement = null; } } else { // This should not happen, but is here as a sanity check. throw new RuntimeException(String.format("Parent of XML element %s is of type %d, not Element", currentElement.getTagName(), parentNode.getNodeType())); } break; // TODO: do we care about attributes or other XML structures? } } // Return null when we run out of chemicals, just like readLine(). return null; }
From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java
private void processPort(Element portElement) throws CatalogingException { try {/*from w ww.j av a 2 s . c o m*/ String id = getPortId(portElement); if (idToWSDLMap.containsKey(id)) { return; } //Create a RIM ServiceBinding instances for service tag ServiceBindingType ebServiceBindingType = bu.rimFac.createServiceBindingType(); bu.addSlotsToRegistryObject(ebServiceBindingType, dontVersionSlotsMap); //Set id ebServiceBindingType.setId(id); idToRIMMap.put(id, ebServiceBindingType); idToWSDLMap.put(id, portElement); //Set name String nameStr = wsdlDocument.getAttribute(portElement, WSDLConstants.ATTR_NAME); ebServiceBindingType.setName(bu.getName(nameStr)); //Set description Element docElement = wsdlDocument.getElement(portElement, WSDLConstants.QNAME_DOCUMENTATION); if (docElement != null) { String docStr = docElement.getFirstChild().getNodeValue(); ebServiceBindingType.setDescription(bu.getDescription(docStr)); } catalogTargetNamespace(ebServiceBindingType); //Add wsdl Service Classification bu.addClassificationToRegistryObject(ebServiceBindingType, CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_WSDL_PORT); //Set parent link Element serviceElement = (Element) portElement.getParentNode(); ServiceType rimService = (ServiceType) idToRIMMap.get(getServiceId(serviceElement)); if (rimService != null) { ebServiceBindingType.setService(rimService.getId()); } //Add accessURI String accessURI = null; Element soapAddressElement = wsdlDocument.getElement(portElement, WSDLConstants.QNAME_SOAP_ADDRESS); if (soapAddressElement != null) { accessURI = wsdlDocument.getAttribute(soapAddressElement, WSDLConstants.ATTR_LOCATION); if (accessURI != null) { ebServiceBindingType.setAccessURI(accessURI); } } // document get binding String bindingStr = wsdlDocument.getAttribute(portElement, WSDLConstants.ATTR_BINDING); Element bindingElement = resolveBinding(wsdlDocument, bindingStr); if (bindingElement == null) { throw new CatalogingException( ServerResourceBundle.getInstance().getString("message.missingRequiredElement", new Object[] { wsdlDocument.getSystemId(), bindingElement })); } //Now process the Binding instances for the Service //Note it may be in an imported document processBinding(bindingElement); //Set Implements Association between Port and Binding ExtrinsicObjectType rimBinding = (ExtrinsicObjectType) idToRIMMap.get(getBindingId(bindingElement)); AssociationType1 ebAssociationType = bu.createAssociationType(ebServiceBindingType.getId(), rimBinding.getId(), CanonicalConstants.CANONICAL_ASSOCIATION_TYPE_ID_Implements); //May need a more deterministic algorithm for setting this id?? ebAssociationType.setId(ebServiceBindingType.getId() + ":Implements:" + rimBinding.getId()); registryObjects.add(ebAssociationType); } catch (CatalogingException ce) { throw ce; } catch (Throwable e) { throw new CatalogingException(e); } }
From source file:org.bigtester.ate.xmlschema.BaseTestStepBeanDefinitionParser.java
/** * {@inheritDoc}//from w w w.j a v a 2 s . c o m */ @Override protected AbstractBeanDefinition parseInternal(@Nullable Element element, @Nullable ParserContext parserContext) { // Here we parse the Spring elements such as < property> if (parserContext == null || element == null) throw GlobalUtils.createNotInitializedException("element and parserContext"); BeanDefinitionHolder holder = parserContext.getDelegate().parseBeanDefinitionElement(element); BeanDefinition bDef = holder.getBeanDefinition(); bDef.setBeanClassName(BaseTestStep.class.getName()); String pageObject = element.getAttribute(XsdElementConstants.ATTR_BASETESTSTEP_PAGEOBJECT); if (StringUtils.hasText(pageObject)) { bDef.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference(pageObject)); } String myWebElement = element.getAttribute(XsdElementConstants.ATTR_BASETESTSTEP_MYWEBELEMENT); if (StringUtils.hasText(myWebElement)) { bDef.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference(myWebElement)); } String ead = element.getAttribute(XsdElementConstants.ATTR_ELEMENTSTEP_ELEMENTACTIONDEF); if (StringUtils.hasText(ead)) { bDef.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference(ead)); } boolean target = Boolean.parseBoolean(element.getAttribute(XsdElementConstants.ATTR_TESTSTEP_TARGETSTEP)); bDef.getPropertyValues().addPropertyValue(XsdElementConstants.ATTR_TESTSTEP_TARGETSTEP, target); boolean optional; if (target) { optional = false; } else { optional = Boolean.parseBoolean(element.getAttribute(XsdElementConstants.ATTR_TESTSTEP_OPTIONALSTEP)); String optionalStepUntilInclusive = element .getAttribute(XsdElementConstants.ATTR_TESTSTEP_CORRELATEDOPTIONALSTEPSUTILINCLUSIVE); bDef.getPropertyValues().addPropertyValue( XsdElementConstants.ATTR_TESTSTEP_CORRELATEDOPTIONALSTEPSUTILINCLUSIVE, optionalStepUntilInclusive); } bDef.getPropertyValues().addPropertyValue(XsdElementConstants.ATTR_TESTSTEP_OPTIONALSTEP, optional); String stepName = element.getAttribute(XsdElementConstants.ATTR_TESTSTEP_STEPNAME); bDef.getPropertyValues().addPropertyValue(XsdElementConstants.ATTR_TESTSTEP_STEPNAME, stepName); String stepDesc = element.getAttribute(XsdElementConstants.ATTR_TESTSTEP_STEPDESCRIPTION); bDef.getPropertyValues().addPropertyValue(XsdElementConstants.ATTR_TESTSTEP_STEPDESCRIPTION, stepDesc); bDef.getPropertyValues().addPropertyValue("repeatStepLogger", new RuntimeBeanReference(GlobalConstants.BEAN_ID_REPEATSTEPEXECUTIONLOGGER)); String testcaseParentName = element.getParentNode().getAttributes().getNamedItem("id").getNodeValue(); bDef.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference(testcaseParentName)); // String text = element.getAttribute("text"); // bd.getPropertyValues().addPropertyValue("text", text); parserContext.getRegistry().registerBeanDefinition(element.getAttribute("id"), bDef); return (AbstractBeanDefinition) bDef; }
From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java
private void menuItemForm(HttpServletRequest request, HttpServletResponse response, HttpSession session, AdminService admin, ExtendedMap formItems) throws VerticalAdminException { int menuKey = formItems.getInt("menukey"); User user = securityService.getLoggedInAdminConsoleUser(); String menuXML = admin.getAdminMenu(user, menuKey); boolean forwardData = formItems.getBoolean("forward_data", false); boolean create; String menuItemXML = null;/* ww w.ja va 2s .co m*/ String categoryXML = null; String pageTemplatesXML; String pageTemplateParamsXML = null; String defaultAccessRightXML = null; // menuitem key: String key = formItems.getString("key", null); try { if (key != null && !key.startsWith("f") && !key.equals("none")) { create = false; menuItemXML = admin.getMenuItem(user, Integer.parseInt(key), false, true); } else { create = true; String insertBelow = formItems.getString("insertbelow", null); if (insertBelow != null && !"-1".equals(insertBelow)) { defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM, Integer.parseInt(insertBelow), true); } else { defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM_DEFAULT, menuKey, true); } } int[] excludeTypeKeys = null; // before we excluded page-tempales of type newsletter, but not anymore. pageTemplatesXML = admin.getPageTemplatesByMenu(menuKey, excludeTypeKeys); Document doc1 = XMLTool.domparse(menuXML); Element menuElem = XMLTool.selectElement(doc1.getDocumentElement(), "//menu[@key = '" + menuKey + "']"); int pageTemplateKey = formItems.getInt("selpagetemplatekey", -1); if (pageTemplateKey < 0 && create) { // selpagetemplatekey has not been set... set it to parent or default // pagetemplatekey (if appliccable) int insertBelow = -1; if (formItems.containsKey("insertbelow") /* && formItems.get("insertbelow") instanceof Integer */ ) { insertBelow = formItems.getInt("insertbelow"); } pageTemplateKey = findParentPagetemplateKey(doc1, insertBelow); formItems.putInt("selpagetemplatekey", pageTemplateKey); } if (pageTemplateKey >= 0) { pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } else if (menuItemXML != null && XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey") != null) { pageTemplateKey = Integer.parseInt(XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey")); pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } else { String tmp = menuElem.getAttribute("defaultpagetemplate"); if (tmp != null && tmp.length() > 0) { pageTemplateKey = Integer.parseInt(tmp); pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } } // insert correct menuitem XML: Element menuitemElem = null; if (menuItemXML != null) { Document miDoc = XMLTool.domparse(menuItemXML); Element tmpElem = miDoc.getDocumentElement(); tmpElem = XMLTool.getFirstElement(tmpElem); if (tmpElem != null) { // add read count // int readCount = admin.getReadCount(LogHandler.TABLE_TMENUITEM, Integer.parseInt(key)); // Element elem = XMLTool.createElement(miDoc, tmpElem, "logentries"); // elem.setAttribute("totalread", String.valueOf(readCount)); if (tmpElem != null) { String xpath = "//menuitem[@key = '" + key + "']"; Element oldElem = (Element) XMLTool.selectNode(doc1.getDocumentElement(), xpath); if (oldElem != null) { Element menuitemsElem = (Element) oldElem.getParentNode(); menuitemElem = (Element) doc1.importNode(tmpElem, true); menuitemsElem.replaceChild(menuitemElem, oldElem); } } } } Document pageTemplateDoc = XMLTool.domparse(pageTemplatesXML); XMLTool.mergeDocuments(doc1, pageTemplateDoc, true); if (defaultAccessRightXML != null) { XMLTool.mergeDocuments(doc1, XMLTool.domparse(defaultAccessRightXML), true); } ExtendedMap parameters = new ExtendedMap(); if (forwardData) { // get accessrights element Node nodeAccessRights; if (create) { nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(), "/menus/accessrights"); } else { nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(), "//menuitem[@key=" + key + "]/accessrights"); } // get new accessrights xml from parameters String xmlAccessRights = buildAccessRightsXML(formItems); if (xmlAccessRights != null) { Document docAccessRights = XMLTool.domparse(xmlAccessRights); if (docAccessRights.getDocumentElement().hasChildNodes()) // replace accessrights element with the generated accessrights { nodeAccessRights.getParentNode().replaceChild( doc1.importNode(docAccessRights.getDocumentElement(), true), nodeAccessRights); } } // get custom parameters // get parameters element Node nodeParameters; if (create) { Node nodeMenu = XMLTool.selectNode(doc1.getDocumentElement(), "/menus"); nodeParameters = XMLTool.createElement(doc1, (Element) nodeMenu, "parameters"); nodeMenu.appendChild(nodeParameters); } else { nodeParameters = XMLTool.selectNode(doc1.getDocumentElement(), "//menuitem[@key=" + key + "]/parameters"); } XMLTool.removeChildNodes((Element) nodeParameters, false); if (isArrayFormItem(formItems, "paramname")) { String[] paramName = (String[]) formItems.get("paramname"); String[] paramValue = (String[]) formItems.get("paramval"); for (int i = 0; i < paramName.length; i++) { final String currParamName = paramName[i]; if (currParamName == null || !currParamName.trim().equals("")) { Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter", paramValue[i]); newElem.setAttribute("name", currParamName); nodeParameters.appendChild(newElem); } } } else { // ingen sideparametre finnes, vi lager en String paramName = formItems.getString("paramname", ""); String paramValue = formItems.getString("paramval", ""); if (paramName.length() > 0) { Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter", paramValue); newElem.setAttribute("name", paramName); nodeParameters.appendChild(newElem); } } parameters.put("referer", formItems.getString("referer")); } if (pageTemplateParamsXML == null) { Element nameElem = (Element) XMLTool.selectNode(doc1, "//menuitem[@key = '" + key + "']/page"); if (nameElem != null) { pageTemplateKey = Integer.parseInt(nameElem.getAttribute("pagetemplatekey")); pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } } Document doc8; if (pageTemplateParamsXML != null) { doc8 = XMLTool.domparse(pageTemplateParamsXML); XMLTool.mergeDocuments(doc1, doc8, true); } String xpath = "/pagetemplates/pagetemplate[@key=" + pageTemplateKey + "]"; Element pagetemplateElem = (Element) XMLTool.selectNode(pageTemplateDoc, xpath); if (pagetemplateElem != null) { String pageTemplateType = pagetemplateElem.getAttribute("type"); if ("form".equals(pageTemplateType)) { Element dataElem = XMLTool.getElement(menuitemElem, "data"); Element formElem = XMLTool.getElement(dataElem, "form"); if (formElem != null) { String keyStr = formElem.getAttribute("categorykey"); if (keyStr.length() > 0) { int categoryKey = Integer.parseInt(keyStr); categoryXML = admin.getCategoryNameXML(categoryKey); } } } } if (categoryXML != null) { Document doc5 = XMLTool.domparse(categoryXML); XMLTool.mergeDocuments(doc1, doc5, true); } // Get content types for this site XMLTool.mergeDocuments(doc1, admin.getContentTypes(false).getAsDOMDocument(), true); // Append languages Document langs = XMLTool.domparse(admin.getLanguages()); XMLTool.mergeDocuments(doc1, langs, true); DOMSource xmlSource = new DOMSource(doc1); // Stylesheet Source xslSource = AdminStore.getStylesheet(session, "menu_item_form.xsl"); // Parameters addCommonParameters(admin, user, request, parameters, -1, menuKey); parameters.put("page", String.valueOf(request.getParameter("page"))); if ((key == null || key.length() == 0 || key.equals("none"))) { parameters.put("key", "none"); } else { parameters.put("key", key); } String type = formItems.getString("type", null); if ((type == null || "page".equals(type)) && pageTemplateKey >= 0) { if (pagetemplateElem != null) { type = pagetemplateElem.getAttribute("type"); } } if ("document".equals(type) || "form".equals(type)) { type = "content"; } parameters.put("type", type); parameters.put("insertbelow", formItems.getString("insertbelow", null)); parameters.put("selpagetemplatekey", String.valueOf(pageTemplateKey)); parameters.put("name", formItems.getString("name", null)); if ("on".equals(formItems.getString("visibility", null))) { parameters.put("visibility", "on"); } parameters.put("forward_data", formItems.get("forward_data", Boolean.FALSE)); parameters.put("menu-name", formItems.getString("menu-name", null)); parameters.put("displayname", formItems.getString("displayname", null)); parameters.put("description", formItems.getString("description", null)); parameters.put("keywords", formItems.getString("keywords", null)); parameters.put("alias", formItems.getString("alias", null)); parameters.put("document", formItems.getString("contentdata_body", null)); if (formItems.getString("noauth", null) != null) { if ("on".equals(formItems.getString("noauth", null))) { parameters.put("noauth", "false"); } else { parameters.put("noauth", "true"); } } parameters.put("catselkey", formItems.getString("catsel", null)); parameters.put("catkey", formItems.getString("category_key", null)); parameters.put("catname", formItems.getString("viewcategory_key", null)); parameters.put("menukey", String.valueOf(menuKey)); // find content title if contentkey is specified if (menuitemElem != null) { String contentKeyStr = menuitemElem.getAttribute("contentkey"); if (contentKeyStr.length() > 0) { int contentKey = Integer.parseInt(contentKeyStr); int versionKey = admin.getCurrentVersionKey(contentKey); String contentTitle = admin.getContentTitle(versionKey); parameters.put("contenttitle", contentTitle); } } // Adds accessrights values, so that these can be remembered until next page for (Object formItemKey : formItems.keySet()) { String paramName = (String) formItemKey; if (paramName.startsWith("accessright[key=")) { parameters.put(paramName, formItems.getString(paramName)); } } parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", null)); // Get form categories int[] contentTypeKeys = admin.getContentTypesByHandlerClass( "com.enonic.vertical.adminweb.handlers.ContentFormHandlerServlet"); if (contentTypeKeys != null && contentTypeKeys.length > 0) { StringBuffer contentTypeString = new StringBuffer(); for (int i = 0; i < contentTypeKeys.length; i++) { if (i > 0) { contentTypeString.append(','); } contentTypeString.append(contentTypeKeys[i]); } parameters.put("contenttypestring", contentTypeString.toString()); } else { parameters.put("contenttypestring", "99999"); } addAccessLevelParameters(user, parameters); UserEntity defaultRunAsUser = siteDao.findByKey(formItems.getInt("menukey")).resolveDefaultRunAsUser(); String defaultRunAsUserName = "NA"; if (defaultRunAsUser != null) { defaultRunAsUserName = defaultRunAsUser.getDisplayName(); } parameters.put("defaultRunAsUser", defaultRunAsUserName); transformXML(session, response.getWriter(), xmlSource, xslSource, parameters); } catch (IOException ioe) { String msg = "I/O error: %t"; VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, ioe); } catch (TransformerException te) { String msg = "XSL transformer error: %t"; VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, te); } }