001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036: package com.sun.tools.xjc.reader.dtd.bindinfo;
037:
038: import java.io.IOException;
039: import java.io.StringReader;
040: import java.util.Map;
041:
042: import javax.xml.bind.annotation.adapters.XmlAdapter;
043: import javax.xml.parsers.DocumentBuilderFactory;
044: import javax.xml.parsers.ParserConfigurationException;
045:
046: import com.sun.codemodel.JClass;
047: import com.sun.codemodel.JClassAlreadyExistsException;
048: import com.sun.codemodel.JCodeModel;
049: import com.sun.codemodel.JDefinedClass;
050: import com.sun.codemodel.JExpr;
051: import com.sun.codemodel.JExpression;
052: import com.sun.codemodel.JMethod;
053: import com.sun.codemodel.JMod;
054: import com.sun.codemodel.JPackage;
055: import com.sun.codemodel.JPrimitiveType;
056: import com.sun.codemodel.JType;
057: import com.sun.codemodel.JVar;
058: import com.sun.tools.xjc.model.CAdapter;
059: import com.sun.tools.xjc.model.CBuiltinLeafInfo;
060: import com.sun.tools.xjc.model.TypeUse;
061: import com.sun.tools.xjc.model.TypeUseFactory;
062:
063: import org.w3c.dom.Element;
064: import org.xml.sax.InputSource;
065: import org.xml.sax.Locator;
066: import org.xml.sax.SAXException;
067:
068: /**
069: * <conversion> declaration in the binding file.
070: * This declaration declares a conversion by user-specified methods.
071: */
072: public class BIUserConversion implements BIConversion {
073: /**
074: * Wraps a given <conversion> element in the binding file.
075: */
076: BIUserConversion(BindInfo bi, Element _e) {
077: this .owner = bi;
078: this .e = _e;
079: }
080:
081: private static void add(Map<String, BIConversion> m, BIConversion c) {
082: m.put(c.name(), c);
083: }
084:
085: /** Adds all built-in conversions into the given map. */
086: static void addBuiltinConversions(BindInfo bi,
087: Map<String, BIConversion> m) {
088: add(
089: m,
090: new BIUserConversion(
091: bi,
092: parse("<conversion name='boolean' type='java.lang.Boolean' parse='getBoolean' />")));
093: add(
094: m,
095: new BIUserConversion(
096: bi,
097: parse("<conversion name='byte' type='java.lang.Byte' parse='parseByte' />")));
098: add(
099: m,
100: new BIUserConversion(
101: bi,
102: parse("<conversion name='short' type='java.lang.Short' parse='parseShort' />")));
103: add(
104: m,
105: new BIUserConversion(
106: bi,
107: parse("<conversion name='int' type='java.lang.Integer' parse='parseInt' />")));
108: add(
109: m,
110: new BIUserConversion(
111: bi,
112: parse("<conversion name='long' type='java.lang.Long' parse='parseLong' />")));
113: add(
114: m,
115: new BIUserConversion(
116: bi,
117: parse("<conversion name='float' type='java.lang.Float' parse='parseFloat' />")));
118: add(
119: m,
120: new BIUserConversion(
121: bi,
122: parse("<conversion name='double' type='java.lang.Double' parse='parseDouble' />")));
123: }
124:
125: private static Element parse(String text) {
126: try {
127: DocumentBuilderFactory dbf = DocumentBuilderFactory
128: .newInstance();
129: dbf.setNamespaceAware(true);
130: InputSource is = new InputSource(new StringReader(text));
131: return dbf.newDocumentBuilder().parse(is)
132: .getDocumentElement();
133: } catch (SAXException x) {
134: throw new Error(x);
135: } catch (IOException x) {
136: throw new Error(x);
137: } catch (ParserConfigurationException x) {
138: throw new Error(x);
139: }
140: }
141:
142: /** The owner {@link BindInfo} object to which this object belongs. */
143: private final BindInfo owner;
144:
145: /** <conversion> element which this object is wrapping. */
146: private final Element e;
147:
148: /** Gets the location where this declaration is declared. */
149: public Locator getSourceLocation() {
150: return DOMLocator.getLocationInfo(e);
151: }
152:
153: /** Gets the conversion name. */
154: public String name() {
155: return DOMUtil.getAttribute(e, "name");
156: }
157:
158: /** Gets a transducer for this conversion. */
159: public TypeUse getTransducer() {
160:
161: String ws = DOMUtil.getAttribute(e, "whitespace");
162: if (ws == null)
163: ws = "collapse";
164:
165: String type = DOMUtil.getAttribute(e, "type");
166: if (type == null)
167: type = name();
168: JType t = null;
169:
170: int idx = type.lastIndexOf('.');
171: if (idx < 0) {
172: // no package name is specified.
173: try {
174: t = JPrimitiveType.parse(owner.codeModel, type);
175: } catch (IllegalArgumentException e) {
176: // otherwise treat it as a class name in the current package
177: type = owner.getTargetPackage().name() + '.' + type;
178: }
179: }
180: if (t == null) {
181: try {
182: // TODO: revisit this later
183: JDefinedClass cls = owner.codeModel._class(type);
184: cls.hide();
185: t = cls;
186: } catch (JClassAlreadyExistsException e) {
187: t = e.getExistingClass();
188: }
189: }
190:
191: String parse = DOMUtil.getAttribute(e, "parse");
192: if (parse == null)
193: parse = "new";
194:
195: String print = DOMUtil.getAttribute(e, "print");
196: if (print == null)
197: print = "toString";
198:
199: JDefinedClass adapter = generateAdapter(owner.codeModel, parse,
200: print, t.boxify());
201:
202: // XmlJavaType customization always converts between string and an user-defined type.
203: return TypeUseFactory.adapt(CBuiltinLeafInfo.STRING,
204: new CAdapter(adapter));
205: }
206:
207: // TODO: anyway to reuse this code between XML Schema compiler?
208: private JDefinedClass generateAdapter(JCodeModel cm,
209: String parseMethod, String printMethod, JClass inMemoryType) {
210: JDefinedClass adapter = null;
211:
212: int id = 1;
213: while (adapter == null) {
214: try {
215: JPackage pkg = owner.getTargetPackage();
216: adapter = pkg._class("Adapter" + id);
217: } catch (JClassAlreadyExistsException e) {
218: // try another name in search for an unique name.
219: // this isn't too efficient, but we expect people to usually use
220: // a very small number of adapters.
221: id++;
222: }
223: }
224:
225: adapter._extends(cm.ref(XmlAdapter.class).narrow(String.class)
226: .narrow(inMemoryType));
227:
228: JMethod unmarshal = adapter.method(JMod.PUBLIC, inMemoryType,
229: "unmarshal");
230: JVar $value = unmarshal.param(String.class, "value");
231:
232: JExpression inv;
233:
234: if (parseMethod.equals("new")) {
235: // "new" indicates that the constructor of the target type
236: // will do the unmarshalling.
237:
238: // RESULT: new <type>()
239: inv = JExpr._new(inMemoryType).arg($value);
240: } else {
241: int idx = parseMethod.lastIndexOf('.');
242: if (idx < 0) {
243: // parseMethod specifies the static method of the target type
244: // which will do the unmarshalling.
245:
246: // because of an error check at the constructor,
247: // we can safely assume that this cast works.
248: inv = inMemoryType.staticInvoke(parseMethod)
249: .arg($value);
250: } else {
251: inv = JExpr.direct(parseMethod + "(value)");
252: }
253: }
254: unmarshal.body()._return(inv);
255:
256: JMethod marshal = adapter.method(JMod.PUBLIC, String.class,
257: "marshal");
258: $value = marshal.param(inMemoryType, "value");
259:
260: int idx = printMethod.lastIndexOf('.');
261: if (idx < 0) {
262: // printMethod specifies a method in the target type
263: // which performs the serialization.
264:
265: // RESULT: <value>.<method>()
266: inv = $value.invoke(printMethod);
267: } else {
268: // RESULT: <className>.<method>(<value>)
269: inv = JExpr.direct(printMethod + "(value)");
270: }
271: marshal.body()._return(inv);
272:
273: return adapter;
274: }
275: }
|