List of usage examples for org.w3c.dom Element getOwnerDocument
public Document getOwnerDocument();
Document
object associated with this node. From source file:com.haulmont.cuba.restapi.XMLConverter.java
@Override public String process(Entity entity, MetaClass metaclass, View view) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { Element root = newDocument(ROOT_ELEMENT_INSTANCE); encodeEntityInstance(new HashSet<Entity>(), entity, root, false, metaclass, view); Document doc = root.getOwnerDocument(); return documentToString(doc); }
From source file:com.dragoniade.deviantart.deviation.SearchRss.java
private int retrieveTotal(ProgressDialog progress, Collection collection) { int offset = collection == null ? 6000 : 480; int greaterThan = 0; int lessThan = Integer.MAX_VALUE; int iteration = 0; String searchQuery = search.getSearch().replace("%username%", user); while (total < 0) { if (progress.isCancelled()) { return -1; }//from ww w .j ava2 s . c o m progress.setText("Fetching total (" + ++iteration + ")"); String queryString = "http://backend.deviantart.com/rss.xml?q=" + searchQuery + (collection == null ? "" : "/" + collection.getId()) + "&type=deviation&offset=" + offset; GetMethod method = new GetMethod(queryString); try { int sc = -1; do { sc = client.executeMethod(method); if (sc != 200) { LoggableException ex = new LoggableException(method.getResponseBodyAsString()); Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex); int res = DialogHelper.showConfirmDialog(owner, "An error has occured when contacting deviantART : error " + sc + ". Try again?", "Continue?", JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) { return -1; } } } while (sc != 200); XmlToolkit toolkit = XmlToolkit.getInstance(); Element responses = toolkit.parseDocument(method.getResponseBodyAsStream()); method.releaseConnection(); List<?> deviations = toolkit.getMultipleNodes(responses, "channel/item"); HashMap<String, String> prefixes = new HashMap<String, String>(); prefixes.put("atom", responses.getOwnerDocument().lookupNamespaceURI("atom")); Node next = toolkit.getSingleNode(responses, "channel/atom:link[@rel='next']", toolkit.getNamespaceContext(prefixes)); int size = deviations.size(); if (debug) { System.out.println(); System.out.println(); System.out.println("Lesser Than: " + lessThan); System.out.println("Greater Than: " + greaterThan); System.out.println("Offset: " + offset); System.out.println("Size: " + size); } if (size != OFFSET && size > 0) { if (next != null) { greaterThan = offset + OFFSET; } else { if (debug) System.out.println("Total (offset + size) : " + (offset + size)); return offset + size; } } // Page is full, there is more deviations if (size == OFFSET) { greaterThan = offset + OFFSET; } if (size == 0) { lessThan = offset; } if (greaterThan == lessThan) { if (debug) System.out.println("Total (greaterThan) : " + greaterThan); return greaterThan; } if (lessThan == Integer.MAX_VALUE) { offset = offset * 2; } else { offset = (greaterThan + lessThan) / 2; if (offset % 60 != 0) { offset = (offset / 60) * 60; } } try { Thread.sleep(500); } catch (InterruptedException e) { } } catch (IOException e) { int res = DialogHelper.showConfirmDialog(owner, "An error has occured when contacting deviantART : error " + e + ". Try again?", "Continue?", JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) { return -1; } } } return total; }
From source file:com.mirth.connect.model.util.ImportConverter.java
public static Document convertCodeTemplates(String codeTemplatesXML) throws Exception { codeTemplatesXML = convertPackageNames(codeTemplatesXML); codeTemplatesXML = runStringConversions(codeTemplatesXML); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document;/*from ww w . ja v a 2s . c om*/ DocumentBuilder builder; builder = factory.newDocumentBuilder(); document = builder.parse(new InputSource(new StringReader(codeTemplatesXML))); NodeList codeTemplates = getElements(document, "codeTemplate", "com.mirth.connect.model.CodeTemplate"); int length = codeTemplates.getLength(); for (int i = 0; i < length; i++) { Element codeTemplate = (Element) codeTemplates.item(i); codeTemplate.getOwnerDocument().renameNode(codeTemplate, codeTemplate.getNamespaceURI(), "codeTemplate"); NodeList versions = codeTemplate.getElementsByTagName("version"); // If there is no version, then this is a migration to 2.0 and the // scope should be incremented by 1 if its value is not currently 0 // (global map). Global Channel Map was added in position 1 for 2.0. if (versions.getLength() == 0) { Element scope = (Element) codeTemplate.getElementsByTagName("scope").item(0); int scopeValue = Integer.parseInt(scope.getTextContent()); if (scopeValue != 0) { scopeValue++; scope.setTextContent(Integer.toString(scopeValue)); } } } return document; }
From source file:it.pronetics.madstore.crawler.publisher.impl.AtomPublisherImpl.java
private void setUpdatedDateTimeIfNecessary(Element entry) { NodeList updatedNodes = entry.getElementsByTagName(AtomConstants.ATOM_ENTRY_UPDATED); Node updatedNode = updatedNodes.item(0); if (updatedNode != null) { String entryUpdatedDateTime = updatedNode.getTextContent(); if (entryUpdatedDateTime == null || entryUpdatedDateTime.equals("")) { LOG.warn("The entry has no updated date, using current time ..."); updatedNode.setTextContent(ISODateTimeFormat.dateTime().print(System.currentTimeMillis())); }/* w w w .ja v a2s .c om*/ } else { LOG.warn("The entry has no updated date, using current time ..."); updatedNode = entry.getOwnerDocument().createElementNS(AtomConstants.ATOM_NS, AtomConstants.ATOM_ENTRY_UPDATED); updatedNode.setTextContent(ISODateTimeFormat.dateTime().print(System.currentTimeMillis())); entry.appendChild(updatedNode); } }
From source file:com.alfaariss.oa.profile.saml2.SAML2Profile.java
private void handleMetaData(HttpServletResponse servletResponse) throws OAException { PrintWriter oPWOut = null;//w w w .ja v a 2 s .com try { // Marshall the metadata: MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory(); Marshaller marshaller = marshallerFactory.getMarshaller(_entityDescriptor); Element e = marshaller.marshall(_entityDescriptor); servletResponse.setContentType(SAML2Constants.METADATA_CONTENT_TYPE); servletResponse.setHeader("Content-Disposition", "attachment; filename=metadata.xml"); //TODO EVB, MHO: cache processing conform RFC2616 [saml-metadata r1404] oPWOut = servletResponse.getWriter(); String s = XMLUtils.getStringFromDocument(e.getOwnerDocument()); oPWOut.write(s); } catch (IOException e) { _logger.warn("I/O error while processing metadata request", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } catch (Exception e) { _logger.warn("Internal error while processing metadata request", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } finally { if (oPWOut != null) oPWOut.close(); } }
From source file:com.enonic.cms.web.portal.services.ContentServicesBase.java
protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem, ExtendedMap formItems, boolean skipEmptyElements) { Document doc = contentdataElem.getOwnerDocument(); Element moduleElement = (Element) formItems.get("__module_element"); contentdataElem.setAttribute("version", "1.0"); // Date conversion objects NodeList blockElements;// ww w.ja v a 2 s .c om try { blockElements = XMLTool.selectNodes(moduleElement, "form/block"); for (int k = 0; k < blockElements.getLength(); ++k) { Element blockElement = (Element) blockElements.item(k); NodeList inputElements = XMLTool.selectNodes(blockElement, "input"); boolean groupBlock = false; String groupXPath = blockElement.getAttribute("group"); if (groupXPath != null && groupXPath.length() > 0) { groupBlock = true; } if (!groupBlock) { createNormalBlock(formItems, doc, contentdataElem, inputElements, skipEmptyElements); } else { createGroupBlock(formItems, doc, contentdataElem, inputElements, groupXPath, k + 1); } } } catch (ParseException pe) { String message = "Failed to parse a date: %t"; VerticalUserServicesLogger.warnUserServices(message, pe); } }
From source file:hoot.services.models.osm.Way.java
/** * Returns an XML representation of the element returned in a query; does * not add tags; assumes way nodes have already been written to the services * db//from ww w . j a va 2 s. c o m * * @param parentXml * XML node this element should be attached under * @param modifyingUserId * ID of the user which created this element * @param modifyingUserDisplayName * user display name of the user which created this element * @param multiLayerUniqueElementIds * if true, IDs are prepended with <map id>_<first letter of the * element type>_; this setting activated is not compatible with * standard OSM clients (specific to Hootenanny iD) * @param addChildren * if true, element children are added to the element xml * @return an XML element */ @Override public org.w3c.dom.Element toXml(org.w3c.dom.Element parentXml, long modifyingUserId, String modifyingUserDisplayName, boolean multiLayerUniqueElementIds, boolean addChildren) { org.w3c.dom.Element element = super.toXml(parentXml, modifyingUserId, modifyingUserDisplayName, multiLayerUniqueElementIds, addChildren); Document doc = parentXml.getOwnerDocument(); if (addChildren) { List<Long> nodeIds = getNodeIds(); Set<Long> elementIds = new HashSet<>(); // way nodes are output in sequence order; list should already be sorted by the query for (long nodeId : nodeIds) { org.w3c.dom.Element nodeElement = doc.createElement("nd"); nodeElement.setAttribute("ref", String.valueOf(nodeId)); element.appendChild(nodeElement); elementIds.add(nodeId); } List<Tuple> elementRecords = (List<Tuple>) Element.getElementRecordsWithUserInfo(getMapId(), ElementType.Node, elementIds, conn); for (Tuple elementRecord : elementRecords) { Element nodeFullElement = ElementFactory.create(ElementType.Node, elementRecord, conn, getMapId()); org.w3c.dom.Element nodeXml = nodeFullElement.toXml(parentXml, modifyingUserId, modifyingUserDisplayName, false, false); parentXml.appendChild(nodeXml); } } org.w3c.dom.Element elementWithTags = addTagsXml(element); if (elementWithTags == null) { return element; } return elementWithTags; }
From source file:com.haulmont.cuba.restapi.XMLConverter.java
@Override public String process(List<Entity> entities, MetaClass metaClass, View view) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { Element root = newDocument(ROOT_ELEMENT_INSTANCE); for (Entity entity : entities) { encodeEntityInstance(new HashSet<Entity>(), entity, root, false, metaClass, view); }//from w w w . jav a 2 s . c om Document doc = root.getOwnerDocument(); return documentToString(doc); }
From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public Element toDomElement(Object jaxbElement, Document doc, boolean adopt, boolean clone, boolean deep) throws JAXBException { if (jaxbElement == null) { return null; }//from ww w .j a va 2 s . c o m if (jaxbElement instanceof Element) { Element domElement = (Element) jaxbElement; if (clone) { domElement = (Element) domElement.cloneNode(deep); } if (domElement.getOwnerDocument().equals(doc)) { return domElement; } if (adopt) { doc.adoptNode(domElement); } return domElement; } else if (jaxbElement instanceof JAXBElement) { return marshalElementToDom((JAXBElement) jaxbElement, doc); } else { throw new IllegalArgumentException( "Not an element: " + jaxbElement + " (" + jaxbElement.getClass().getName() + ")"); } }
From source file:be.fedict.eid.idp.protocol.ws_federation.AbstractWSFederationProtocolService.java
private String getWResult(String wctx, String wtrealm, String userId, Map<String, Attribute> attributes, SecretKey secretKey, PublicKey publicKey) throws TransformerException, IOException { RequestSecurityTokenResponseCollection requestSecurityTokenResponseCollection = Saml2Util.buildXMLObject( RequestSecurityTokenResponseCollection.class, RequestSecurityTokenResponseCollection.ELEMENT_NAME); RequestSecurityTokenResponse requestSecurityTokenResponse = Saml2Util .buildXMLObject(RequestSecurityTokenResponse.class, RequestSecurityTokenResponse.ELEMENT_NAME); requestSecurityTokenResponseCollection.getRequestSecurityTokenResponses().add(requestSecurityTokenResponse); if (null != wctx) { requestSecurityTokenResponse.setContext(wctx); }/*from w ww. jav a 2s. c o m*/ TokenType tokenType = Saml2Util.buildXMLObject(TokenType.class, TokenType.ELEMENT_NAME); tokenType.setValue(SAMLConstants.SAML20_NS); RequestType requestType = Saml2Util.buildXMLObject(RequestType.class, RequestType.ELEMENT_NAME); requestType.setValue("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue"); KeyType keyType = Saml2Util.buildXMLObject(KeyType.class, KeyType.ELEMENT_NAME); keyType.setValue("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer"); RequestedSecurityToken requestedSecurityToken = Saml2Util.buildXMLObject(RequestedSecurityToken.class, RequestedSecurityToken.ELEMENT_NAME); requestSecurityTokenResponse.getUnknownXMLObjects().add(tokenType); requestSecurityTokenResponse.getUnknownXMLObjects().add(requestType); requestSecurityTokenResponse.getUnknownXMLObjects().add(keyType); requestSecurityTokenResponse.getUnknownXMLObjects().add(requestedSecurityToken); String issuerName = this.configuration.getDefaultIssuer(); DateTime issueInstantDateTime = new DateTime(); Assertion assertion = Saml2Util.getAssertion(issuerName, null, wtrealm, wtrealm, configuration.getResponseTokenValidity(), issueInstantDateTime, getAuthenticationPolicy(), userId, attributes, secretKey, publicKey); requestedSecurityToken.setUnknownXMLObject(assertion); Element element; IdPIdentity idpIdentity = this.configuration.findIdentity(); if (null != idpIdentity) { LOG.debug("sign assertion"); element = Saml2Util.signAsElement(requestSecurityTokenResponseCollection, assertion, idpIdentity.getPrivateKeyEntry()); } else { LOG.warn("assertion NOT signed!"); element = Saml2Util.marshall(requestSecurityTokenResponseCollection); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Saml2Util.writeDocument(element.getOwnerDocument(), outputStream); String wresult = new String(outputStream.toByteArray(), Charset.forName("UTF-8")); LOG.debug("wresult=\"" + wresult + "\""); return wresult; }