2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.samsungtv.internal.service;
15 import java.io.IOException;
16 import java.io.StringReader;
17 import java.util.HashMap;
19 import javax.xml.parsers.DocumentBuilder;
20 import javax.xml.parsers.DocumentBuilderFactory;
21 import javax.xml.parsers.ParserConfigurationException;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.w3c.dom.Document;
26 import org.xml.sax.InputSource;
27 import org.xml.sax.SAXException;
30 * The {@link SamsungTvUtils} provides some utilities for internal use.
32 * @author Pauli Anttila - Initial contribution
35 public class SamsungTvUtils {
38 * Build {@link String} type {@link HashMap} from variable number of
42 * Variable number of {@link String} parameters which will be
45 public static HashMap<String, String> buildHashMap(String... data) {
46 HashMap<String, String> result = new HashMap<>();
48 if (data.length % 2 != 0) {
49 throw new IllegalArgumentException("Odd number of arguments");
54 for (String value : data) {
59 throw new IllegalArgumentException("Null key value");
65 result.put(key, value);
75 * Build {@link Document} from {@link String} which contains XML content.
78 * {@link String} which contains XML content.
79 * @return {@link Document} or null if convert has failed.
81 public static @Nullable Document loadXMLFromString(String xml) {
83 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
84 // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
85 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
86 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
87 factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
88 factory.setXIncludeAware(false);
89 factory.setExpandEntityReferences(false);
90 DocumentBuilder builder = factory.newDocumentBuilder();
91 InputSource is = new InputSource(new StringReader(xml));
92 return builder.parse(is);
94 } catch (ParserConfigurationException | SAXException | IOException e) {
95 // Silently ignore exception and return null.