001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package javax.xml.bind.annotation; 018 019 import javax.xml.transform.dom.DOMResult; 020 import javax.xml.transform.dom.DOMSource; 021 import javax.xml.transform.Source; 022 import javax.xml.parsers.DocumentBuilder; 023 import javax.xml.bind.ValidationEventHandler; 024 025 import org.w3c.dom.Element; 026 import org.w3c.dom.Document; 027 import org.w3c.dom.Node; 028 import org.w3c.dom.DocumentFragment; 029 030 public class W3CDomHandler implements DomHandler<Element, DOMResult> { 031 032 private DocumentBuilder builder; 033 034 public W3CDomHandler() { 035 } 036 037 public W3CDomHandler(DocumentBuilder builder) { 038 if (builder == null) { 039 throw new IllegalArgumentException(); 040 } 041 this.builder = builder; 042 } 043 044 public DOMResult createUnmarshaller(ValidationEventHandler errorHandler) { 045 if (builder == null) { 046 return new DOMResult(); 047 } else { 048 return new DOMResult(builder.newDocument()); 049 } 050 } 051 052 public DocumentBuilder getBuilder() { 053 return builder; 054 } 055 056 public Element getElement(DOMResult rt) { 057 Node n = rt.getNode(); 058 if (n instanceof Document) { 059 return ((Document)n).getDocumentElement(); 060 } 061 if (n instanceof Element) { 062 return (Element)n; 063 } 064 if (n instanceof DocumentFragment) { 065 return (Element)n.getChildNodes().item(0); 066 } else { 067 throw new IllegalStateException(n.toString()); 068 } 069 } 070 071 public Source marshal(Element n, ValidationEventHandler errorHandler) { 072 return new DOMSource(n); 073 } 074 075 public void setBuilder(DocumentBuilder builder) { 076 this.builder = builder; 077 } 078 }