@Get("xml") public Representation toXml() { try { DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML); // Generate a DOM document representing the item. Document d = representation.getDocument(); Element eltItem = d.createElement("item"); d.appendChild(eltItem); Element eltName = d.createElement("name"); eltName.appendChild(d.createTextNode(item.getName())); eltItem.appendChild(eltName); Element eltDescription = d.createElement("description"); eltDescription.appendChild(d.createTextNode(item.getDescription())); eltItem.appendChild(eltDescription); d.normalizeDocument(); // Returns the XML representation of this document. return representation; } catch (IOException e) { e.printStackTrace(); } return null; }
/** * This method serializes the BPMN2 model into an XML representation. * * @param defns The BPMN2 model * @param os The output stream * @param prefixes The optional map of prefixes against namespaces * @param classLoader The classloader to be used * @throws IOException Failed to serialize * @deprecated Should use the org.savara.bpmn2.model.util.BPMN2ModelUtil class */ public static void serialize( TDefinitions defns, java.io.OutputStream os, java.util.Map<String, String> prefixes, java.lang.ClassLoader classLoader) throws IOException { try { org.savara.bpmn2.model.ObjectFactory factory = new org.savara.bpmn2.model.ObjectFactory(); // JAXBContext context = JAXBContext.newInstance(TDefinitions.class); JAXBContext context = JAXBContext.newInstance("org.savara.bpmn2.model", classLoader); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // SAVARA-175 - it seems that to get jaxb to generate the namespace prefix // mapping at the top of the document, it is necessary to (1) have the TProcess // created with the original namespace prefix mappings, which on initial // marshalling will be moved on to the elements that have the prefix, and // then (2) reapply the prefixes by building the DOM, adding the prefix // namespace info, and then transforming back to text. if (prefixes != null) { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); marshaller.marshal(factory.createDefinitions(defns), baos); // Convert to DOM javax.xml.parsers.DocumentBuilderFactory dbfactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbfactory.setNamespaceAware(false); org.w3c.dom.Document doc = dbfactory .newDocumentBuilder() .parse(new java.io.ByteArrayInputStream(baos.toByteArray())); for (String ns : prefixes.keySet()) { String prefix = prefixes.get(ns); doc.getDocumentElement().setAttribute("xmlns:" + prefix, ns); } doc.normalizeDocument(); javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc); javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os); javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory.newInstance().newTransformer(); transformer.transform(source, result); } else { marshaller.marshal(factory.createDefinitions(defns), os); } } catch (Exception e) { throw new IOException("Failed to serialize BPMN2 definitions", e); } }
public static void validate(Document d, String schema, DOMErrorHandler handler) { DOMConfiguration config = d.getDomConfig(); config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); config.setParameter("validate", true); config.setParameter("schema-location", schema); config.setParameter("resource-resolver", new ClasspathResourceResolver()); config.setParameter("error-handler", handler); d.normalizeDocument(); }
public static Document getDocument(File xml) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse(xml); document.normalizeDocument(); return document; }
@Post("xml") public Representation acceptItem(Representation entity) { DomRepresentation result = null; Document d = null; try { DomRepresentation input = new DomRepresentation(entity); Document doc = input.getDocument(); // handle input document Element rootEl = doc.getDocumentElement(); String usernameDoctor = XMLUtils.getTextValue(rootEl, "username"); // output result = new DomRepresentation(MediaType.TEXT_XML); d = result.getDocument(); try { ObjectifyService.register(Patient.class); ObjectifyService.register(Relative.class); } catch (Exception e) { } Key<Relative> doctor = new Key<Relative>(Relative.class, usernameDoctor); Objectify ofy = ObjectifyService.begin(); List<Patient> listRU = ofy.query(Patient.class).filter("doctor", doctor).list(); Element root = d.createElement("getUsers"); d.appendChild(root); Element eltName4 = d.createElement("getUsersList"); for (Patient us : listRU) { Element user = d.createElement("user"); user.setAttribute("firstname", "" + us.getFirstName()); user.setAttribute("lastname", "" + us.getLastName()); user.setAttribute("username", "" + us.getUsername()); user.setAttribute("password", "" + us.getPassword()); user.appendChild(d.createTextNode(us.getUsername())); eltName4.appendChild(user); } root.appendChild(eltName4); d.normalizeDocument(); } catch (Exception e) { result = XMLUtils.createXMLError("get doctors list error", "" + e.getMessage()); } return result; }
public Document extractDocument(InputSource inputSource, XmlRequestMatcher xmlRequestMatcher) throws SAXException { try { Document document = xmlRequestMatcher.documentBuilder.parse(inputSource); document.normalizeDocument(); trimNode(document); return document; } catch (IOException e) { throw new RuntimeException(e); } }
public static Map<String, NutMap> read(String path) { Map<String, NutMap> maps = new LinkedHashMap<>(); Document doc = Xmls.xml(DubboConfigureReader.class.getClassLoader().getResourceAsStream(path)); doc.normalizeDocument(); Element top = doc.getDocumentElement(); NodeList list = top.getChildNodes(); int count = list.getLength(); for (int i = 0; i < count; i++) { Node node = list.item(i); if (node instanceof Element) { Element ele = (Element) node; String eleName = ele.getNodeName(); if (!eleName.startsWith("dubbo:")) continue; // 跳过非dubbo节点 String typeName = eleName.substring("dubbo:".length()); NutMap attrs = toAttrMap(ele.getAttributes()); log.debug("found " + typeName); String genBeanName = ele.getAttribute("id"); if (Strings.isBlank(genBeanName)) { if ("protocol".equals(typeName)) genBeanName = "dubbo"; else { genBeanName = ele.getAttribute("interface"); if (Strings.isBlank(genBeanName)) { try { genBeanName = Class.forName( "com.alibaba.dubbo.config." + Strings.upperFirst(typeName) + "Config") .getName(); } catch (ClassNotFoundException e) { throw Lang.wrapThrow(e); } } } if (maps.containsKey(genBeanName)) { int _count = 2; while (true) { String key = genBeanName + "_" + _count; if (maps.containsKey(key)) { _count++; continue; } genBeanName += "_" + _count; break; } } } attrs.put("_typeName", typeName); maps.put(genBeanName, attrs); } } return maps; }
/** * Handle HTTP GET Metod / xml * * @return an XML list of contacts. */ @Get("xml") public Representation toXML() { // System.out.println("Request Original Ref " + getOriginalRef()); // System.out.println("Request Entity " + getRequest().getEntityAsText() // + // " entity mediaType " + getRequest().getEntity().getMediaType()); Reference ref = getRequest().getResourceRef(); final String baseURL = ref.getHierarchicalPart(); Form formQuery = ref.getQueryAsForm(); try { DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML); Document d = representation.getDocument(); Element elContacts = d.createElement(CONTACTS); d.appendChild(elContacts); Iterator<Contact> it = getSortedContacts(formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME)).iterator(); while (it.hasNext()) { Contact contact = it.next(); Element el = d.createElement(CONTACT); Element id = d.createElement(ID); id.appendChild(d.createTextNode(String.format("%s", contact.getId()))); el.appendChild(id); Element firstname = d.createElement(FIRST_NAME); firstname.appendChild(d.createTextNode(contact.getFirstName())); el.appendChild(firstname); Element lastname = d.createElement(LAST_NAME); lastname.appendChild(d.createTextNode(contact.getLastName())); el.appendChild(lastname); Element url = d.createElement(URL); url.appendChild(d.createTextNode(String.format("%s/%s", baseURL, contact.getId()))); el.appendChild(url); elContacts.appendChild(el); } d.normalizeDocument(); return representation; } catch (Exception e) { setStatus(Status.SERVER_ERROR_INTERNAL); return null; } }
/** * Adds a new gerritProject configuration to the gived XML document. Assumes that the document is * structured like the original project config.xml in the LocalData for this class. * * @param gerritProjectPattern the {@link GerritProject#pattern} to set. * @param document the config.xml * @return the new xml * @throws Exception if so */ private String changeConfigXml(String gerritProjectPattern, Document document) throws Exception { Node projects = xPath(document, "/project/triggers/*[1]/gerritProjects"); String tagName = "com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.GerritProject"; Node newProject = document.createElement(tagName); setXmlConfig(document, newProject, "ANT", gerritProjectPattern); Node branches = document.createElement("branches"); tagName = "com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.Branch"; Node branch = document.createElement(tagName); setXmlConfig(document, branch, "ANT", "**"); branches.appendChild(branch); newProject.appendChild(branches); projects.appendChild(newProject); document.normalizeDocument(); return xmlToString(document); }
public ResponseConnector(String datafile, String prefix, String keys, IResolveContent resolver) { _prefix = prefix; if (keys == null || keys.equals("")) return; Document doc = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(new File(datafile)); doc.normalizeDocument(); String[] parts = keys.split(";"); XPath xpath = XPathFactoryInstanceHolder.get().newXPath(); for (String part : parts) { NodeList nodes = (NodeList) xpath.evaluate( "Test[@name='" + part + "']", doc.getDocumentElement(), XPathConstants.NODESET); if (nodes.getLength() == 0) continue; Node node = nodes.item(0); NodeList responses = (NodeList) xpath.evaluate("Response", node, XPathConstants.NODESET); for (int i = 0; i < responses.getLength(); ++i) { Element response = (Element) responses.item(i); String value = resolver.resolve(response); _data.put(response.getAttribute("path"), value); } } } catch (ParserConfigurationException e) { throw new RuntimeException("Parser Configuration Error ", e); } catch (IOException e) { throw new RuntimeException("IO Error ", e); } catch (SAXException e) { throw new RuntimeException("SAX Error ", e); } catch (XPathExpressionException e) { throw new RuntimeException("XPath exception", e); } }
protected Document xmlFile2Doc(File f) throws Exception { InputStream in = null; try { in = new FileInputStream(f); DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance(); domFact.setNamespaceAware(true); domFact.setIgnoringElementContentWhitespace(true); domFact.setIgnoringComments(true); domFact.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder domBuilder = domFact.newDocumentBuilder(); Document doc = domBuilder.parse(in); doc.normalizeDocument(); return doc; } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } }
protected Document parseCallResult(InputStream data, IFacebookMethod method) throws FacebookException, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(namespaceAware); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(data); doc.normalizeDocument(); stripEmptyTextNodes(doc); printDom(doc, method.methodName() + "| "); NodeList errors = doc.getElementsByTagName(ERROR_TAG); if (errors.getLength() > 0) { int errorCode = Integer.parseInt(errors.item(0).getFirstChild().getFirstChild().getTextContent()); String message = errors.item(0).getFirstChild().getNextSibling().getTextContent(); throw new FacebookException(errorCode, message); } return doc; } catch (ParserConfigurationException ex) { throw new RuntimeException("Trouble configuring XML Parser", ex); } catch (SAXException ex) { throw new RuntimeException("Trouble parsing XML from facebook", ex); } }
/** * DOM3 method: Normalize the document with namespaces * * @param doc * @return */ public static Document normalizeNamespaces(Document doc) { DOMConfiguration docConfig = doc.getDomConfig(); docConfig.setParameter("namespaces", Boolean.TRUE); doc.normalizeDocument(); return doc; }
@Override public String invokeIncidentSearchRequest( IncidentSearchRequest incidentSearchRequest, String federatedQueryID, Element samlToken) throws Exception { if (allowQueriesWithoutSAMLToken) { if (samlToken == null) { // Add SAML token to request call samlToken = SAMLTokenUtils.createStaticAssertionAsElement( "https://idp.ojbc-local.org:9443/idp/shibboleth", SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS, SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1, true, true, null); } } if (samlToken == null) { throw new Exception("No SAML token provided. Unable to perform query."); } // POJO to XML Request // When multiple operations are supported, we will call the appropriate POJO to XML Method Document incidentRequestPayload = RequestMessageBuilderUtilities.createIncidentSearchRequest( incidentSearchRequest, cityTownCodelistNamespace, cityTownCodelistElementName); incidentRequestPayload.normalizeDocument(); log.debug(OJBUtils.getStringFromDocument(incidentRequestPayload)); // Create exchange Exchange senderExchange = new DefaultExchange(camelContext, ExchangePattern.InOnly); // Set exchange body to XML Request message senderExchange.getIn().setBody(incidentRequestPayload); // Set reply to and WS-Addressing message ID senderExchange.getIn().setHeader("federatedQueryRequestGUID", federatedQueryID); senderExchange.getIn().setHeader("WSAddressingReplyTo", this.getReplyToAddress()); // Set the token header so that CXF can retrieve this on the outbound call String tokenID = senderExchange.getExchangeId(); senderExchange.getIn().setHeader("tokenID", tokenID); OJBSamlMap.putToken(tokenID, samlToken); incidentSearchMessageProcessor.sendResponseMessage(camelContext, senderExchange); // Put message ID and "noResponse" place holder. putRequestInMap(federatedQueryID); String response = pollMap(federatedQueryID); if (response.length() > 500) { log.debug("Here is the response (truncated): " + response.substring(0, 500)); } else { log.debug("Here is the response: " + response); } // This is a defensive check in case the polling completes and the service has not yet returned // a response // In this case we send back an empty search result if (response.equals(NO_RESPONSE)) { log.debug("Endpoints timed out and no response recieved at web app, create error response"); response = MergeNotificationErrorProcessor.returnMergeNotificationErrorMessage(); } // return response here return response; }
/** * Pulls the root element of a DOM document. * * @param document the document * @param normalize whether or not to normalize the document * @return the element */ public Element pull(Document document, boolean normalize) { if (normalize) { document.normalizeDocument(); } return pull(document.getDocumentElement(), normalize); }
public static void start(CommandLine commandLine) throws Exception { List<SimpleWitness> witnesses = null; Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT; Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS; Comparator<Token> comparator = new EqualityTokenComparator(); CollationAlgorithm collationAlgorithm = null; boolean joined = true; final String[] witnessSpecs = commandLine.getArgs(); final InputStream[] inputStreams = new InputStream[witnessSpecs.length]; for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) { try { inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]); } catch (MalformedURLException urlEx) { throw new ParseException("Invalid resource: " + witnessSpecs[wc]); } } if (inputStreams.length < 1) { throw new ParseException("No input resource(s) given"); } else if (inputStreams.length < 2) { try (InputStream inputStream = inputStreams[0]) { final SimpleCollation collation = JsonProcessor.read(inputStream); witnesses = collation.getWitnesses(); collationAlgorithm = collation.getAlgorithm(); joined = collation.isJoined(); } } final String script = commandLine.getOptionValue("s"); try { final PluginScript pluginScript = (script == null ? PluginScript.read("<internal>", new StringReader("")) : PluginScript.read(argumentToInput(script))); tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer); normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer); comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator); } catch (IOException e) { throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage()); } switch (commandLine.getOptionValue("a", "").toLowerCase()) { case "needleman-wunsch": collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator); break; case "medite": collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR); break; case "gst": collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2); break; default: collationAlgorithm = Optional.ofNullable(collationAlgorithm) .orElse(CollationAlgorithmFactory.dekker(comparator)); break; } if (witnesses == null) { final Charset inputCharset = Charset.forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name())); final boolean xmlMode = commandLine.hasOption("xml"); final XPathExpression tokenXPath = XPathFactory.newInstance() .newXPath() .compile(commandLine.getOptionValue("xp", "//text()")); witnesses = new ArrayList<>(inputStreams.length); for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) { try (InputStream stream = inputStreams[wc]) { final String sigil = "w" + (wc + 1); if (!xmlMode) { final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, inputCharset)); final StringWriter writer = new StringWriter(); final char[] buf = new char[1024]; while (reader.read(buf) != -1) { writer.write(buf); } witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer)); } else { final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final Document document = documentBuilder.parse(stream); document.normalizeDocument(); final SimpleWitness witness = new SimpleWitness(sigil); final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document, XPathConstants.NODESET); final List<Token> tokens = new ArrayList<>(tokenNodes.getLength()); for (int nc = 0; nc < tokenNodes.getLength(); nc++) { final String tokenText = tokenNodes.item(nc).getTextContent(); tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText))); } witness.setTokens(tokens); witnesses.add(witness); } } } } final VariantGraph variantGraph = new VariantGraph(); collationAlgorithm.collate(variantGraph, witnesses); if (joined && !commandLine.hasOption("t")) { VariantGraph.JOIN.apply(variantGraph); } final String output = commandLine.getOptionValue("o", "-"); final Charset outputCharset = Charset.forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name())); final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase(); try (PrintWriter out = argumentToOutput(output, outputCharset)) { final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph); if ("csv".equals(outputFormat)) { serializer.toCsv(out); } else if ("dot".equals(outputFormat)) { serializer.toDot(out); } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) { XMLStreamWriter xml = null; try { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xml.writeStartDocument(outputCharset.name(), "1.0"); if ("graphml".equals(outputFormat)) { serializer.toGraphML(xml); } else { serializer.toTEI(xml); } xml.writeEndDocument(); } catch (XMLStreamException e) { throw new IOException(e); } finally { if (xml != null) { try { xml.close(); } catch (XMLStreamException e) { // ignored } } } } else { JsonProcessor.write(variantGraph, out); } } }