下面列出了javax.xml.parsers.DocumentBuilder#reset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Process and XML file
* @param XMLFile File to process
* @param ParentFolderId Flder where the new Folde()s) will be created
* @return the last object created
* @throws PDException In any error
*/
public PDFolders ProcessXML(File XMLFile, String ParentFolderId) throws PDException
{
try {
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(XMLFile);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject;
PDFolders NewFold=null;
for (int i=0; i<OPDObjectList.getLength(); i++)
{
OPDObject = OPDObjectList.item(i);
NewFold=ImportXMLNode(OPDObject, ParentFolderId, false);
}
DB.reset();
return(NewFold); // returned LAST Folder when opd file contains several.
}catch(Exception ex)
{
throw new PDException(ex.getLocalizedMessage());
}
}
private void returnDocumentBuilderToPool(DocumentBuilder db) {
try {
db.reset();
documentBuilderPool.offerFirst(db);
} catch (UnsupportedOperationException e) {
// document builders that don't support reset() can't be pooled
}
}
/** {@inheritDoc} */
public void returnBuilder(DocumentBuilder builder) {
if (!(builder instanceof DocumentBuilderProxy)) {
return;
}
DocumentBuilderProxy proxiedBuilder = (DocumentBuilderProxy) builder;
if (proxiedBuilder.getOwningPool() != this) {
return;
}
synchronized (this) {
if (proxiedBuilder.isReturned()) {
return;
}
if (proxiedBuilder.getPoolVersion() != poolVersion) {
return;
}
DocumentBuilder unwrappedBuilder = proxiedBuilder.getProxiedBuilder();
unwrappedBuilder.reset();
SoftReference<DocumentBuilder> builderReference = new SoftReference<DocumentBuilder>(unwrappedBuilder);
if (builderPool.size() < maxPoolSize) {
proxiedBuilder.setReturned(true);
builderPool.push(builderReference);
}
}
}
/** {@inheritDoc} */
public void returnBuilder(DocumentBuilder builder) {
if (!(builder instanceof DocumentBuilderProxy)) {
return;
}
DocumentBuilderProxy proxiedBuilder = (DocumentBuilderProxy) builder;
if (proxiedBuilder.getOwningPool() != this) {
return;
}
synchronized (proxiedBuilder) {
if (proxiedBuilder.isReturned()) {
return;
}
// Not strictly true in that it may not actually be pushed back
// into the cache, depending on builderPool.size() below. But
// that's ok. returnBuilder() shouldn't normally be called twice
// on the same builder instance anyway, and it also doesn't matter
// whether a builder is ever logically returned to the pool.
proxiedBuilder.setReturned(true);
}
DocumentBuilder unwrappedBuilder = proxiedBuilder.getProxiedBuilder();
unwrappedBuilder.reset();
SoftReference<DocumentBuilder> builderReference = new SoftReference<DocumentBuilder>(unwrappedBuilder);
synchronized(builderPool) {
if (builderPool.size() < maxPoolSize) {
builderPool.push(builderReference);
}
}
}
@Override
public void close() {
while (!builderQueue.isEmpty()) {
DocumentBuilder documentBuilder = builderQueue.poll();
documentBuilder.reset();
documentBuilder.setEntityResolver(null);
}
}
private void SendFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
String Param=Req.getParameter(DriverRemote.PARAM);
if (PDLog.isDebug())
PDLog.Debug("SendFile Param:"+Param);
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(new ByteArrayInputStream(Param.getBytes("UTF-8")));
NodeList OPDObjectList = XMLObjects.getElementsByTagName("Id");
Node OPDObject = OPDObjectList.item(0);
String Id=OPDObject.getTextContent();
OPDObjectList = XMLObjects.getElementsByTagName("Ver");
OPDObject = OPDObjectList.item(0);
String Ver=OPDObject.getTextContent();
DB.reset();
PDDocs doc=new PDDocs(getSessOPD(Req));
doc.setPDId(Id);
if (Ver!=null && Ver.length()!=0)
doc.LoadVersion(Id, Ver);
else
doc.LoadCurrent(Id);
ServletOutputStream out=response.getOutputStream();
PDMimeType mt=new PDMimeType(getSessOPD(Req));
mt.Load(doc.getMimeType());
response.setContentType(mt.getMimeCode());
response.setHeader("Content-disposition", "inline; filename=" + doc.getName());
try {
if (Ver!=null && Ver.length()!=0)
doc.getStreamVer(out);
else
doc.getStream(out);
} catch (Exception e)
{
out.close();
throw e;
}
out.close();
}
private void SendFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
String Param=Req.getParameter(DriverRemote.PARAM);
if (PDLog.isDebug())
PDLog.Debug("SendFile Param:"+Param);
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(new ByteArrayInputStream(Param.getBytes("UTF-8")));
NodeList OPDObjectList = XMLObjects.getElementsByTagName("Id");
Node OPDObject = OPDObjectList.item(0);
String Id=OPDObject.getTextContent();
OPDObjectList = XMLObjects.getElementsByTagName("Ver");
OPDObject = OPDObjectList.item(0);
String Ver=OPDObject.getTextContent();
DB.reset();
PDDocs doc=new PDDocs(SParent.getSessOPD(Req));
doc.setPDId(Id);
if (Ver!=null && Ver.length()!=0)
doc.LoadVersion(Id, Ver);
else
doc.LoadCurrent(Id);
ServletOutputStream out=response.getOutputStream();
PDMimeType mt=new PDMimeType(SParent.getSessOPD(Req));
mt.Load(doc.getMimeType());
response.setContentType(mt.getMimeCode());
response.setHeader("Content-disposition", "inline; filename=" + doc.getName());
try {
if (Ver!=null && Ver.length()!=0)
doc.getStreamVer(out);
else
doc.getStream(out);
} catch (Exception e)
{
out.close();
throw e;
}
out.close();
}
public static DocumentBuilder get() throws ParserConfigurationException {
DocumentBuilder result = instance.get();
if (result == null) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
result = factory.newDocumentBuilder();
instance.set(result);
} else {
result.reset();
}
return result;
}
private void returnDocumentBuilderToPool(DocumentBuilder db) {
try {
db.reset();
documentBuilderPool.offerFirst(db);
} catch (UnsupportedOperationException e) {
// document builders that don't support reset() can't be pooled
}
}
public static Document parse(InputStream stream, boolean validating) {
DocumentBuilder documentBuilder = getDocumentBuilder(validating);
try {
return documentBuilder.parse(stream);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
documentBuilder.reset();
}
}
public static Document newDocument(boolean validating) {
DocumentBuilder documentBuilder = getDocumentBuilder(validating);
try {
return documentBuilder.newDocument();
} finally {
documentBuilder.reset();
}
}
/**
* @param documentBuilder
* @return
*/
private static DocumentBuilder resetDocumentBuilder(DocumentBuilder documentBuilder) {
documentBuilder.reset();
documentBuilder.setEntityResolver(MCREntityResolver.instance());
return documentBuilder;
}
/**
* Imports ANY kind of OpenProdoc object(s) (doc, folder, definition, object of any kind,..) in XML format from a file
* @param XMLFile local file containing the object
* @param ParentFolderId Folder Id for importing folders or docs.
* @return Number of objects found and processed in the XML
* @throws PDException In any error
*/
public int ProcessXML(File XMLFile, String ParentFolderId) throws PDException
{
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML>:XMLFile="+XMLFile.getAbsolutePath()+" ParentFolderId="+ParentFolderId);
try {
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(XMLFile);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject = null;
ObjPD Obj2Build=null;
int Tot=0;
if (PDLog.isDebug())
PDLog.Debug("DriverGeneric.ProcessXML:Elements="+OPDObjectList.getLength());
for (int i=0; i<OPDObjectList.getLength(); i++)
{
OPDObject = OPDObjectList.item(i);
Obj2Build=BuildObj(OPDObject);
if (Obj2Build instanceof PDDocs)
{
((PDDocs)Obj2Build).ImportXMLNode(OPDObject, XMLFile.getAbsolutePath().substring(0,
XMLFile.getAbsolutePath().lastIndexOf(File.separatorChar)),
ParentFolderId, true);
Tot++;
}
else if (Obj2Build instanceof PDFolders)
; // ((PDFolders)Obj2Build).ImportXMLNode(OPDObject, ParentFolderId, false);
else
{
Obj2Build.ProcesXMLNode(OPDObject);
Tot++;
}
}
DB.reset();
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML<");
return(Tot);
}catch(Exception ex)
{
PDLog.Error(ex.getLocalizedMessage());
throw new PDException(ex.getLocalizedMessage());
}
}
/**
* Imports ANY kind of OpenProdoc object(s) (doc, folder, definition, object of any kind,..) in XML format from a InputStream
* @param XMLFile InputStream containing the object
* @param ParentFolderId Folder Id for importing folders or docs.
* @return Number of objects found and processed in the XML
* @throws PDException In any error
*/
public int ProcessXML(InputStream XMLFile, String ParentFolderId) throws PDException
{
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML>:InputStream. ParentFolderId="+ParentFolderId);
try {
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(XMLFile);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject = null;
ObjPD Obj2Build=null;
int Tot=0;
if (PDLog.isDebug())
PDLog.Debug("DriverGeneric.ProcessXML:Elements="+OPDObjectList.getLength());
for (int i=0; i<OPDObjectList.getLength(); i++)
{
OPDObject = OPDObjectList.item(i);
Obj2Build=BuildObj(OPDObject);
if (Obj2Build instanceof PDDocs)
{
((PDDocs)Obj2Build).ImportXMLNode(OPDObject, ParentFolderId, false);
Tot++;
}
else if (Obj2Build instanceof PDFolders)
{
// ((PDFolders)Obj2Build).ImportXMLNode(OPDObject, ParentFolderId, false);
// Tot++;
}
else
{
Obj2Build.ProcesXMLNode(OPDObject);
Tot++;
}
}
DB.reset();
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML<");
return(Tot);
}catch(Exception ex)
{
PDLog.Error(ex.getLocalizedMessage());
throw new PDException(ex.getLocalizedMessage());
}
}
/**
* Imports ANY kind of OpenProdoc object(s) (doc, folder, definition, object of any kind,..) in XML format from a InputStream with base64 content
* @param XMLFile InputStream containing the object
* @param ParentFolderId Folder Id for importing folders or docs.
* @return Number of objects found and processed in the XML
* @throws PDException In any error
*/
public int ProcessXMLB64(InputStream XMLFile, String ParentFolderId) throws PDException
{
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML>:InputStream. ParentFolderId="+ParentFolderId);
try {
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(XMLFile);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject = null;
ObjPD Obj2Build=null;
int Tot=0;
if (PDLog.isDebug())
PDLog.Debug("DriverGeneric.ProcessXML:Elements="+OPDObjectList.getLength());
for (int i=0; i<OPDObjectList.getLength(); i++)
{
OPDObject = OPDObjectList.item(i);
Obj2Build=BuildObj(OPDObject);
if (Obj2Build instanceof PDDocs)
{
((PDDocs)Obj2Build).ImportXMLNode(OPDObject, ParentFolderId, false);
Tot++;
}
else if (Obj2Build instanceof PDFolders)
{
ParentFolderId=((PDFolders)Obj2Build).ImportXMLNode(OPDObject, ParentFolderId, false).getPDId();
Tot++;
}
else
{
Obj2Build.ProcesXMLNode(OPDObject);
Tot++;
}
}
DB.reset();
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML<");
return(Tot);
}catch(Exception ex)
{
PDLog.Error(ex.getLocalizedMessage());
throw new PDException(ex.getLocalizedMessage());
}
}
/**
* Imports all the documents referenced in a XML file in ABBY FlexyCapture format
* @param Sess OpenProdoc session
* @param XMLFile XML File
* @param ParentFoldId OpenProdoc folder where do th import
* @param DateFormat format of dates in the XML
* @param TimeStampFormat Format of timestamps in the XML
* @return The File object of the (last) "OCRed" image referenced in the XML
* @throws PDException In any Error
*/
static public File ProcessXMLAbby(DriverGeneric Sess, File XMLFile, String ParentFoldId, String DateFormat, String TimeStampFormat) throws PDException
{
try {
File ImageFile=null;
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(XMLFile);
NodeList DocList = XMLObjects.getElementsByTagName("form:Documents");
NodeList DocElem;
NodeList SectElem;
NodeList AttrElem;
PDObjDefs DefTyp=new PDObjDefs(Sess);
for (int NumDocs=0; NumDocs<DocList.getLength(); NumDocs++)
{
DocElem=DocList.item(NumDocs).getChildNodes();
for (int NumDoc = 0; NumDoc < DocElem.getLength(); NumDoc++)
{
if (DocElem.item(NumDoc).getNodeType()==Node.ELEMENT_NODE)
{
String TypeName=DocElem.item(NumDoc).getNodeName();
TypeName=TypeName.substring(1, TypeName.indexOf(":"));
DefTyp.Clear();
DefTyp.Load(TypeName);
if (DefTyp.getParent()==null || DefTyp.getParent().length()==0)
throw new PDException("Incorrect_Document_Type:"+TypeName);
String FileName=DocElem.item(NumDoc).getAttributes().getNamedItem("addData:ImagePath").getNodeValue();
SectElem=DocElem.item(NumDoc).getChildNodes();
for (int NumSect = 0; NumSect < SectElem.getLength(); NumSect++)
{
if (SectElem.item(NumSect).getNodeType()==Node.ELEMENT_NODE)
{
PDDocs Doc=new PDDocs(Sess, TypeName);
if (FileName.charAt(0)==File.separatorChar || FileName.contains(":") && File.separatorChar=='\\')
ImageFile=new File(FileName);
else
ImageFile=new File(XMLFile.getParent()+File.separator+FileName);
Doc.setFile(ImageFile.getAbsolutePath());
Doc.setParentId(ParentFoldId);
Record Rec=Doc.getRecSum();
AttrElem=SectElem.item(NumSect).getChildNodes();
for (int NumAttr = 0; NumAttr < AttrElem.getLength(); NumAttr++)
{
if (AttrElem.item(NumAttr).getNodeType()==Node.ELEMENT_NODE)
{
String NameAttr=AttrElem.item(NumAttr).getNodeName().substring(1);
String Val=AttrElem.item(NumAttr).getTextContent();
if (Rec.ContainsAttr(NameAttr))
{
int Type=Rec.getAttr(NameAttr).getType();
if (Type==Attribute.tDATE)
{
SimpleDateFormat formatterDate = new SimpleDateFormat(DateFormat);
Rec.getAttr(NameAttr).setValue(formatterDate.parse(Val));
}
else if (Type==Attribute.tTIMESTAMP)
{
SimpleDateFormat formatterTS = new SimpleDateFormat(TimeStampFormat);
Rec.getAttr(NameAttr).setValue(formatterTS.parse(Val));
}
else
Rec.getAttr(NameAttr).Import(Val);
}
}
}
Doc.assignValues(Rec);
if (Doc.getTitle()==null)
Doc.setTitle(FileName);
Doc.insert();
}
}
}
}
}
DB.reset();
return(ImageFile);
}catch(Exception ex)
{
PDLog.Error(ex.getLocalizedMessage());
throw new PDException(ex.getLocalizedMessage());
}
}
public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
DocumentBuilder res = XML_DOCUMENT_BUILDER.get();
res.reset();
return res;
}
/**
*
* @param Req
* @throws Exception
*/
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();
if (!item.isFormField())
{
FileName=item.getName();
FileData=item.getInputStream();
break;
}
}
DriverGeneric PDSession=SParent.getSessOPD(Req);
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(FileData);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject;
ObjPD Obj2Build;
int Tot=0;
for (int i=0; i<OPDObjectList.getLength(); i++)
{
OPDObject = OPDObjectList.item(i);
Obj2Build=PDSession.BuildObj(OPDObject);
Obj2Build.ProcesXMLNode(OPDObject);
Tot++;
}
DB.reset();
out.println(UpFileStatus.SetResultOk(Req, "Total="+Tot));
FileData.close();
} catch (Exception e)
{
out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
throw e;
}
}
public static void releaseDocumentBuilder( DocumentBuilder docBuilder )
{
docBuilder.reset( );
builders.offer( docBuilder );
}
/** {@inheritDoc} */
@Override
public KeyFrameMeta loadKeyFrameMeta(File file) {
String filename = file.getAbsolutePath() + ".meta";
File metadataFile = new File(filename);
if (!metadataFile.exists()) {
// No such metadata
return null;
}
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using builder to get DOM representation of the XML file
dom = db.parse(filename);
db.reset();
} catch (ParserConfigurationException pce) {
log.error("Could not parse XML file.", pce);
return null;
} catch (SAXException se) {
log.error("Could not parse XML file.", se);
return null;
} catch (IOException ioe) {
log.error("Could not parse XML file.", ioe);
return null;
}
Element root = dom.getDocumentElement();
// Check if .xml file is valid and for this .flv file
if (!"FrameMetadata".equals(root.getNodeName())) {
// Invalid XML
return null;
}
String modified = root.getAttribute("modified");
if (modified == null || !modified.equals(String.valueOf(file.lastModified()))) {
// File has changed in the meantime
return null;
}
if (!root.hasAttribute("duration")) {
// Old file without duration informations
return null;
}
if (!root.hasAttribute("audioOnly")) {
// Old file without audio/video informations
return null;
}
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
NodeList keyFrames;
try {
XPathExpression xexpr = xpath.compile("/FrameMetadata/KeyFrame");
keyFrames = (NodeList) xexpr.evaluate(dom, XPathConstants.NODESET);
} catch (XPathExpressionException err) {
log.error("could not compile xpath expression", err);
return null;
}
int length = keyFrames.getLength();
if (keyFrames == null || length == 0) {
// File doesn't contain informations about keyframes
return null;
}
KeyFrameMeta result = new KeyFrameMeta();
result.duration = Long.parseLong(root.getAttribute("duration"));
result.positions = new long[length];
result.timestamps = new int[length];
for (int i = 0; i < length; i++) {
Node node = keyFrames.item(i);
NamedNodeMap attrs = node.getAttributes();
result.positions[i] = Long.parseLong(attrs.getNamedItem("position").getNodeValue());
result.timestamps[i] = Integer.parseInt(attrs.getNamedItem("timestamp").getNodeValue());
}
result.audioOnly = "true".equals(root.getAttribute("audioOnly"));
return result;
}