How to use getTargetCharset method of com.consol.citrus.util.XMLUtils class

Best Citrus code snippet using com.consol.citrus.util.XMLUtils.getTargetCharset

Source:XMLUtils.java Github

copy

Full Screen

...182 */183 public static String serialize(Document doc) {184 LSSerializer serializer = configurer.createLSSerializer();185 LSOutput output = configurer.createLSOutput();186 String charset = getTargetCharset(doc).displayName();187 output.setEncoding(charset);188 StringWriter writer = new StringWriter();189 output.setCharacterStream(writer);190 serializer.write(doc, output);191 return writer.toString();192 }193 /**194 * Pretty prints a XML string.195 * @param xml196 * @throws CitrusRuntimeException197 * @return pretty printed XML string198 */199 public static String prettyPrint(String xml) {200 LSParser parser = configurer.createLSParser();201 configurer.setParserConfigParameter(parser, VALIDATE_IF_SCHEMA, false);202 LSInput input = configurer.createLSInput();203 try {204 Charset charset = getTargetCharset(xml);205 input.setByteStream(new ByteArrayInputStream(xml.trim().getBytes(charset)));206 input.setEncoding(charset.displayName());207 } catch(UnsupportedEncodingException e) {208 throw new CitrusRuntimeException(e);209 }210 Document doc;211 try {212 doc = parser.parse(input);213 } catch (Exception e) {214 return xml;215 }216 return serialize(doc);217 }218 /**219 * Look up namespace attribute declarations in the specified node and220 * store them in a binding map, where the key is the namespace prefix and the value221 * is the namespace uri.222 *223 * @param referenceNode XML node to search for namespace declarations.224 * @return map containing namespace prefix - namespace url pairs.225 */226 public static Map<String, String> lookupNamespaces(Node referenceNode) {227 Map<String, String> namespaces = new HashMap<String, String>();228 Node node;229 if (referenceNode.getNodeType() == Node.DOCUMENT_NODE) {230 node = referenceNode.getFirstChild();231 } else {232 node = referenceNode;233 }234 if (node != null && node.hasAttributes()) {235 for (int i = 0; i < node.getAttributes().getLength(); i++) {236 Node attribute = node.getAttributes().item(i);237 if (attribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE + ":")) {238 namespaces.put(attribute.getNodeName().substring((XMLConstants.XMLNS_ATTRIBUTE + ":").length()), attribute.getNodeValue());239 } else if (attribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {240 //default namespace241 namespaces.put(XMLConstants.DEFAULT_NS_PREFIX, attribute.getNodeValue());242 }243 }244 }245 return namespaces;246 }247 /**248 * Look up namespace attribute declarations in the XML fragment and249 * store them in a binding map, where the key is the namespace prefix and the value250 * is the namespace uri.251 *252 * @param xml XML fragment.253 * @return map containing namespace prefix - namespace uri pairs.254 */255 public static Map<String, String> lookupNamespaces(String xml) {256 Map<String, String> namespaces = new HashMap<String, String>();257 //TODO: handle inner CDATA sections because namespaces they might interfere with real namespaces in xml fragment258 if (xml.indexOf(XMLConstants.XMLNS_ATTRIBUTE) != -1) {259 String[] tokens = StringUtils.split(xml, XMLConstants.XMLNS_ATTRIBUTE);260 do {261 String token = tokens[1];262 String nsPrefix;263 if (token.startsWith(":")) {264 nsPrefix = token.substring(1, token.indexOf('='));265 } else if (token.startsWith("=")) {266 nsPrefix = XMLConstants.DEFAULT_NS_PREFIX;267 } else {268 //we have found a "xmlns" phrase that is no namespace attribute - ignore and continue269 tokens = StringUtils.split(token, XMLConstants.XMLNS_ATTRIBUTE);270 continue;271 }272 String nsUri;273 try {274 nsUri = token.substring(token.indexOf('\"')+1, token.indexOf('\"', token.indexOf('\"')+1));275 } catch (StringIndexOutOfBoundsException e) {276 //maybe we have more luck with single "'"277 nsUri = token.substring(token.indexOf('\'')+1, token.indexOf('\'', token.indexOf('\'')+1));278 }279 namespaces.put(nsPrefix, nsUri);280 tokens = StringUtils.split(token, XMLConstants.XMLNS_ATTRIBUTE);281 } while(tokens != null);282 }283 return namespaces;284 }285 /**286 * Parse message payload with DOM implementation.287 * @param messagePayload288 * @throws CitrusRuntimeException289 * @return DOM document.290 */291 public static Document parseMessagePayload(String messagePayload) {292 LSParser parser = configurer.createLSParser();293 LSInput receivedInput = configurer.createLSInput();294 try {295 Charset charset = getTargetCharset(messagePayload);296 receivedInput.setByteStream(new ByteArrayInputStream(messagePayload.trim().getBytes(charset)));297 receivedInput.setEncoding(charset.displayName());298 } catch(UnsupportedEncodingException e) {299 throw new CitrusRuntimeException(e);300 }301 return parser.parse(receivedInput);302 }303 /**304 * Try to find encoding for document node. Also supports Citrus default encoding set305 * as System property.306 * @param doc307 * @return308 */309 public static Charset getTargetCharset(Document doc) {310 String defaultEncoding = System.getProperty(Citrus.CITRUS_FILE_ENCODING_PROPERTY, System.getenv(Citrus.CITRUS_FILE_ENCODING_ENV));311 if (StringUtils.hasText(defaultEncoding)) {312 return Charset.forName(defaultEncoding);313 }314 if (doc.getInputEncoding() != null) {315 return Charset.forName(doc.getInputEncoding());316 }317 // return as encoding the default UTF-8318 return Charset.forName("UTF-8");319 }320 /**321 * Try to find target encoding in XML declaration.322 *323 * @param messagePayload XML message payload.324 * @return charsetName if supported.325 */326 private static Charset getTargetCharset(String messagePayload) throws UnsupportedEncodingException {327 String defaultEncoding = System.getProperty(Citrus.CITRUS_FILE_ENCODING_PROPERTY, System.getenv(Citrus.CITRUS_FILE_ENCODING_ENV));328 if (StringUtils.hasText(defaultEncoding)) {329 return Charset.forName(defaultEncoding);330 }331 // trim incoming payload332 String payload = messagePayload.trim();333 char doubleQuote = '\"';334 char singleQuote = '\'';335 // make sure payload has an XML encoding string336 String encodingKey = "encoding";337 if (payload.startsWith("<?xml") && payload.contains(encodingKey) && payload.contains("?>") && (payload.indexOf(encodingKey) < payload.indexOf("?>"))) {338 // extract only encoding part, as otherwise the rest of the complete pay load will be load339 String encoding = payload.substring(payload.indexOf(encodingKey) + encodingKey.length(), payload.indexOf("?>"));340 char quoteChar = doubleQuote;...

Full Screen

Full Screen

Source:AbstractXmlDataDictionary.java Github

copy

Full Screen

...46 Document doc = XMLUtils.parseMessagePayload(messagePayload);47 LSSerializer serializer = XMLUtils.createLSSerializer();48 serializer.setFilter(new TranslateFilter(context));49 LSOutput output = XMLUtils.createLSOutput();50 String charset = XMLUtils.getTargetCharset(doc).displayName();51 output.setEncoding(charset);52 StringWriter writer = new StringWriter();53 output.setCharacterStream(writer);54 serializer.write(doc, output);55 message.setPayload(writer.toString());56 return message;57 }58 /**59 * Serializer filter uses data dictionary translation on elements and attributes.60 */61 private class TranslateFilter implements LSSerializerFilter {62 private TestContext context;63 public TranslateFilter(TestContext context) {64 this.context = context;...

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import java.io.File;3import java.io.FileInputStream;4import java.io.FileNotFoundException;5import java.io.IOException;6import java.io.InputStream;7import java.nio.charset.Charset;8import java.util.Map;9import javax.xml.parsers.DocumentBuilder;10import javax.xml.parsers.DocumentBuilderFactory;11import javax.xml.parsers.ParserConfigurationException;12import org.springframework.util.xml.SimpleNamespaceContext;13import org.w3c.dom.Document;14import org.xml.sax.SAXException;15public class XMLUtils {16 public static final String XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";17 private XMLUtils() {18 super();19 }20 public static Charset getTargetCharset(File xmlFile) throws FileNotFoundException {21 return getTargetCharset(new FileInputStream(xmlFile));22 }23 public static Charset getTargetCharset(InputStream xmlStream) {24 Document document = parseDocument(xmlStream);25 String encoding = document.getXmlEncoding();26 if (encoding != null) {27 return Charset.forName(encoding);28 }29 return Charset.forName("UTF-8");30 }31 public static Document parseDocument(InputStream xmlStream) {32 try {33 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();34 factory.setNamespaceAware(true);35 DocumentBuilder builder = factory.newDocumentBuilder();36 return builder.parse(xmlStream);37 } catch (ParserConfigurationException | SAXException | IOException e) {38 throw new CitrusRuntimeException("Failed to parse XML document", e);39 }40 }41 public static Document parseDocument(File xmlFile) throws FileNotFoundException {42 return parseDocument(new FileInputStream(xmlFile));43 }

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1import com.consol.citrus.util.XMLUtils;2public class 4 {3public static void main(String[] args) {4XMLUtils utils = new XMLUtils();5String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";6System.out.println(utils.getTargetCharset(xml));7}8}9Related Posts: Java String charAt() Method10Java String getBytes() Method11Java String toCharArray() Method12Java String charAt() Method13Java String getBytes() Method14Java String toCharArray() Method15Java String byteAt() Method16Java String getChars() Method17Java String toLowerCase() Method18Java String toUpperCase() Method19Java String trim() Method20Java String replace() Method21Java String replaceFirst() Method22Java String replaceAll() Method23Java String substring() Method24Java String split() Method25Java String join() Method26Java String strip() Method27Java String stripLeading() Method28Java String stripTrailing() Method29Java String isBlank() Method30Java String isEmpty() Method31Java String lines() Method32Java String indent() Method33Java String translateEscapes() Method34Java String toCodePoints() Method35Java String format() Method36Java String hashCode() Method37Java String equals() Method38Java String compareTo() Method39Java String compareToIgnoreCase() Method40Java String concat() Method41Java String contains() Method42Java String contentEquals() Method43Java String startsWith() Method44Java String endsWith() Method45Java String indexOf() Method46Java String lastIndexOf() Method47Java String matches() Method48Java String regionMatches() Method49Java String intern() Method50Java String valueOf() Method51Java String toString() Method52Java String toCharArray() Method53Java String getChars() Method54Java String split() Method55Java String join() Method56Java String strip() Method57Java String stripLeading() Method58Java String stripTrailing() Method59Java String isBlank() Method60Java String isEmpty() Method61Java String lines() Method62Java String indent() Method63Java String translateEscapes() Method64Java String toCodePoints() Method65Java String format() Method66Java String hashCode() Method67Java String equals() Method68Java String compareTo() Method69Java String compareToIgnoreCase() Method70Java String concat() Method71Java String contains() Method72Java String contentEquals() Method

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import java.io.ByteArrayInputStream;3import java.io.InputStream;4import java.nio.charset.Charset;5import javax.xml.transform.stream.StreamSource;6public class getTargetCharset {7 public static void main(String[] args) {8 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";9 InputStream inputStream = new ByteArrayInputStream(xml.getBytes());10 StreamSource streamSource = new StreamSource(inputStream);11 Charset charset = XMLUtils.getTargetCharset(streamSource);12 System.out.println("charset = " + charset);13 }14}

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import java.io.*;3import java.nio.charset.*;4import java.util.*;5import java.util.regex.*;6import javax.xml.parsers.*;7import javax.xml.transform.*;8import javax.xml.transform.dom.*;9import javax.xml.transform.stream.*;10import org.apache.commons.lang.*;11import org.w3c.dom.*;12import org.xml.sax.*;13public class XMLUtils {14 private static final String DEFAULT_CHARSET = "UTF-8";15 private XMLUtils() {16 super();17 }18 public static Document parseMessage(String xmlString) {19 return parseMessage(xmlString, DEFAULT_CHARSET);20 }21 public static Document parseMessage(String xmlString, String charset) {22 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();23 factory.setNamespaceAware(true);24 DocumentBuilder builder = null;25 try {26 builder = factory.newDocumentBuilder();27 return builder.parse(new ByteArrayInputStream(xmlString.getBytes(charset)));28 } catch (ParserConfigurationException e) {29 throw new CitrusRuntimeException("Failed to create XML document builder", e);30 } catch (UnsupportedEncodingException e) {31 throw new CitrusRuntimeException("Unsupported charset", e);32 } catch (SAXException e) {33 throw new CitrusRuntimeException("Failed to parse XML document", e);34 } catch (IOException e) {35 throw new CitrusRuntimeException("Failed to parse XML document", e);36 }37 }38 public static String createXmlString(Document document) {39 return createXmlString(document, DEFAULT_CHARSET);40 }41 public static String createXmlString(Document document, String charset) {42 try {43 TransformerFactory transformerFactory = TransformerFactory.newInstance();44 Transformer transformer = transformerFactory.newTransformer();45 transformer.setOutputProperty(OutputKeys.INDENT, "yes");

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import java.io.File;3import java.io.IOException;4import java.nio.charset.Charset;5import org.apache.commons.io.FileUtils;6import org.springframework.util.xml.SimpleNamespaceContext;7import org.testng.Assert;8import org.testng.annotations.Test;9import com.consol.citrus.exceptions.CitrusRuntimeException;10public class XMLUtilsTest {11 public void testGetTargetCharset() {12 "</ns2:Root>";13 SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();14 Assert.assertEquals(XMLUtils.getTargetCharset(xml, namespaceContext), Charset.forName("UTF-8"));15 }16 public void testGetTargetCharsetWithDefault() {17 "</ns2:Root>";18 SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();19 Assert.assertEquals(XMLUtils.getTargetCharset(xml, namespaceContext, Charset.defaultCharset()), Charset.defaultCharset());20 }21 @Test(expectedExceptions = CitrusRuntimeException.class)22 public void testGetTargetCharsetWithException() {23 "</ns2:Root>";24 SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import java.io.IOException;3import java.nio.charset.Charset;4import java.nio.charset.StandardCharsets;5import org.springframework.util.xml.SimpleTransformErrorListener;6import org.xml.sax.InputSource;7import org.xml.sax.SAXException;8import org.xml.sax.XMLReader;9import com.consol.citrus.exceptions.CitrusRuntimeException;10import com.consol.citrus.util.XMLUtils;11public class getTargetCharset {12 public static void main(String[] args) throws IOException, SAXException {13 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><child>test</child></root>";14 InputSource xmlInputSource = new InputSource();15 xmlInputSource.setByteStream(new java.io.ByteArrayInputStream(xml.getBytes()));16 XMLReader xmlReader = XMLUtils.createXMLReader();17 xmlReader.setErrorHandler(new SimpleTransformErrorListener());18 xmlReader.parse(xmlInputSource);19 Charset targetCharset = XMLUtils.getTargetCharset(xmlReader);20 System.out.println(targetCharset);21 }22}

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import org.testng.annotations.Test;3public class getTargetCharsetTest {4public void getTargetCharset() {5XMLUtils.getTargetCharset();6}7}

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import java.io.*;3import java.nio.charset.*;4import java.nio.file.*;5import java.nio.file.attribute.*;6import java.util.*;7import javax.xml.transform.*;8import javax.xml.transform.stream.*;9import org.xml.sax.*;10{11public static String getTargetCharset(Source source) throws TransformerException12{13TransformerFactory factory = TransformerFactory.newInstance();14Transformer transformer = factory.newTransformer();15Properties outputProps = transformer.getOutputProperties();16String encoding = outputProps.getProperty(OutputKeys.ENCODING);17if (encoding == null)18{19encoding = Charset.defaultCharset().name();20}21return encoding;22}23public static void main(String[] args) throws IOException, TransformerException, SAXException24{25String str = new String(Files.readAllBytes(Paths.get("C:\\Users\\Admin\\Desktop\\4.xml")));26StreamSource source = new StreamSource(new StringReader(str));27System.out.println(getTargetCharset(source));28}29}

Full Screen

Full Screen

getTargetCharset

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.util;2import java.io.*;3import javax.xml.transform.*;4import javax.xml.transform.stream.*;5public class XMLUtilsGetTargetCharset {6 public static void main(String[] args) throws Exception {7 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";8 TransformerFactory transformerFactory = TransformerFactory.newInstance();9 Transformer transformer = transformerFactory.newTransformer();10 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");11 transformer.setOutputProperty(OutputKeys.INDENT, "yes");12 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");13 StringWriter writer = new StringWriter();14 transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(writer));15 String output = writer.getBuffer().toString();16 System.out.println(XMLUtils.getTargetCharset(output));17 }18}19public static String getTargetCharset(String xml) {20 try {21 Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));22 return document.getXmlEncoding();23 } catch (Exception e) {24 return null;25 }26}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful