src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamWriterFactory.java

Wed, 12 Jun 2013 14:47:09 +0100

author
mkos
date
Wed, 12 Jun 2013 14:47:09 +0100
changeset 384
8f2986ff0235
parent 368
0989ad8c0860
child 515
6cd506508147
permissions
-rw-r--r--

8013021: Rebase 8005432 & 8003542 against the latest jdk8/jaxws
8003542: Improve processing of MTOM attachments
8005432: Update access to JAX-WS
Reviewed-by: mullan

     1 /*
     2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.xml.internal.ws.api.streaming;
    28 import com.sun.istack.internal.NotNull;
    29 import com.sun.istack.internal.Nullable;
    30 import com.sun.xml.internal.ws.encoding.HasEncoding;
    31 import com.sun.xml.internal.ws.encoding.SOAPBindingCodec;
    32 import com.sun.xml.internal.ws.streaming.XMLReaderException;
    33 import com.sun.xml.internal.ws.util.xml.XMLStreamWriterFilter;
    35 import javax.xml.stream.XMLOutputFactory;
    36 import javax.xml.stream.XMLStreamException;
    37 import javax.xml.stream.XMLStreamReader;
    38 import javax.xml.stream.XMLStreamWriter;
    39 import javax.xml.transform.stream.StreamResult;
    40 import javax.xml.ws.WebServiceException;
    41 import java.io.OutputStream;
    42 import java.io.StringWriter;
    43 import java.lang.reflect.InvocationTargetException;
    44 import java.lang.reflect.Method;
    45 import java.util.logging.Level;
    46 import java.util.logging.Logger;
    48 /**
    49  * Factory for {@link XMLStreamWriter}.
    50  *
    51  * <p>
    52  * This wraps {@link XMLOutputFactory} and allows us to reuse {@link XMLStreamWriter} instances
    53  * when appropriate.
    54  *
    55  * @author Kohsuke Kawaguchi
    56  */
    57 @SuppressWarnings("StaticNonFinalUsedInInitialization")
    58 public abstract class XMLStreamWriterFactory {
    60     private static final Logger LOGGER = Logger.getLogger(XMLStreamWriterFactory.class.getName());
    62     /**
    63      * Singleton instance.
    64      */
    65     private static volatile @NotNull XMLStreamWriterFactory theInstance;
    68     static {
    69         XMLOutputFactory  xof = null;
    70         if (Boolean.getBoolean(XMLStreamWriterFactory.class.getName()+".woodstox")) {
    71             try {
    72                 xof = (XMLOutputFactory)Class.forName("com.ctc.wstx.stax.WstxOutputFactory").newInstance();
    73             } catch (Exception e) {
    74                 // Ignore and fallback to default XMLOutputFactory
    75             }
    76         }
    77         if (xof == null) {
    78             xof = XMLOutputFactory.newInstance();
    79         }
    81         XMLStreamWriterFactory f=null;
    83         // this system property can be used to disable the pooling altogether,
    84         // in case someone hits an issue with pooling in the production system.
    85         if (!Boolean.getBoolean(XMLStreamWriterFactory.class.getName()+".noPool")) {
    86             try {
    87                 Class<?> clazz = xof.createXMLStreamWriter(new StringWriter()).getClass();
    88                 if (clazz.getName().startsWith("com.sun.xml.internal.stream.")) {
    89                     f =  new Zephyr(xof,clazz);
    90                 }
    91             } catch (XMLStreamException ex) {
    92                 Logger.getLogger(XMLStreamWriterFactory.class.getName()).log(Level.INFO, null, ex);
    93             } catch (NoSuchMethodException ex) {
    94                 Logger.getLogger(XMLStreamWriterFactory.class.getName()).log(Level.INFO, null, ex);
    95             }
    96         }
    98         if(f==null) {
    99             // is this Woodstox?
   100             if(xof.getClass().getName().equals("com.ctc.wstx.stax.WstxOutputFactory"))
   101                 f = new NoLock(xof);
   102         }
   103         if (f == null)
   104             f = new Default(xof);
   106         theInstance = f;
   107         if (LOGGER.isLoggable(Level.FINE)) {
   108             LOGGER.log(Level.FINE, "XMLStreamWriterFactory instance is = {0}", f);
   109         }
   110     }
   112     /**
   113      * See {@link #create(OutputStream)} for the contract.
   114      * This method may be invoked concurrently.
   115      */
   116     public abstract XMLStreamWriter doCreate(OutputStream out);
   118     /**
   119      * See {@link #create(OutputStream,String)} for the contract.
   120      * This method may be invoked concurrently.
   121      */
   122     public abstract XMLStreamWriter doCreate(OutputStream out, String encoding);
   124     /**
   125      * See {@link #recycle(XMLStreamWriter)} for the contract.
   126      * This method may be invoked concurrently.
   127      */
   128     public abstract void doRecycle(XMLStreamWriter r);
   130     /**
   131      * Should be invoked when the code finished using an {@link XMLStreamWriter}.
   132      *
   133      * <p>
   134      * If the recycled instance implements {@link RecycleAware},
   135      * {@link RecycleAware#onRecycled()} will be invoked to let the instance
   136      * know that it's being recycled.
   137      *
   138      * <p>
   139      * It is not a hard requirement to call this method on every {@link XMLStreamReader}
   140      * instance. Not doing so just reduces the performance by throwing away
   141      * possibly reusable instances. So the caller should always consider the effort
   142      * it takes to recycle vs the possible performance gain by doing so.
   143      *
   144      * <p>
   145      * This method may be invked by multiple threads concurrently.
   146      *
   147      * @param r
   148      *      The {@link XMLStreamReader} instance that the caller finished using.
   149      *      This could be any {@link XMLStreamReader} implementation, not just
   150      *      the ones that were created from this factory. So the implementation
   151      *      of this class needs to be aware of that.
   152      */
   153     public static void recycle(XMLStreamWriter r) {
   154         get().doRecycle(r);
   155     }
   157     /**
   158      * Interface that can be implemented by {@link XMLStreamWriter} to
   159      * be notified when it's recycled.
   160      *
   161      * <p>
   162      * This provides a filtering {@link XMLStreamWriter} an opportunity to
   163      * recycle its inner {@link XMLStreamWriter}.
   164      */
   165     public interface RecycleAware {
   166         void onRecycled();
   167     }
   169     /**
   170      * Gets the singleton instance.
   171      */
   172     public static @NotNull XMLStreamWriterFactory get() {
   173         return theInstance;
   174     }
   176     /**
   177      * Overrides the singleton {@link XMLStreamWriterFactory} instance that
   178      * the JAX-WS RI uses.
   179      *
   180      * @param f
   181      *      must not be null.
   182      */
   183     @SuppressWarnings({"null", "ConstantConditions"})
   184     public static void set(@NotNull XMLStreamWriterFactory f) {
   185         if(f==null) throw new IllegalArgumentException();
   186         theInstance = f;
   187     }
   189     /**
   190      * Short-cut for {@link #create(OutputStream, String)} with UTF-8.
   191      */
   192     public static XMLStreamWriter create(OutputStream out) {
   193         return get().doCreate(out);
   194     }
   196     public static XMLStreamWriter create(OutputStream out, String encoding) {
   197         return get().doCreate(out, encoding);
   198     }
   200     /**
   201      * @deprecated
   202      *      Use {@link #create(OutputStream)}
   203      */
   204     public static XMLStreamWriter createXMLStreamWriter(OutputStream out) {
   205         return create(out);
   206     }
   208     /**
   209      * @deprecated
   210      *      Use {@link #create(OutputStream, String)}
   211      */
   212     public static XMLStreamWriter createXMLStreamWriter(OutputStream out, String encoding) {
   213         return create(out, encoding);
   214     }
   216     /**
   217      * @deprecated
   218      *      Use {@link #create(OutputStream, String)}. The boolean flag was unused anyway.
   219      */
   220     public static XMLStreamWriter createXMLStreamWriter(OutputStream out, String encoding, boolean declare) {
   221         return create(out,encoding);
   222     }
   224     /**
   225      * Default {@link XMLStreamWriterFactory} implementation
   226      * that can work with any {@link XMLOutputFactory}.
   227      *
   228      * <p>
   229      * {@link XMLOutputFactory} is not required to be thread-safe, so the
   230      * create method on this implementation is synchronized.
   231      */
   232     public static final class Default extends XMLStreamWriterFactory {
   233         private final XMLOutputFactory xof;
   235         public Default(XMLOutputFactory xof) {
   236             this.xof = xof;
   237         }
   239         @Override
   240         public XMLStreamWriter doCreate(OutputStream out) {
   241             return doCreate(out,"UTF-8");
   242         }
   244         @Override
   245         public synchronized XMLStreamWriter doCreate(OutputStream out, String encoding) {
   246             try {
   247                 XMLStreamWriter writer = xof.createXMLStreamWriter(out,encoding);
   248                 return new HasEncodingWriter(writer, encoding);
   249             } catch (XMLStreamException e) {
   250                 throw new XMLReaderException("stax.cantCreate",e);
   251             }
   252         }
   254         @Override
   255         public void doRecycle(XMLStreamWriter r) {
   256             // no recycling
   257         }
   258     }
   260     /**
   261      * {@link XMLStreamWriterFactory} implementation for Sun's StaX implementation.
   262      *
   263      * <p>
   264      * This implementation supports instance reuse.
   265      */
   266     public static final class Zephyr extends XMLStreamWriterFactory {
   267         private final XMLOutputFactory xof;
   268         private final ThreadLocal<XMLStreamWriter> pool = new ThreadLocal<XMLStreamWriter>();
   269         private final Method resetMethod;
   270         private final Method setOutputMethod;
   271         private final Class zephyrClass;
   273         public static XMLStreamWriterFactory newInstance(XMLOutputFactory xof) {
   274             try {
   275                 Class<?> clazz = xof.createXMLStreamWriter(new StringWriter()).getClass();
   277                 if(!clazz.getName().startsWith("com.sun.xml.internal.stream."))
   278                 return null;    // nope
   280                 return new Zephyr(xof,clazz);
   281             } catch (XMLStreamException e) {
   282                 return null;    // impossible
   283             } catch (NoSuchMethodException e) {
   284                 return null;    // this xof wasn't Zephyr
   285             }
   286         }
   288         private Zephyr(XMLOutputFactory xof, Class clazz) throws NoSuchMethodException {
   289             this.xof = xof;
   291             zephyrClass = clazz;
   292             setOutputMethod = clazz.getMethod("setOutput", StreamResult.class, String.class);
   293             resetMethod = clazz.getMethod("reset");
   294         }
   296         /**
   297          * Fetchs an instance from the pool if available, otherwise null.
   298          */
   299         private @Nullable XMLStreamWriter fetch() {
   300             XMLStreamWriter sr = pool.get();
   301             if(sr==null)    return null;
   302             pool.set(null);
   303             return sr;
   304         }
   306         @Override
   307         public XMLStreamWriter doCreate(OutputStream out) {
   308             return doCreate(out,"UTF-8");
   309         }
   311         @Override
   312         public XMLStreamWriter doCreate(OutputStream out, String encoding) {
   313             XMLStreamWriter xsw = fetch();
   314             if(xsw!=null) {
   315                 // try to reuse
   316                 try {
   317                     resetMethod.invoke(xsw);
   318                     setOutputMethod.invoke(xsw,new StreamResult(out),encoding);
   319                 } catch (IllegalAccessException e) {
   320                     throw new XMLReaderException("stax.cantCreate",e);
   321                 } catch (InvocationTargetException e) {
   322                     throw new XMLReaderException("stax.cantCreate",e);
   323                 }
   324             } else {
   325                 // create a new instance
   326                 try {
   327                     xsw = xof.createXMLStreamWriter(out,encoding);
   328                 } catch (XMLStreamException e) {
   329                     throw new XMLReaderException("stax.cantCreate",e);
   330                 }
   331             }
   332             return new HasEncodingWriter(xsw, encoding);
   333         }
   335         @Override
   336         public void doRecycle(XMLStreamWriter r) {
   337             if (r instanceof HasEncodingWriter) {
   338                 r = ((HasEncodingWriter)r).getWriter();
   339             }
   340             if(zephyrClass.isInstance(r)) {
   341                 // this flushes the underlying stream, so it might cause chunking issue
   342                 try {
   343                     r.close();
   344                 } catch (XMLStreamException e) {
   345                     throw new WebServiceException(e);
   346                 }
   347                 pool.set(r);
   348             }
   349             if(r instanceof RecycleAware)
   350                 ((RecycleAware)r).onRecycled();
   351         }
   352     }
   354     /**
   355      *
   356      * For {@link javax.xml.stream.XMLOutputFactory} is thread safe.
   357      */
   358     public static final class NoLock extends XMLStreamWriterFactory {
   359         private final XMLOutputFactory xof;
   361         public NoLock(XMLOutputFactory xof) {
   362             this.xof = xof;
   363         }
   365         @Override
   366         public XMLStreamWriter doCreate(OutputStream out) {
   367             return doCreate(out, SOAPBindingCodec.UTF8_ENCODING);
   368         }
   370         @Override
   371         public XMLStreamWriter doCreate(OutputStream out, String encoding) {
   372             try {
   373                 XMLStreamWriter writer = xof.createXMLStreamWriter(out,encoding);
   374                 return new HasEncodingWriter(writer, encoding);
   375             } catch (XMLStreamException e) {
   376                 throw new XMLReaderException("stax.cantCreate",e);
   377             }
   378         }
   380         @Override
   381         public void doRecycle(XMLStreamWriter r) {
   382             // no recycling
   383         }
   385     }
   387     private static class HasEncodingWriter extends XMLStreamWriterFilter implements HasEncoding {
   388         private final String encoding;
   390         HasEncodingWriter(XMLStreamWriter writer, String encoding) {
   391             super(writer);
   392             this.encoding = encoding;
   393         }
   395         @Override
   396         public String getEncoding() {
   397             return encoding;
   398         }
   400         XMLStreamWriter getWriter() {
   401             return writer;
   402         }
   403     }
   404 }

mercurial