Autopsy  4.19.1
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  private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
59  // See JIRA-6958 for details about class loading and jaxb.
60  ClassLoader original = Thread.currentThread().getContextClassLoader();
61  try {
62  Thread.currentThread().setContextClassLoader(XMLUtil.class.getClassLoader());
63  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
64  return builderFactory.newDocumentBuilder();
65  } finally {
66  Thread.currentThread().setContextClassLoader(original);
67  }
68  }
69 
70  private static SchemaFactory getSchemaFactory(String schemaLanguage) {
71  // See JIRA-6958 for details about class loading and jaxb.
72  ClassLoader original = Thread.currentThread().getContextClassLoader();
73  try {
74  Thread.currentThread().setContextClassLoader(XMLUtil.class.getClassLoader());
75  return SchemaFactory.newInstance(schemaLanguage);
76  } finally {
77  Thread.currentThread().setContextClassLoader(original);
78  }
79  }
80 
81  private static TransformerFactory getTransformerFactory() {
82  // See JIRA-6958 for details about class loading and jaxb.
83  ClassLoader original = Thread.currentThread().getContextClassLoader();
84  try {
85  Thread.currentThread().setContextClassLoader(XMLUtil.class.getClassLoader());
86  return TransformerFactory.newInstance();
87  } finally {
88  Thread.currentThread().setContextClassLoader(original);
89  }
90  }
91 
99  public static Document createDocument() throws ParserConfigurationException {
100  return getDocumentBuilder().newDocument();
101  }
102 
117  public static <T> Document loadDocument(String docPath, Class<T> clazz, String schemaResourceName) throws IOException, ParserConfigurationException, SAXException {
118  Document doc = loadDocument(docPath);
119  validateDocument(doc, clazz, schemaResourceName);
120  return doc;
121  }
122 
134  public static Document loadDocument(String docPath) throws ParserConfigurationException, SAXException, IOException {
135  DocumentBuilder builder = getDocumentBuilder();
136  Document doc = builder.parse(new FileInputStream(docPath));
137  return doc;
138  }
139 
150  public static <T> void validateDocument(final Document doc, Class<T> clazz, String schemaResourceName) throws SAXException, IOException {
151  PlatformUtil.extractResourceToUserConfigDir(clazz, schemaResourceName, false);
152  File schemaFile = new File(Paths.get(PlatformUtil.getUserConfigDirectory(), schemaResourceName).toAbsolutePath().toString());
153  SchemaFactory schemaFactory = getSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI);
154  Schema schema = schemaFactory.newSchema(schemaFile);
155  Validator validator = schema.newValidator();
156  validator.validate(new DOMSource(doc), new DOMResult());
157  }
158 
173  public static void saveDocument(final Document doc, String encoding, String docPath) throws TransformerConfigurationException, FileNotFoundException, UnsupportedEncodingException, TransformerException, IOException {
174  TransformerFactory xf = getTransformerFactory();
175  xf.setAttribute("indent-number", 1); //NON-NLS
176  Transformer xformer = xf.newTransformer();
177  xformer.setOutputProperty(OutputKeys.METHOD, "xml"); //NON-NLS
178  xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS
179  xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
180  xformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //NON-NLS
181  xformer.setOutputProperty(OutputKeys.VERSION, "1.0");
182  File file = new File(docPath);
183  try (FileOutputStream stream = new FileOutputStream(file)) {
184  Result out = new StreamResult(new OutputStreamWriter(stream, encoding));
185  xformer.transform(new DOMSource(doc), out);
186  stream.flush();
187  }
188  }
189 
207  // TODO: Deprecate.
208  public static <T> boolean xmlIsValid(DOMSource xmlfile, Class<T> clazz, String schemaFile) {
209  try {
210  PlatformUtil.extractResourceToUserConfigDir(clazz, schemaFile, false);
211  File schemaLoc = new File(PlatformUtil.getUserConfigDirectory() + File.separator + schemaFile);
212  SchemaFactory schm = getSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI);
213  try {
214  Schema schema = schm.newSchema(schemaLoc);
215  Validator validator = schema.newValidator();
216  DOMResult result = new DOMResult();
217  validator.validate(xmlfile, result);
218  return true;
219  } catch (SAXException e) {
220  Logger.getLogger(clazz.getName()).log(Level.WARNING, "Unable to validate XML file.", e); //NON-NLS
221  return false;
222  }
223  } catch (IOException e) {
224  Logger.getLogger(clazz.getName()).log(Level.WARNING, "Unable to load XML file [" + xmlfile.toString() + "] of type [" + schemaFile + "]", e); //NON-NLS
225  return false;
226  }
227  }
228 
246  // TODO: Deprecate.
247  public static <T> boolean xmlIsValid(Document doc, Class<T> clazz, String type) {
248  DOMSource dms = new DOMSource(doc);
249  return xmlIsValid(dms, clazz, type);
250  }
251 
258  // TODO: Deprecate.
259  public static <T> Document loadDoc(Class<T> clazz, String xmlPath) {
260  Document ret = null;
261  try {
262  DocumentBuilder builder = getDocumentBuilder();
263  ret = builder.parse(new FileInputStream(xmlPath));
264  } catch (ParserConfigurationException e) {
265  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error loading XML file " + xmlPath + " : can't initialize parser.", e); //NON-NLS
266  } catch (SAXException e) {
267  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error loading XML file " + xmlPath + " : can't parse XML.", e); //NON-NLS
268  } catch (IOException e) {
269  //error reading file
270  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error loading XML file " + xmlPath + " : can't read file.", e); //NON-NLS
271  }
272  return ret;
273  }
274 
282  // TODO: Deprecate
283  public static <T> Document loadDoc(Class<T> clazz, String xmlPath, String xsdPath) {
284  Document ret = loadDoc(clazz, xmlPath);
285  if (!XMLUtil.xmlIsValid(ret, clazz, xsdPath)) {
286  Logger.getLogger(clazz.getName()).log(Level.WARNING, "Error loading XML file: could not validate against [{0}], results may not be accurate", xsdPath); //NON-NLS
287  }
288  return ret;
289  }
290 
299  // TODO: Deprecate.
300  public static <T> boolean saveDoc(Class<T> clazz, String xmlPath, String encoding, final Document doc) {
301  TransformerFactory xf = getTransformerFactory();
302  xf.setAttribute("indent-number", 1); //NON-NLS
303  boolean success = false;
304  try {
305  Transformer xformer = xf.newTransformer();
306  xformer.setOutputProperty(OutputKeys.METHOD, "xml"); //NON-NLS
307  xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS
308  xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
309  xformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //NON-NLS
310  xformer.setOutputProperty(OutputKeys.VERSION, "1.0");
311  File file = new File(xmlPath);
312  try (FileOutputStream stream = new FileOutputStream(file)) {
313  Result out = new StreamResult(new OutputStreamWriter(stream, encoding));
314  xformer.transform(new DOMSource(doc), out);
315  stream.flush();
316  }
317  success = true;
318 
319  } catch (UnsupportedEncodingException e) {
320  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Should not happen", e); //NON-NLS
321  } catch (TransformerConfigurationException e) {
322  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file", e); //NON-NLS
323  } catch (TransformerException e) {
324  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file", e); //NON-NLS
325  } catch (FileNotFoundException e) {
326  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file: cannot write to file: " + xmlPath, e); //NON-NLS
327  } catch (IOException e) {
328  Logger.getLogger(clazz.getName()).log(Level.SEVERE, "Error writing XML file: cannot write to file: " + xmlPath, e); //NON-NLS
329  }
330  return success;
331  }
332 
333 }
static< T > Document loadDoc(Class< T > clazz, String xmlPath)
Definition: XMLUtil.java:259
static TransformerFactory getTransformerFactory()
Definition: XMLUtil.java:81
static< T > Document loadDoc(Class< T > clazz, String xmlPath, String xsdPath)
Definition: XMLUtil.java:283
static SchemaFactory getSchemaFactory(String schemaLanguage)
Definition: XMLUtil.java:70
static< T > boolean xmlIsValid(Document doc, Class< T > clazz, String type)
Definition: XMLUtil.java:247
static< T > void validateDocument(final Document doc, Class< T > clazz, String schemaResourceName)
Definition: XMLUtil.java:150
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:117
static< T > boolean xmlIsValid(DOMSource xmlfile, Class< T > clazz, String schemaFile)
Definition: XMLUtil.java:208
static Document loadDocument(String docPath)
Definition: XMLUtil.java:134
static void saveDocument(final Document doc, String encoding, String docPath)
Definition: XMLUtil.java:173
synchronized static Logger getLogger(String name)
Definition: Logger.java:124
static DocumentBuilder getDocumentBuilder()
Definition: XMLUtil.java:58
static< T > boolean saveDoc(Class< T > clazz, String xmlPath, String encoding, final Document doc)
Definition: XMLUtil.java:300

Copyright © 2012-2021 Basis Technology. Generated on: Thu Sep 30 2021
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.