Autopsy  4.21.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
XMLUtil.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2012-2020 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.coreutils;
20 
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.OutputStreamWriter;
27 import java.io.UnsupportedEncodingException;
28 import java.nio.file.Paths;
29 import java.util.logging.Level;
30 import javax.xml.XMLConstants;
31 import javax.xml.parsers.DocumentBuilder;
32 import javax.xml.parsers.DocumentBuilderFactory;
33 import javax.xml.parsers.ParserConfigurationException;
34 import javax.xml.transform.OutputKeys;
35 import javax.xml.transform.Result;
36 import javax.xml.transform.Transformer;
37 import javax.xml.transform.TransformerConfigurationException;
38 import javax.xml.transform.TransformerException;
39 import javax.xml.transform.TransformerFactory;
40 import javax.xml.transform.dom.DOMResult;
41 import javax.xml.transform.dom.DOMSource;
42 import javax.xml.transform.stream.StreamResult;
43 import javax.xml.validation.Schema;
44 import javax.xml.validation.SchemaFactory;
45 import javax.xml.validation.Validator;
46 import org.w3c.dom.Document;
47 import org.xml.sax.SAXException;
48 
56 public class XMLUtil {
57 
58  static {
59  // this is to ensure using xalan for the transformer factory: https://stackoverflow.com/a/64364531/2375948
60  System.setProperty("javax.xml.transform.TransformerFactory","com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
61  }
62 
63  private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
64  // See JIRA-6958 for details about class loading and jaxb.
65  ClassLoader original = Thread.currentThread().getContextClassLoader();
66  try {
67  Thread.currentThread().setContextClassLoader(XMLUtil.class.getClassLoader());
68  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
69  return builderFactory.newDocumentBuilder();
70  } finally {
71  Thread.currentThread().setContextClassLoader(original);
72  }
73  }
74 
75  private static SchemaFactory getSchemaFactory(String schemaLanguage) {
76  // See JIRA-6958 for details about class loading and jaxb.
77  ClassLoader original = Thread.currentThread().getContextClassLoader();
78  try {
79  Thread.currentThread().setContextClassLoader(XMLUtil.class.getClassLoader());
80  return SchemaFactory.newInstance(schemaLanguage);
81  } finally {
82  Thread.currentThread().setContextClassLoader(original);
83  }
84  }
85 
86  private static TransformerFactory getTransformerFactory() {
87  // See JIRA-6958 for details about class loading and jaxb.
88  ClassLoader original = Thread.currentThread().getContextClassLoader();
89  try {
90  Thread.currentThread().setContextClassLoader(XMLUtil.class.getClassLoader());
91  return TransformerFactory.newInstance();
92  } finally {
93  Thread.currentThread().setContextClassLoader(original);
94  }
95  }
96 
104  public static Document createDocument() throws ParserConfigurationException {
105  return getDocumentBuilder().newDocument();
106  }
107 
122  public static <T> Document loadDocument(String docPath, Class<T> clazz, String schemaResourceName) throws IOException, ParserConfigurationException, SAXException {
123  Document doc = loadDocument(docPath);
124  validateDocument(doc, clazz, schemaResourceName);
125  return doc;
126  }
127 
139  public static Document loadDocument(String docPath) throws ParserConfigurationException, SAXException, IOException {
140  DocumentBuilder builder = getDocumentBuilder();
141  Document doc = builder.parse(new FileInputStream(docPath));
142  return doc;
143  }
144 
155  public static <T> void validateDocument(final Document doc, Class<T> clazz, String schemaResourceName) throws SAXException, IOException {
156  PlatformUtil.extractResourceToUserConfigDir(clazz, schemaResourceName, false);
157  File schemaFile = new File(Paths.get(PlatformUtil.getUserConfigDirectory(), schemaResourceName).toAbsolutePath().toString());
158  SchemaFactory schemaFactory = getSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI);
159  Schema schema = schemaFactory.newSchema(schemaFile);
160  Validator validator = schema.newValidator();
161  validator.validate(new DOMSource(doc), new DOMResult());
162  }
163 
178  public static void saveDocument(final Document doc, String encoding, String docPath) throws TransformerConfigurationException, FileNotFoundException, UnsupportedEncodingException, TransformerException, IOException {
179  TransformerFactory xf = getTransformerFactory();
180  xf.setAttribute("indent-number", 1); //NON-NLS
181  Transformer xformer = xf.newTransformer();
182  xformer.setOutputProperty(OutputKeys.METHOD, "xml"); //NON-NLS
183  xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS
184  xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
185  xformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //NON-NLS
186  xformer.setOutputProperty(OutputKeys.VERSION, "1.0");
187  File file = new File(docPath);
188  try (FileOutputStream stream = new FileOutputStream(file)) {
189  Result out = new StreamResult(new OutputStreamWriter(stream, encoding));
190  xformer.transform(new DOMSource(doc), out);
191  stream.flush();
192  }
193  }
194 
212  // TODO: Deprecate.
213  public static <T> boolean xmlIsValid(DOMSource xmlfile, Class<T> clazz, String schemaFile) {
214  try {
215  PlatformUtil.extractResourceToUserConfigDir(clazz, schemaFile, false);
216  File schemaLoc = new File(PlatformUtil.getUserConfigDirectory() + File.separator + schemaFile);
217  SchemaFactory schm = getSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI);
218  try {
219  Schema schema = schm.newSchema(schemaLoc);
220  Validator validator = schema.newValidator();
221  DOMResult result = new DOMResult();
222  validator.validate(xmlfile, result);
223  return true;
224  } catch (SAXException e) {
225  Logger.getLogger(clazz.getName()).log(Level.WARNING, "Unable to validate XML file.", e); //NON-NLS
226  return false;
227  }
228  } catch (IOException e) {
229  Logger.getLogger(clazz.getName()).log(Level.WARNING, "Unable to load XML file [" + xmlfile.toString() + "] of type [" + schemaFile + "]", e); //NON-NLS
230  return false;
231  }
232  }
233 
251  // TODO: Deprecate.
252  public static <T> boolean xmlIsValid(Document doc, Class<T> clazz, String type) {
253  DOMSource dms = new DOMSource(doc);
254  return xmlIsValid(dms, clazz, type);
255  }
256 
263  // TODO: Deprecate.
264  public static <T> Document loadDoc(Class<T> clazz, String xmlPath) {
265  Document ret = null;
266  try {
267  DocumentBuilder builder = getDocumentBuilder();
268  ret = builder.parse(new FileInputStream(xmlPath));
269  } catch (ParserConfigurationException e) {
270  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error loading XML file " + xmlPath + " : can't initialize parser.", e); //NON-NLS
271  } catch (SAXException e) {
272  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error loading XML file " + xmlPath + " : can't parse XML.", e); //NON-NLS
273  } catch (IOException e) {
274  //error reading file
275  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error loading XML file " + xmlPath + " : can't read file.", e); //NON-NLS
276  }
277  return ret;
278  }
279 
287  // TODO: Deprecate
288  public static <T> Document loadDoc(Class<T> clazz, String xmlPath, String xsdPath) {
289  Document ret = loadDoc(clazz, xmlPath);
290  if (!XMLUtil.xmlIsValid(ret, clazz, xsdPath)) {
291  Logger.getLogger(clazz.getName()).log(Level.WARNING, "Error loading XML file: could not validate against [{0}], results may not be accurate", xsdPath); //NON-NLS
292  }
293  return ret;
294  }
295 
304  // TODO: Deprecate.
305  public static <T> boolean saveDoc(Class<T> clazz, String xmlPath, String encoding, final Document doc) {
306  TransformerFactory xf = getTransformerFactory();
307  xf.setAttribute("indent-number", 1); //NON-NLS
308  boolean success = false;
309  try {
310  Transformer xformer = xf.newTransformer();
311  xformer.setOutputProperty(OutputKeys.METHOD, "xml"); //NON-NLS
312  xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS
313  xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
314  xformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //NON-NLS
315  xformer.setOutputProperty(OutputKeys.VERSION, "1.0");
316  File file = new File(xmlPath);
317  try (FileOutputStream stream = new FileOutputStream(file)) {
318  Result out = new StreamResult(new OutputStreamWriter(stream, encoding));
319  xformer.transform(new DOMSource(doc), out);
320  stream.flush();
321  }
322  success = true;
323 
324  } catch (UnsupportedEncodingException e) {
325  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Should not happen", e); //NON-NLS
326  } catch (TransformerConfigurationException e) {
327  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file", e); //NON-NLS
328  } catch (TransformerException e) {
329  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file", e); //NON-NLS
330  } catch (FileNotFoundException e) {
331  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file: cannot write to file: " + xmlPath, e); //NON-NLS
332  } catch (IOException e) {
333  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file: cannot write to file: " + xmlPath, e); //NON-NLS
334  }
335  return success;
336  }
337 
338 }
static< T > Document loadDoc(Class< T > clazz, String xmlPath)
Definition: XMLUtil.java:264
static TransformerFactory getTransformerFactory()
Definition: XMLUtil.java:86
static< T > Document loadDoc(Class< T > clazz, String xmlPath, String xsdPath)
Definition: XMLUtil.java:288
static SchemaFactory getSchemaFactory(String schemaLanguage)
Definition: XMLUtil.java:75
static< T > boolean xmlIsValid(Document doc, Class< T > clazz, String type)
Definition: XMLUtil.java:252
static< T > void validateDocument(final Document doc, Class< T > clazz, String schemaResourceName)
Definition: XMLUtil.java:155
static< T > boolean extractResourceToUserConfigDir(final Class< T > resourceClass, final String resourceFileName, boolean overWrite)
static< T > Document loadDocument(String docPath, Class< T > clazz, String schemaResourceName)
Definition: XMLUtil.java:122
static< T > boolean xmlIsValid(DOMSource xmlfile, Class< T > clazz, String schemaFile)
Definition: XMLUtil.java:213
static Document loadDocument(String docPath)
Definition: XMLUtil.java:139
static void saveDocument(final Document doc, String encoding, String docPath)
Definition: XMLUtil.java:178
synchronized static Logger getLogger(String name)
Definition: Logger.java:124
static DocumentBuilder getDocumentBuilder()
Definition: XMLUtil.java:63
static< T > boolean saveDoc(Class< T > clazz, String xmlPath, String encoding, final Document doc)
Definition: XMLUtil.java:305

Copyright © 2012-2022 Basis Technology. Generated on: Tue Feb 6 2024
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.