1 /*
   2  * Copyright (c) 1997, 2015, 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  */
  25 
  26 package com.sun.xml.internal.bind.v2.runtime.output;
  27 
  28 import java.io.IOException;
  29 import java.io.OutputStream;
  30 import java.util.Arrays;
  31 import java.util.Collections;
  32 
  33 import com.sun.xml.internal.bind.api.JAXBRIContext;
  34 import com.sun.xml.internal.bind.v2.runtime.Name;
  35 import com.sun.istack.internal.FinalArrayList;
  36 import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler;
  37 
  38 /**
  39  * {@link XmlOutput} that generates canonical XML.
  40  *
  41  * @author Kohsuke Kawaguchi
  42  */
  43 public class C14nXmlOutput extends UTF8XmlOutput {
  44     public C14nXmlOutput(OutputStream out, Encoded[] localNames, boolean namedAttributesAreOrdered, CharacterEscapeHandler escapeHandler) {
  45         super(out, localNames, escapeHandler);
  46         this.namedAttributesAreOrdered = namedAttributesAreOrdered;
  47 
  48         for( int i=0; i<staticAttributes.length; i++ )
  49             staticAttributes[i] = new StaticAttribute();
  50     }
  51 
  52     /**
  53      * Hosts statically known attributes.
  54      *
  55      * {@link StaticAttribute} instances are reused.
  56      */
  57     private StaticAttribute[] staticAttributes = new StaticAttribute[8];
  58     private int len = 0;
  59 
  60     /**
  61      * Used to sort namespace declarations. Reused.
  62      */
  63     private int[] nsBuf = new int[8];
  64 
  65     /**
  66      * Hosts other attributes whose name are not statically known
  67      * (AKA attribute wildcard.)
  68      *
  69      * As long as this map is empty, there's no need for sorting.
  70      */
  71     private final FinalArrayList<DynamicAttribute> otherAttributes = new FinalArrayList<DynamicAttribute>();
  72 
  73     /**
  74      * True if {@link JAXBRIContext} is created with c14n support on,
  75      * in which case all named attributes are sorted by the marshaller
  76      * and we won't have to do it here.
  77      */
  78     private final boolean namedAttributesAreOrdered;
  79 
  80     final class StaticAttribute implements Comparable<StaticAttribute> {
  81         Name name;
  82         String value;
  83 
  84         public void set(Name name, String value) {
  85             this.name = name;
  86             this.value = value;
  87         }
  88 
  89         void write() throws IOException {
  90             C14nXmlOutput.super.attribute(name,value);
  91         }
  92 
  93         DynamicAttribute toDynamicAttribute() {
  94             int nsUriIndex = name.nsUriIndex;
  95             int prefix;
  96             if(nsUriIndex==-1)
  97                 prefix = -1;
  98             else
  99                 prefix = nsUriIndex2prefixIndex[nsUriIndex];
 100             return new DynamicAttribute(
 101                 prefix, name.localName, value );
 102         }
 103 
 104         public int compareTo(StaticAttribute that) {
 105             return this.name.compareTo(that.name);
 106         }
 107 
 108     }
 109 
 110     final class DynamicAttribute implements Comparable<DynamicAttribute> {
 111         final int prefix;
 112         final String localName;
 113         final String value;
 114 
 115         public DynamicAttribute(int prefix, String localName, String value) {
 116             this.prefix = prefix;
 117             this.localName = localName;
 118             this.value = value;
 119         }
 120 
 121         private String getURI() {
 122             if(prefix==-1)  return "";
 123             else            return nsContext.getNamespaceURI(prefix);
 124         }
 125 
 126         public int compareTo(DynamicAttribute that) {
 127             int r = this.getURI().compareTo(that.getURI());
 128             if(r!=0)    return r;
 129             return this.localName.compareTo(that.localName);
 130         }
 131     }
 132 
 133     @Override
 134     public void attribute(Name name, String value) throws IOException {
 135         if(staticAttributes.length==len) {
 136             // reallocate
 137             int newLen = len*2;
 138             StaticAttribute[] newbuf = new StaticAttribute[newLen];
 139             System.arraycopy(staticAttributes,0,newbuf,0,len);
 140             for(int i=len;i<newLen;i++)
 141                 staticAttributes[i] = new StaticAttribute();
 142             staticAttributes = newbuf;
 143         }
 144 
 145         staticAttributes[len++].set(name,value);
 146     }
 147 
 148     @Override
 149     public void attribute(int prefix, String localName, String value) throws IOException {
 150         otherAttributes.add(new DynamicAttribute(prefix,localName,value));
 151     }
 152 
 153     @Override
 154     public void endStartTag() throws IOException {
 155         if(otherAttributes.isEmpty()) {
 156             if(len!=0) {
 157                 // sort is expensive even for size 0 array,
 158                 // so it's worth checking len==0
 159                 if(!namedAttributesAreOrdered)
 160                     Arrays.sort(staticAttributes,0,len);
 161                 // this is the common case
 162                 for( int i=0; i<len; i++ )
 163                     staticAttributes[i].write();
 164                 len = 0;
 165             }
 166         } else {
 167             // this is the exceptional case
 168 
 169             // sort all the attributes, not just the other attributes
 170             for( int i=0; i<len; i++ )
 171                 otherAttributes.add(staticAttributes[i].toDynamicAttribute());
 172             len = 0;
 173             Collections.sort(otherAttributes);
 174 
 175             // write them all
 176             int size = otherAttributes.size();
 177             for( int i=0; i<size; i++ ) {
 178                 DynamicAttribute a = otherAttributes.get(i);
 179                 super.attribute(a.prefix,a.localName,a.value);
 180             }
 181             otherAttributes.clear();
 182         }
 183         super.endStartTag();
 184     }
 185 
 186     /**
 187      * Write namespace declarations after sorting them.
 188      */
 189     @Override
 190     protected void writeNsDecls(int base) throws IOException {
 191         int count = nsContext.getCurrent().count();
 192 
 193         if(count==0)
 194             return; // quickly reject the most common case
 195 
 196         if(count>nsBuf.length)
 197             nsBuf = new int[count];
 198 
 199         for( int i=count-1; i>=0; i-- )
 200             nsBuf[i] = base+i;
 201 
 202         // do a bubble sort. Hopefully # of ns decls are small enough to justify bubble sort.
 203         // faster algorithm is more compliated to implement
 204         for( int i=0; i<count; i++ ) {
 205             for( int j=i+1; j<count; j++ ) {
 206                 String p = nsContext.getPrefix(nsBuf[i]);
 207                 String q = nsContext.getPrefix(nsBuf[j]);
 208                 if( p.compareTo(q) > 0 ) {
 209                     // swap
 210                     int t = nsBuf[j];
 211                     nsBuf[j] = nsBuf[i];
 212                     nsBuf[i] = t;
 213                 }
 214             }
 215         }
 216 
 217         // write them out
 218         for( int i=0; i<count; i++ )
 219             writeNsDecl(nsBuf[i]);
 220     }
 221 }