1 /*
   2  * Copyright (c) 1997, 2017, 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 /*
  27  * Licensed Materials - Property of IBM
  28  * RMI-IIOP v1.0
  29  * Copyright IBM Corp. 1998 1999  All Rights Reserved
  30  *
  31  */
  32 
  33 package com.sun.corba.se.impl.encoding;
  34 
  35 import java.io.IOException;
  36 import java.io.Serializable;
  37 import java.io.ByteArrayInputStream;
  38 import java.io.ObjectInputStream;
  39 import java.io.IOException;
  40 import java.io.StreamCorruptedException;
  41 import java.io.OptionalDataException;
  42 import java.io.IOException;
  43 
  44 import java.util.Stack;
  45 
  46 import java.net.URL;
  47 import java.net.MalformedURLException;
  48 
  49 import java.nio.ByteBuffer;
  50 
  51 import java.lang.reflect.InvocationTargetException;
  52 import java.lang.reflect.Method;
  53 
  54 import java.math.BigDecimal;
  55 
  56 import java.rmi.Remote;
  57 import java.rmi.StubNotFoundException;
  58 
  59 import java.security.AccessController;
  60 import java.security.PrivilegedExceptionAction;
  61 import java.security.PrivilegedActionException;
  62 
  63 import org.omg.CORBA.SystemException;
  64 import org.omg.CORBA.Object;
  65 import org.omg.CORBA.Principal;
  66 import org.omg.CORBA.TypeCode;
  67 import org.omg.CORBA.Any;
  68 import org.omg.CORBA.portable.Delegate;
  69 import org.omg.CORBA.portable.ValueBase;
  70 import org.omg.CORBA.portable.IndirectionException;
  71 import org.omg.CORBA.CompletionStatus;
  72 import org.omg.CORBA.TCKind;
  73 import org.omg.CORBA.TypeCodePackage.BadKind;
  74 import org.omg.CORBA.CustomMarshal;
  75 import org.omg.CORBA.TypeCode;
  76 import org.omg.CORBA.Principal;
  77 import org.omg.CORBA.Any;
  78 import org.omg.CORBA.portable.BoxedValueHelper;
  79 import org.omg.CORBA.portable.ValueFactory;
  80 import org.omg.CORBA.portable.CustomValue;
  81 import org.omg.CORBA.portable.StreamableValue;
  82 import org.omg.CORBA.MARSHAL;
  83 import org.omg.CORBA.portable.IDLEntity;
  84 
  85 import javax.rmi.PortableRemoteObject;
  86 import javax.rmi.CORBA.Tie;
  87 import javax.rmi.CORBA.Util;
  88 import javax.rmi.CORBA.ValueHandler;
  89 
  90 import com.sun.corba.se.pept.protocol.MessageMediator;
  91 import com.sun.corba.se.pept.transport.ByteBufferPool;
  92 
  93 import com.sun.corba.se.spi.protocol.RequestDispatcherRegistry;
  94 import com.sun.corba.se.spi.protocol.CorbaClientDelegate;
  95 
  96 import com.sun.corba.se.spi.ior.IOR;
  97 import com.sun.corba.se.spi.ior.IORFactories;
  98 import com.sun.corba.se.spi.ior.iiop.GIOPVersion;
  99 
 100 import com.sun.corba.se.spi.orb.ORB;
 101 import com.sun.corba.se.spi.orb.ORBVersionFactory;
 102 import com.sun.corba.se.spi.orb.ORBVersion;
 103 
 104 import com.sun.corba.se.spi.protocol.CorbaMessageMediator;
 105 
 106 import com.sun.corba.se.spi.logging.CORBALogDomains;
 107 import com.sun.corba.se.spi.presentation.rmi.PresentationManager;
 108 import com.sun.corba.se.spi.presentation.rmi.StubAdapter;
 109 import com.sun.corba.se.spi.presentation.rmi.PresentationDefaults;
 110 
 111 import com.sun.corba.se.impl.logging.ORBUtilSystemException;
 112 import com.sun.corba.se.impl.logging.OMGSystemException;
 113 
 114 import com.sun.corba.se.impl.corba.PrincipalImpl;
 115 import com.sun.corba.se.impl.corba.TypeCodeImpl;
 116 import com.sun.corba.se.impl.corba.CORBAObjectImpl;
 117 
 118 import com.sun.corba.se.impl.encoding.CDROutputObject;
 119 import com.sun.corba.se.impl.encoding.CodeSetConversion;
 120 
 121 import com.sun.corba.se.impl.util.Utility;
 122 import com.sun.corba.se.impl.util.RepositoryId;
 123 
 124 import com.sun.corba.se.impl.orbutil.RepositoryIdStrings;
 125 import com.sun.corba.se.impl.orbutil.RepositoryIdInterface;
 126 import com.sun.corba.se.impl.orbutil.RepositoryIdUtility;
 127 import com.sun.corba.se.impl.orbutil.RepositoryIdFactory;
 128 
 129 import com.sun.corba.se.impl.orbutil.ORBUtility;
 130 import com.sun.corba.se.impl.orbutil.CacheTable;
 131 
 132 
 133 import com.sun.org.omg.CORBA.portable.ValueHelper;
 134 
 135 import com.sun.org.omg.SendingContext.CodeBase;
 136 
 137 public class CDRInputStream_1_0 extends CDRInputStreamBase
 138     implements RestorableInputStream
 139 {
 140     private static final String kReadMethod = "read";
 141     private static final int maxBlockLength = 0x7fffff00;
 142 
 143     protected BufferManagerRead bufferManagerRead;
 144     protected ByteBufferWithInfo bbwi;
 145 
 146     // Set to the ORB's transportDebugFlag value.  This value is
 147     // used if the ORB is null.
 148     private boolean debug = false;
 149 
 150     protected boolean littleEndian;
 151     protected ORB orb;
 152     protected ORBUtilSystemException wrapper ;
 153     protected OMGSystemException omgWrapper ;
 154     protected ValueHandler valueHandler = null;
 155 
 156     // Value cache
 157     private CacheTable valueCache = null;
 158 
 159     // Repository ID cache
 160     private CacheTable repositoryIdCache = null;
 161 
 162     // codebase cache
 163     private CacheTable codebaseCache = null;
 164 
 165     // Current Class Stack (repository Ids of current class being read)
 166     // private Stack currentStack = null;
 167 
 168     // Length of current chunk, or a large positive number if not in a chunk
 169     protected int blockLength = maxBlockLength;
 170 
 171     // Read end flag (value nesting depth)
 172     protected int end_flag = 0;
 173 
 174     // Beginning with the resolution to interop issue 3526 (4328?),
 175     // only enclosing chunked valuetypes are taken into account
 176     // when computing the nesting level.  However, we still need
 177     // the old computation around for interoperability with our
 178     // older ORBs.
 179     private int chunkedValueNestingLevel = 0;
 180 
 181     // Flag used to determine whether blocksize was zero
 182     // private int checkForNullBlock = -1;
 183 
 184     // In block flag
 185     // private boolean inBlock = false;
 186 
 187     // Indicates whether we are inside a value
 188     // private boolean outerValueDone = true;
 189 
 190     // Int used by read_value(Serializable) that is set by this class
 191     // before calling ValueFactory.read_value
 192     protected int valueIndirection = 0;
 193 
 194     // Int set by readStringOrIndirection to communicate the actual
 195     // offset of the string length field back to the caller
 196     protected int stringIndirection = 0;
 197 
 198     // Flag indicating whether we are unmarshalling a chunked value
 199     protected boolean isChunked = false;
 200 
 201     // Repository ID handlers
 202     private RepositoryIdUtility repIdUtil;
 203     private RepositoryIdStrings repIdStrs;
 204 
 205     // Code set converters (created when first needed)
 206     private CodeSetConversion.BTCConverter charConverter;
 207     private CodeSetConversion.BTCConverter wcharConverter;
 208 
 209     // RMI-IIOP stream format version 2 case in which we know
 210     // that there is no more optional data available.  If the
 211     // Serializable's readObject method tries to read anything,
 212     // we must throw a MARSHAL with the special minor code
 213     // so that the ValueHandler can give the correct exception
 214     // to readObject.  The state is cleared when the ValueHandler
 215     // calls end_value after the readObject method exits.
 216     private boolean specialNoOptionalDataState = false;
 217 
 218     // Template method
 219     public CDRInputStreamBase dup()
 220     {
 221         CDRInputStreamBase result = null ;
 222 
 223         try {
 224             result = (CDRInputStreamBase)this.getClass().newInstance();
 225         } catch (Exception e) {
 226             throw wrapper.couldNotDuplicateCdrInputStream( e ) ;
 227         }
 228         result.init(this.orb,
 229                     this.bbwi.byteBuffer,
 230                     this.bbwi.buflen,
 231                     this.littleEndian,
 232                     this.bufferManagerRead);
 233 
 234         ((CDRInputStream_1_0)result).bbwi.position(this.bbwi.position());
 235         // To ensure we keep bbwi.byteBuffer.limit in sync with bbwi.buflen.
 236         ((CDRInputStream_1_0)result).bbwi.byteBuffer.limit(this.bbwi.buflen);
 237 
 238         return result;
 239     }
 240 
 241     /**
 242      * NOTE:  size passed to init means buffer size
 243      */
 244     public void init(org.omg.CORBA.ORB orb,
 245                      ByteBuffer byteBuffer,
 246                      int size,
 247                      boolean littleEndian,
 248                      BufferManagerRead bufferManager)
 249     {
 250         this.orb = (ORB)orb;
 251         this.wrapper = ORBUtilSystemException.get( (ORB)orb,
 252             CORBALogDomains.RPC_ENCODING ) ;
 253         this.omgWrapper = OMGSystemException.get( (ORB)orb,
 254             CORBALogDomains.RPC_ENCODING ) ;
 255         this.littleEndian = littleEndian;
 256         this.bufferManagerRead = bufferManager;
 257         this.bbwi = new ByteBufferWithInfo(orb,byteBuffer,0);
 258         this.bbwi.buflen = size;
 259         this.bbwi.byteBuffer.limit(bbwi.buflen);
 260         this.markAndResetHandler = bufferManagerRead.getMarkAndResetHandler();
 261 
 262         debug = ((ORB)orb).transportDebugFlag;
 263     }
 264 
 265     // See description in CDRInputStream
 266     void performORBVersionSpecificInit() {
 267         createRepositoryIdHandlers();
 268     }
 269 
 270     private final void createRepositoryIdHandlers()
 271     {
 272         repIdUtil = RepositoryIdFactory.getRepIdUtility();
 273         repIdStrs = RepositoryIdFactory.getRepIdStringsFactory();
 274     }
 275 
 276     public GIOPVersion getGIOPVersion() {
 277         return GIOPVersion.V1_0;
 278     }
 279 
 280     // Called by Request and Reply message. Valid for GIOP versions >= 1.2 only.
 281     // Illegal for GIOP versions < 1.2.
 282     void setHeaderPadding(boolean headerPadding) {
 283         throw wrapper.giopVersionError();
 284     }
 285 
 286     protected final int computeAlignment(int index, int align) {
 287         if (align > 1) {
 288             int incr = index & (align - 1);
 289             if (incr != 0)
 290                 return align - incr;
 291         }
 292 
 293         return 0;
 294     }
 295 
 296     public int getSize()
 297     {
 298         return bbwi.position();
 299     }
 300 
 301     protected void checkBlockLength(int align, int dataSize) {
 302         // Since chunks can end at arbitrary points (though not within
 303         // primitive CDR types, arrays of primitives, strings, wstrings,
 304         // or indirections),
 305         // we must check here for termination of the current chunk.
 306         if (!isChunked)
 307             return;
 308 
 309         // RMI-IIOP stream format version 2 case in which we know
 310         // that there is no more optional data available.  If the
 311         // Serializable's readObject method tries to read anything,
 312         // we must throw a MARSHAL exception with the special minor code
 313         // so that the ValueHandler can give the correct exception
 314         // to readObject.  The state is cleared when the ValueHandler
 315         // calls end_value after the readObject method exits.
 316         if (specialNoOptionalDataState) {
 317             throw omgWrapper.rmiiiopOptionalDataIncompatible1() ;
 318         }
 319 
 320         boolean checkForEndTag = false;
 321 
 322         // Are we at the end of the current chunk?  If so,
 323         // try to interpret the next long as a chunk length.
 324         // (It has to be either a chunk length, end tag,
 325         // or valuetag.)
 326         //
 327         // If it isn't a chunk length, blockLength will
 328         // remain set to maxBlockLength.
 329         if (blockLength == get_offset()) {
 330 
 331             blockLength = maxBlockLength;
 332             start_block();
 333 
 334             // What's next is either a valuetag or
 335             // an end tag.  If it's a valuetag, we're
 336             // probably being called as part of the process
 337             // to read the valuetag.  If it's an end tag,
 338             // then there isn't enough data left in
 339             // this valuetype to read!
 340             if (blockLength == maxBlockLength)
 341                 checkForEndTag = true;
 342 
 343         } else
 344         if (blockLength < get_offset()) {
 345             // Are we already past the end of the current chunk?
 346             // This is always an error.
 347             throw wrapper.chunkOverflow() ;
 348         }
 349 
 350         // If what's next on the wire isn't a chunk length or
 351         // what we want to read (which can't be split across chunks)
 352         // won't fit in the current chunk, throw this exception.
 353         // This probably means that we're in an RMI-IIOP
 354         // Serializable's readObject method or a custom marshaled
 355         // IDL type is reading too much/in an incorrect order
 356         int requiredNumBytes =
 357                             computeAlignment(bbwi.position(), align) + dataSize;
 358 
 359         if (blockLength != maxBlockLength &&
 360             blockLength < get_offset() + requiredNumBytes) {
 361             throw omgWrapper.rmiiiopOptionalDataIncompatible2() ;
 362         }
 363 
 364         // REVISIT - We should look at using the built in advancement
 365         //           of using ByteBuffer.get() rather than explicitly
 366         //           advancing the ByteBuffer's position.
 367         //           This is true for anywhere we are incrementing
 368         //           the ByteBuffer's position.
 369         if (checkForEndTag) {
 370             int nextLong = read_long();
 371             bbwi.position(bbwi.position() - 4);
 372 
 373             // It was an end tag, so there wasn't enough data
 374             // left in the valuetype's encoding on the wire
 375             // to read what we wanted
 376             if (nextLong < 0)
 377                 throw omgWrapper.rmiiiopOptionalDataIncompatible3() ;
 378         }
 379     }
 380 
 381     protected void alignAndCheck(int align, int n) {
 382 
 383         checkBlockLength(align, n);
 384 
 385         // WARNING: Must compute real alignment after calling
 386         // checkBlockLength since it may move the position
 387         int alignResult = computeAlignment(bbwi.position(), align);
 388         bbwi.position(bbwi.position() + alignResult);
 389 
 390         if (bbwi.position() + n > bbwi.buflen)
 391             grow(align, n);
 392     }
 393 
 394     //
 395     // This can be overridden....
 396     //
 397     protected void grow(int align, int n) {
 398 
 399         bbwi.needed = n;
 400 
 401         bbwi = bufferManagerRead.underflow(bbwi);
 402 
 403     }
 404 
 405     //
 406     // Marshal primitives.
 407     //
 408 
 409     public final void consumeEndian() {
 410         littleEndian = read_boolean();
 411     }
 412 
 413     // No such type in java
 414     public final double read_longdouble() {
 415         throw wrapper.longDoubleNotImplemented( CompletionStatus.COMPLETED_MAYBE);
 416     }
 417 
 418     public final boolean read_boolean() {
 419         return (read_octet() != 0);
 420     }
 421 
 422     public final char read_char() {
 423         alignAndCheck(1, 1);
 424 
 425         return getConvertedChars(1, getCharConverter())[0];
 426     }
 427 
 428     public char read_wchar() {
 429 
 430         // Don't allow transmission of wchar/wstring data with
 431         // foreign ORBs since it's against the spec.
 432         if (ORBUtility.isForeignORB((ORB)orb)) {
 433             throw wrapper.wcharDataInGiop10( CompletionStatus.COMPLETED_MAYBE);
 434         }
 435 
 436         // If we're talking to one of our legacy ORBs, do what
 437         // they did:
 438         int b1, b2;
 439 
 440         alignAndCheck(2, 2);
 441 
 442         if (littleEndian) {
 443             b2 = bbwi.byteBuffer.get(bbwi.position()) & 0x00FF;
 444             bbwi.position(bbwi.position() + 1);
 445             b1 = bbwi.byteBuffer.get(bbwi.position()) & 0x00FF;
 446             bbwi.position(bbwi.position() + 1);
 447         } else {
 448             b1 = bbwi.byteBuffer.get(bbwi.position()) & 0x00FF;
 449             bbwi.position(bbwi.position() + 1);
 450             b2 = bbwi.byteBuffer.get(bbwi.position()) & 0x00FF;
 451             bbwi.position(bbwi.position() + 1);
 452         }
 453 
 454         return (char)((b1 << 8) + (b2 << 0));
 455     }
 456 
 457     public final byte read_octet() {
 458 
 459         alignAndCheck(1, 1);
 460 
 461         byte b = bbwi.byteBuffer.get(bbwi.position());
 462         bbwi.position(bbwi.position() + 1);
 463 
 464         return b;
 465     }
 466 
 467     public final short read_short() {
 468         int b1, b2;
 469 
 470         alignAndCheck(2, 2);
 471 
 472         if (littleEndian) {
 473             b2 = (bbwi.byteBuffer.get(bbwi.position()) << 0) & 0x000000FF;
 474             bbwi.position(bbwi.position() + 1);
 475             b1 = (bbwi.byteBuffer.get(bbwi.position()) << 8) & 0x0000FF00;
 476             bbwi.position(bbwi.position() + 1);
 477         } else {
 478             b1 = (bbwi.byteBuffer.get(bbwi.position()) << 8) & 0x0000FF00;
 479             bbwi.position(bbwi.position() + 1);
 480             b2 = (bbwi.byteBuffer.get(bbwi.position()) << 0) & 0x000000FF;
 481             bbwi.position(bbwi.position() + 1);
 482         }
 483 
 484         return (short)(b1 | b2);
 485     }
 486 
 487     public final short read_ushort() {
 488         return read_short();
 489     }
 490 
 491     public final int read_long() {
 492         int b1, b2, b3, b4;
 493 
 494         alignAndCheck(4, 4);
 495 
 496         int bufPos = bbwi.position();
 497         if (littleEndian) {
 498             b4 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 499             b3 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 500             b2 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 501             b1 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 502         } else {
 503             b1 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 504             b2 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 505             b3 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 506             b4 = bbwi.byteBuffer.get(bufPos++) & 0xFF;
 507         }
 508         bbwi.position(bufPos);
 509 
 510         return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
 511     }
 512 
 513     public final int read_ulong() {
 514         return read_long();
 515     }
 516 
 517     public final long read_longlong() {
 518         long i1, i2;
 519 
 520         alignAndCheck(8, 8);
 521 
 522         if (littleEndian) {
 523             i2 = read_long() & 0xFFFFFFFFL;
 524             i1 = (long)read_long() << 32;
 525         } else {
 526             i1 = (long)read_long() << 32;
 527             i2 = read_long() & 0xFFFFFFFFL;
 528         }
 529 
 530         return (i1 | i2);
 531     }
 532 
 533     public final long read_ulonglong() {
 534         return read_longlong();
 535     }
 536 
 537     public final float read_float() {
 538         return Float.intBitsToFloat(read_long());
 539     }
 540 
 541     public final double read_double() {
 542         return Double.longBitsToDouble(read_longlong());
 543     }
 544 
 545     protected final void checkForNegativeLength(int length) {
 546         if (length < 0)
 547             throw wrapper.negativeStringLength( CompletionStatus.COMPLETED_MAYBE,
 548                 new Integer(length) ) ;
 549     }
 550 
 551     protected final String readStringOrIndirection(boolean allowIndirection) {
 552 
 553         int len = read_long();
 554 
 555         //
 556         // Check for indirection
 557         //
 558         if (allowIndirection) {
 559             if (len == 0xffffffff)
 560                 return null;
 561             else
 562                 stringIndirection = get_offset() - 4;
 563         }
 564 
 565         checkForNegativeLength(len);
 566 
 567         return internalReadString(len);
 568     }
 569 
 570     private final String internalReadString(int len) {
 571         // Workaround for ORBs which send string lengths of
 572         // zero to mean empty string.
 573         //
 574         // IMPORTANT: Do not replace 'new String("")' with "", it may result
 575         // in a Serialization bug (See serialization.zerolengthstring) and
 576         // bug id: 4728756 for details
 577         if (len == 0)
 578             return new String("");
 579 
 580         char[] result = getConvertedChars(len - 1, getCharConverter());
 581 
 582         // Skip over the 1 byte null
 583         read_octet();
 584 
 585         return new String(result, 0, getCharConverter().getNumChars());
 586     }
 587 
 588     public final String read_string() {
 589         return readStringOrIndirection(false);
 590     }
 591 
 592     public String read_wstring() {
 593         // Don't allow transmission of wchar/wstring data with
 594         // foreign ORBs since it's against the spec.
 595         if (ORBUtility.isForeignORB((ORB)orb)) {
 596             throw wrapper.wcharDataInGiop10( CompletionStatus.COMPLETED_MAYBE);
 597         }
 598 
 599         int len = read_long();
 600 
 601         //
 602         // Workaround for ORBs which send string lengths of
 603         // zero to mean empty string.
 604         //
 605         //
 606         // IMPORTANT: Do not replace 'new String("")' with "", it may result
 607         // in a Serialization bug (See serialization.zerolengthstring) and
 608         // bug id: 4728756 for details
 609         if (len == 0)
 610             return new String("");
 611 
 612         checkForNegativeLength(len);
 613 
 614         len--;
 615         char[] c = new char[len];
 616 
 617         for (int i = 0; i < len; i++)
 618             c[i] = read_wchar();
 619 
 620         // skip the two null terminator bytes
 621         read_wchar();
 622         // bbwi.position(bbwi.position() + 2);
 623 
 624         return new String(c);
 625     }
 626 
 627     public final void read_octet_array(byte[] b, int offset, int length) {
 628         if ( b == null )
 629             throw wrapper.nullParam() ;
 630 
 631         // Must call alignAndCheck at least once to ensure
 632         // we aren't at the end of a chunk.  Of course, we
 633         // should only call it if we actually need to read
 634         // something, otherwise we might end up with an
 635         // exception at the end of the stream.
 636         if (length == 0)
 637             return;
 638 
 639         alignAndCheck(1, 1);
 640 
 641         int n = offset;
 642         while (n < length+offset) {
 643             int avail;
 644             int bytes;
 645             int wanted;
 646 
 647             avail = bbwi.buflen - bbwi.position();
 648             if (avail <= 0) {
 649                 grow(1, 1);
 650                 avail = bbwi.buflen - bbwi.position();
 651             }
 652             wanted = (length + offset) - n;
 653             bytes = (wanted < avail) ? wanted : avail;
 654             // Microbenchmarks are showing a loop of ByteBuffer.get(int) being
 655             // faster than ByteBuffer.get(byte[], int, int).
 656             for (int i = 0; i < bytes; i++) {
 657                 b[n+i] = bbwi.byteBuffer.get(bbwi.position() + i);
 658             }
 659 
 660             bbwi.position(bbwi.position() + bytes);
 661 
 662             n += bytes;
 663         }
 664     }
 665 
 666     public Principal read_Principal() {
 667         int len = read_long();
 668         byte[] pvalue = new byte[len];
 669         read_octet_array(pvalue,0,len);
 670 
 671         Principal p = new PrincipalImpl();
 672         p.name(pvalue);
 673         return p;
 674     }
 675 
 676     public TypeCode read_TypeCode() {
 677         TypeCodeImpl tc = new TypeCodeImpl(orb);
 678         tc.read_value(parent);
 679         return tc;
 680     }
 681 
 682     public Any read_any() {
 683         Any any = orb.create_any();
 684         TypeCodeImpl tc = new TypeCodeImpl(orb);
 685 
 686         // read off the typecode
 687 
 688         // REVISIT We could avoid this try-catch if we could peek the typecode
 689         // kind off this stream and see if it is a tk_value.  Looking at the
 690         // code we know that for tk_value the Any.read_value() below
 691         // ignores the tc argument anyway (except for the kind field).
 692         // But still we would need to make sure that the whole typecode,
 693         // including encapsulations, is read off.
 694         try {
 695             tc.read_value(parent);
 696         } catch (MARSHAL ex) {
 697             if (tc.kind().value() != TCKind._tk_value)
 698                 throw ex;
 699             // We can be sure that the whole typecode encapsulation has been
 700             // read off.
 701             dprintThrowable(ex);
 702         }
 703         // read off the value of the any
 704         any.read_value(parent, tc);
 705 
 706         return any;
 707     }
 708 
 709     public org.omg.CORBA.Object read_Object() {
 710         return read_Object(null);
 711     }
 712 
 713     // ------------ RMI related methods --------------------------
 714 
 715     // IDL to Java ptc-00-01-08 1.21.4.1
 716     //
 717     // The clz argument to read_Object can be either a stub
 718     // Class or the "Class object for the RMI/IDL interface type
 719     // that is statically expected."
 720     // This functions as follows:
 721     // 1. If clz==null, just use the repository ID from the stub
 722     // 2. If clz is a stub class, just use it as a static factory.
 723     //    clz is a stub class iff StubAdapter.isStubClass( clz ).
 724     //    In addition, clz is a IDL stub class iff
 725     //    IDLEntity.class.isAssignableFrom( clz ).
 726     // 3. If clz is an interface, use it to create the appropriate
 727     //    stub factory.
 728 
 729     public org.omg.CORBA.Object read_Object(Class clz)
 730     {
 731         // In any case, we must first read the IOR.
 732         IOR ior = IORFactories.makeIOR(parent) ;
 733         if (ior.isNil()) {
 734             return null ;
 735         }
 736 
 737         PresentationManager.StubFactoryFactory sff = ORB.getStubFactoryFactory() ;
 738         String codeBase = ior.getProfile().getCodebase() ;
 739         PresentationManager.StubFactory stubFactory = null ;
 740 
 741         if (clz == null) {
 742             RepositoryId rid = RepositoryId.cache.getId( ior.getTypeId() ) ;
 743             String className = rid.getClassName() ;
 744             orb.validateIORClass(className);
 745             boolean isIDLInterface = rid.isIDLType() ;
 746 
 747             if (className == null || className.equals( "" ))
 748                 stubFactory = null ;
 749             else
 750                 try {
 751                     stubFactory = sff.createStubFactory( className,
 752                         isIDLInterface, codeBase, (Class)null,
 753                         (ClassLoader)null );
 754                 } catch (Exception exc) {
 755                     // Could not create stubFactory, so use null.
 756                     // XXX stubFactory handling is still too complex:
 757                     // Can we resolve the stubFactory question once in
 758                     // a single place?
 759                     stubFactory = null ;
 760                 }
 761         } else if (StubAdapter.isStubClass( clz )) {
 762             stubFactory = PresentationDefaults.makeStaticStubFactory(
 763                 clz ) ;
 764         } else {
 765             // clz is an interface class
 766             boolean isIDL = IDLEntity.class.isAssignableFrom( clz ) ;
 767             stubFactory = sff.createStubFactory( clz.getName(),
 768                 isIDL, codeBase, clz, clz.getClassLoader() ) ;
 769         }
 770         return internalIORToObject( ior, stubFactory, orb ) ;
 771     }
 772 
 773     /*
 774      * This is used as a general utility (e.g., the PortableInterceptor
 775      * implementation uses it.   If stubFactory is null, the ior's
 776      * IIOPProfile must support getServant.
 777      */
 778     public static org.omg.CORBA.Object internalIORToObject(
 779         IOR ior, PresentationManager.StubFactory stubFactory, ORB orb)
 780     {
 781         ORBUtilSystemException wrapper = ORBUtilSystemException.get(
 782             (ORB)orb, CORBALogDomains.RPC_ENCODING ) ;
 783 
 784         java.lang.Object servant = ior.getProfile().getServant() ;
 785         if (servant != null ) {
 786             if (servant instanceof Tie) {
 787                 String codebase = ior.getProfile().getCodebase();
 788                 org.omg.CORBA.Object objref = (org.omg.CORBA.Object)
 789                     Utility.loadStub( (Tie)servant, stubFactory, codebase,
 790                         false);
 791 
 792                 // If we managed to load a stub, return it, otherwise we
 793                 // must fail...
 794                 if (objref != null) {
 795                     return objref;
 796                 } else {
 797                     throw wrapper.readObjectException() ;
 798                 }
 799             } else if (servant instanceof org.omg.CORBA.Object) {
 800                 if (!(servant instanceof
 801                         org.omg.CORBA.portable.InvokeHandler)) {
 802                     return (org.omg.CORBA.Object) servant;
 803                 }
 804             } else
 805                 throw wrapper.badServantReadObject() ;
 806         }
 807 
 808         CorbaClientDelegate del = ORBUtility.makeClientDelegate( ior ) ;
 809         org.omg.CORBA.Object objref = null ;
 810         try {
 811             objref = stubFactory.makeStub() ;
 812         } catch (Throwable e) {
 813             wrapper.stubCreateError( e ) ;
 814 
 815             if (e instanceof ThreadDeath) {
 816                 throw (ThreadDeath) e;
 817             }
 818 
 819             // Return the "default" stub...
 820             objref = new CORBAObjectImpl() ;
 821         }
 822 
 823         StubAdapter.setDelegate( objref, del ) ;
 824         return objref;
 825     }
 826 
 827     public java.lang.Object read_abstract_interface()
 828     {
 829         return read_abstract_interface(null);
 830     }
 831 
 832     public java.lang.Object read_abstract_interface(java.lang.Class clz)
 833     {
 834         boolean object = read_boolean();
 835 
 836         if (object) {
 837             return read_Object(clz);
 838         } else {
 839             return read_value();
 840         }
 841     }
 842 
 843     public Serializable read_value()
 844     {
 845         return read_value((Class)null);
 846     }
 847 
 848     private Serializable handleIndirection() {
 849         int indirection = read_long() + get_offset() - 4;
 850         if (valueCache != null && valueCache.containsVal(indirection)) {
 851 
 852             java.io.Serializable cachedValue
 853                 = (java.io.Serializable)valueCache.getKey(indirection);
 854             return cachedValue;
 855         } else {
 856             // In RMI-IIOP the ValueHandler will recognize this
 857             // exception and use the provided indirection value
 858             // to lookup a possible indirection to an object
 859             // currently on the deserialization stack.
 860             throw new IndirectionException(indirection);
 861         }
 862     }
 863 
 864     private String readRepositoryIds(int valueTag,
 865                                      Class expectedType,
 866                                      String expectedTypeRepId) {
 867         return readRepositoryIds(valueTag, expectedType,
 868                                  expectedTypeRepId, null);
 869     }
 870 
 871     /**
 872      * Examines the valuetag to see how many (if any) repository IDs
 873      * are present on the wire.  If no repository ID information
 874      * is on the wire but the expectedType or expectedTypeRepId
 875      * is known, it will return one of those (favoring the
 876      * expectedType's repId). Failing that, it uses the supplied
 877      * BoxedValueHelper to obtain the repository ID, as a last resort.
 878      */
 879     private String readRepositoryIds(int valueTag,
 880                                      Class expectedType,
 881                                      String expectedTypeRepId,
 882                                      BoxedValueHelper factory) {
 883         switch(repIdUtil.getTypeInfo(valueTag)) {
 884             case RepositoryIdUtility.NO_TYPE_INFO :
 885                 // Throw an exception if we have no repository ID info and
 886                 // no expectedType to work with.  Otherwise, how would we
 887                 // know what to unmarshal?
 888                 if (expectedType == null) {
 889                     if (expectedTypeRepId != null) {
 890                         return expectedTypeRepId;
 891                     } else if (factory != null) {
 892                         return factory.get_id();
 893                     } else {
 894                         throw wrapper.expectedTypeNullAndNoRepId(
 895                             CompletionStatus.COMPLETED_MAYBE);
 896                     }
 897                 }
 898                 return repIdStrs.createForAnyType(expectedType);
 899             case RepositoryIdUtility.SINGLE_REP_TYPE_INFO :
 900                 return read_repositoryId();
 901             case RepositoryIdUtility.PARTIAL_LIST_TYPE_INFO :
 902                 return read_repositoryIds();
 903             default:
 904                 throw wrapper.badValueTag( CompletionStatus.COMPLETED_MAYBE,
 905                     Integer.toHexString(valueTag) ) ;
 906         }
 907     }
 908 
 909     public Serializable read_value(Class expectedType) {
 910 
 911         // Read value tag
 912         int vType = readValueTag();
 913 
 914         // Is value null?
 915         if (vType == 0)
 916             return null;
 917 
 918         // Is this an indirection to a previously
 919         // read valuetype?
 920         if (vType == 0xffffffff)
 921             return handleIndirection();
 922 
 923         // Save where this valuetype started so we
 924         // can put it in the indirection valueCache
 925         // later
 926         int indirection = get_offset() - 4;
 927 
 928         // Need to save this special marker variable
 929         // to restore its value during recursion
 930         boolean saveIsChunked = isChunked;
 931 
 932         isChunked = repIdUtil.isChunkedEncoding(vType);
 933 
 934         java.lang.Object value = null;
 935 
 936         String codebase_URL = null;
 937         if (repIdUtil.isCodeBasePresent(vType)) {
 938             codebase_URL = read_codebase_URL();
 939         }
 940 
 941         // Read repository id(s)
 942         String repositoryIDString
 943             = readRepositoryIds(vType, expectedType, null);
 944 
 945         // If isChunked was determined to be true based
 946         // on the valuetag, this will read a chunk length
 947         start_block();
 948 
 949         // Remember that end_flag keeps track of all nested
 950         // valuetypes and is used for older ORBs
 951         end_flag--;
 952         if (isChunked)
 953             chunkedValueNestingLevel--;
 954 
 955         if (repositoryIDString.equals(repIdStrs.getWStringValueRepId())) {
 956             value = read_wstring();
 957         } else
 958         if (repositoryIDString.equals(repIdStrs.getClassDescValueRepId())) {
 959             // read in the class whether with the old ClassDesc or the
 960             // new one
 961             value = readClass();
 962         } else {
 963 
 964             Class valueClass = expectedType;
 965 
 966             // By this point, either the expectedType or repositoryIDString
 967             // is guaranteed to be non-null.
 968             if (expectedType == null ||
 969                 !repositoryIDString.equals(repIdStrs.createForAnyType(expectedType))) {
 970 
 971                 valueClass = getClassFromString(repositoryIDString,
 972                                                 codebase_URL,
 973                                                 expectedType);
 974             }
 975 
 976             if (valueClass == null) {
 977                 // No point attempting to use value handler below, since the
 978                 // class information is not available.
 979                 throw wrapper.couldNotFindClass(
 980                     CompletionStatus.COMPLETED_MAYBE,
 981                     new ClassNotFoundException());
 982             }
 983 
 984             if (valueClass != null &&
 985                 org.omg.CORBA.portable.IDLEntity.class.isAssignableFrom(valueClass)) {
 986 
 987                 value =  readIDLValue(indirection,
 988                                       repositoryIDString,
 989                                       valueClass,
 990                                       codebase_URL);
 991 
 992             } else {
 993 
 994                 // Must be some form of RMI-IIOP valuetype
 995 
 996                 try {
 997                     if (valueHandler == null)
 998                         valueHandler = ORBUtility.createValueHandler();
 999 
1000                     value = valueHandler.readValue(parent,
1001                                                    indirection,
1002                                                    valueClass,
1003                                                    repositoryIDString,
1004                                                    getCodeBase());
1005 
1006                 } catch(SystemException sysEx) {
1007                     // Just rethrow any CORBA system exceptions
1008                     // that come out of the ValueHandler
1009                     throw sysEx;
1010                 } catch(Exception ex) {
1011                     throw wrapper.valuehandlerReadException(
1012                         CompletionStatus.COMPLETED_MAYBE, ex ) ;
1013                 } catch(Error e) {
1014                     throw wrapper.valuehandlerReadError(
1015                         CompletionStatus.COMPLETED_MAYBE, e ) ;
1016                 }
1017             }
1018         }
1019 
1020         // Skip any remaining chunks until we get to
1021         // an end tag or a valuetag.  If we see a valuetag,
1022         // that means there was another valuetype in the sender's
1023         // version of this class that we need to skip over.
1024         handleEndOfValue();
1025 
1026         // Read and process the end tag if we're chunking.
1027         // Assumes that we're at the position of the end tag
1028         // (handleEndOfValue should assure this)
1029         readEndTag();
1030 
1031         // Cache the valuetype that we read
1032         if (valueCache == null)
1033             valueCache = new CacheTable(orb,false);
1034         valueCache.put(value, indirection);
1035 
1036         // Allow for possible continuation chunk.
1037         // If we're a nested valuetype inside of a chunked
1038         // valuetype, and that enclosing valuetype has
1039         // more data to write, it will need to have this
1040         // new chunk begin after we wrote our end tag.
1041         isChunked = saveIsChunked;
1042         start_block();
1043 
1044         return (java.io.Serializable)value;
1045     }
1046 
1047     public Serializable read_value(BoxedValueHelper factory) {
1048 
1049         // Read value tag
1050         int vType = readValueTag();
1051 
1052         if (vType == 0)
1053             return null; // value is null
1054         else if (vType == 0xffffffff) { // Indirection tag
1055             int indirection = read_long() + get_offset() - 4;
1056             if (valueCache != null && valueCache.containsVal(indirection))
1057                 {
1058                     java.io.Serializable cachedValue =
1059                            (java.io.Serializable)valueCache.getKey(indirection);
1060                     return cachedValue;
1061                 }
1062             else {
1063                 throw new IndirectionException(indirection);
1064             }
1065         }
1066         else {
1067             int indirection = get_offset() - 4;
1068 
1069             // end_block();
1070 
1071             boolean saveIsChunked = isChunked;
1072             isChunked = repIdUtil.isChunkedEncoding(vType);
1073 
1074             java.lang.Object value = null;
1075 
1076             String codebase_URL = null;
1077             if (repIdUtil.isCodeBasePresent(vType)){
1078                 codebase_URL = read_codebase_URL();
1079             }
1080 
1081             // Read repository id
1082             String repositoryIDString
1083                 = readRepositoryIds(vType, null, null, factory);
1084 
1085             // Compare rep. ids to see if we should use passed helper
1086             if (!repositoryIDString.equals(factory.get_id()))
1087                 factory = Utility.getHelper(null, codebase_URL, repositoryIDString);
1088 
1089             start_block();
1090             end_flag--;
1091             if (isChunked)
1092                 chunkedValueNestingLevel--;
1093 
1094             if (factory instanceof ValueHelper) {
1095                 value = readIDLValueWithHelper((ValueHelper)factory, indirection);
1096             } else {
1097                 valueIndirection = indirection;  // for callback
1098                 value = factory.read_value(parent);
1099             }
1100 
1101             handleEndOfValue();
1102             readEndTag();
1103 
1104             // Put into valueCache
1105             if (valueCache == null)
1106                 valueCache = new CacheTable(orb,false);
1107             valueCache.put(value, indirection);
1108 
1109             // allow for possible continuation chunk
1110             isChunked = saveIsChunked;
1111             start_block();
1112 
1113             return (java.io.Serializable)value;
1114         }
1115     }
1116 
1117     private boolean isCustomType(ValueHelper helper) {
1118         try{
1119             TypeCode tc = helper.get_type();
1120             int kind = tc.kind().value();
1121             if (kind == TCKind._tk_value) {
1122                 return (tc.type_modifier() == org.omg.CORBA.VM_CUSTOM.value);
1123             }
1124         } catch(BadKind ex) {
1125             throw wrapper.badKind(ex) ;
1126         }
1127 
1128         return false;
1129     }
1130 
1131     // This method is actually called indirectly by
1132     // read_value(String repositoryId).
1133     // Therefore, it is not a truly independent read call that handles
1134     // header information itself.
1135     public java.io.Serializable read_value(java.io.Serializable value) {
1136 
1137         // Put into valueCache using valueIndirection
1138         if (valueCache == null)
1139             valueCache = new CacheTable(orb,false);
1140         valueCache.put(value, valueIndirection);
1141 
1142         if (value instanceof StreamableValue)
1143             ((StreamableValue)value)._read(parent);
1144         else if (value instanceof CustomValue)
1145             ((CustomValue)value).unmarshal(parent);
1146 
1147         return value;
1148     }
1149 
1150     public java.io.Serializable read_value(java.lang.String repositoryId) {
1151 
1152         // if (inBlock)
1153         //    end_block();
1154 
1155         // Read value tag
1156         int vType = readValueTag();
1157 
1158         if (vType == 0)
1159             return null; // value is null
1160         else if (vType == 0xffffffff) { // Indirection tag
1161             int indirection = read_long() + get_offset() - 4;
1162             if (valueCache != null && valueCache.containsVal(indirection))
1163                 {
1164                     java.io.Serializable cachedValue =
1165                           (java.io.Serializable)valueCache.getKey(indirection);
1166                     return cachedValue;
1167                 }
1168             else {
1169                 throw new IndirectionException(indirection);
1170             }
1171         }
1172         else {
1173             int indirection = get_offset() - 4;
1174 
1175             // end_block();
1176 
1177             boolean saveIsChunked = isChunked;
1178             isChunked = repIdUtil.isChunkedEncoding(vType);
1179 
1180             java.lang.Object value = null;
1181 
1182             String codebase_URL = null;
1183             if (repIdUtil.isCodeBasePresent(vType)){
1184                 codebase_URL = read_codebase_URL();
1185             }
1186 
1187             // Read repository id
1188             String repositoryIDString
1189                 = readRepositoryIds(vType, null, repositoryId);
1190 
1191             ValueFactory factory =
1192                Utility.getFactory(null, codebase_URL, orb, repositoryIDString);
1193 
1194             start_block();
1195             end_flag--;
1196             if (isChunked)
1197                 chunkedValueNestingLevel--;
1198 
1199             valueIndirection = indirection;  // for callback
1200             value = factory.read_value(parent);
1201 
1202             handleEndOfValue();
1203             readEndTag();
1204 
1205             // Put into valueCache
1206             if (valueCache == null)
1207                 valueCache = new CacheTable(orb,false);
1208             valueCache.put(value, indirection);
1209 
1210             // allow for possible continuation chunk
1211             isChunked = saveIsChunked;
1212             start_block();
1213 
1214             return (java.io.Serializable)value;
1215         }
1216     }
1217 
1218     private Class readClass() {
1219 
1220         String codebases = null, classRepId = null;
1221 
1222         if (orb == null ||
1223             ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) ||
1224             ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) {
1225 
1226             codebases = (String)read_value(java.lang.String.class);
1227             classRepId = (String)read_value(java.lang.String.class);
1228         } else {
1229             // Pre-Merlin/J2EE 1.3 ORBs wrote the repository ID
1230             // and codebase strings in the wrong order.
1231             classRepId = (String)read_value(java.lang.String.class);
1232             codebases = (String)read_value(java.lang.String.class);
1233         }
1234 
1235         if (debug) {
1236             dprint("readClass codebases: "
1237                    + codebases
1238                    + " rep Id: "
1239                    + classRepId);
1240         }
1241 
1242         Class cl = null;
1243 
1244         RepositoryIdInterface repositoryID
1245             = repIdStrs.getFromString(classRepId);
1246 
1247         try {
1248             cl = repositoryID.getClassFromType(codebases);
1249         } catch(ClassNotFoundException cnfe) {
1250             throw wrapper.cnfeReadClass( CompletionStatus.COMPLETED_MAYBE,
1251                 cnfe, repositoryID.getClassName() ) ;
1252         } catch(MalformedURLException me) {
1253             throw wrapper.malformedUrl( CompletionStatus.COMPLETED_MAYBE,
1254                 me, repositoryID.getClassName(), codebases ) ;
1255         }
1256 
1257         return cl;
1258     }
1259 
1260     private java.lang.Object readIDLValueWithHelper(ValueHelper helper, int indirection)
1261     {
1262         // look for two-argument static read method
1263         Method readMethod;
1264         try {
1265             Class argTypes[] = {org.omg.CORBA.portable.InputStream.class, helper.get_class()};
1266             readMethod = helper.getClass().getDeclaredMethod(kReadMethod, argTypes);
1267         }
1268         catch(NoSuchMethodException nsme) { // must be boxed value helper
1269             java.lang.Object result = helper.read_value(parent);
1270             return result;
1271         }
1272 
1273         // found two-argument read method, so must be non-boxed value...
1274         // ...create a blank instance
1275         java.lang.Object val = null;
1276         try {
1277             val = helper.get_class().newInstance();
1278         } catch(java.lang.InstantiationException ie) {
1279             throw wrapper.couldNotInstantiateHelper( ie,
1280                 helper.get_class() ) ;
1281         } catch(IllegalAccessException iae){
1282             // Value's constructor is protected or private
1283             //
1284             // So, use the helper to read the value.
1285             //
1286             // NOTE : This means that in this particular case a recursive ref.
1287             // would fail.
1288             return helper.read_value(parent);
1289         }
1290 
1291         // add blank instance to cache table
1292         if (valueCache == null)
1293             valueCache = new CacheTable(orb,false);
1294         valueCache.put(val, indirection);
1295 
1296         // if custom type, call unmarshal method
1297         if (val instanceof CustomMarshal && isCustomType(helper)) {
1298             ((CustomMarshal)val).unmarshal(parent);
1299             return val;
1300         }
1301 
1302         // call two-argument read method using reflection
1303         try {
1304             java.lang.Object args[] = {parent, val};
1305             readMethod.invoke(helper, args);
1306             return val;
1307         } catch(IllegalAccessException iae2) {
1308             throw wrapper.couldNotInvokeHelperReadMethod( iae2, helper.get_class() ) ;
1309         } catch(InvocationTargetException ite){
1310             throw wrapper.couldNotInvokeHelperReadMethod( ite, helper.get_class() ) ;
1311         }
1312     }
1313 
1314     private java.lang.Object readBoxedIDLEntity(Class clazz, String codebase)
1315     {
1316         Class cls = null ;
1317 
1318         try {
1319             ClassLoader clazzLoader = (clazz == null ? null : clazz.getClassLoader());
1320 
1321             cls = Utility.loadClassForClass(clazz.getName()+"Helper", codebase,
1322                                                    clazzLoader, clazz, clazzLoader);
1323             final Class helperClass = cls ;
1324 
1325             final Class argTypes[] = {org.omg.CORBA.portable.InputStream.class};
1326 
1327             // getDeclaredMethod requires RuntimePermission accessDeclaredMembers
1328             // if a different class loader is used (even though the javadoc says otherwise)
1329             Method readMethod = null;
1330             try {
1331                 readMethod = (Method)AccessController.doPrivileged(
1332                     new PrivilegedExceptionAction() {
1333                         public java.lang.Object run() throws NoSuchMethodException {
1334                             return helperClass.getDeclaredMethod(kReadMethod, argTypes);
1335                         }
1336                     }
1337                 );
1338             } catch (PrivilegedActionException pae) {
1339                 // this gets caught below
1340                 throw (NoSuchMethodException)pae.getException();
1341             }
1342 
1343             java.lang.Object args[] = {parent};
1344             return readMethod.invoke(null, args);
1345 
1346         } catch (ClassNotFoundException cnfe) {
1347             throw wrapper.couldNotInvokeHelperReadMethod( cnfe, cls ) ;
1348         } catch(NoSuchMethodException nsme) {
1349             throw wrapper.couldNotInvokeHelperReadMethod( nsme, cls ) ;
1350         } catch(IllegalAccessException iae) {
1351             throw wrapper.couldNotInvokeHelperReadMethod( iae, cls ) ;
1352         } catch(InvocationTargetException ite) {
1353             throw wrapper.couldNotInvokeHelperReadMethod( ite, cls ) ;
1354         }
1355     }
1356 
1357     private java.lang.Object readIDLValue(int indirection, String repId,
1358                                           Class clazz, String codebase)
1359     {
1360         ValueFactory factory ;
1361 
1362         // Always try to find a ValueFactory first, as required by the spec.
1363         // There are some complications here in the IDL 3.0 mapping (see 1.13.8),
1364         // but basically we must always be able to override the DefaultFactory
1365         // or Helper mappings that are also used.  This appears to be the case
1366         // even in the boxed value cases.  The original code only did the lookup
1367         // in the case of class implementing either StreamableValue or CustomValue,
1368         // but abstract valuetypes only implement ValueBase, and really require
1369         // the use of the repId to find a factory (including the DefaultFactory).
1370         try {
1371             // use new-style OBV support (factory object)
1372             factory = Utility.getFactory(clazz, codebase, orb, repId);
1373         } catch (MARSHAL marshal) {
1374             // XXX log marshal at one of the INFO levels
1375 
1376             // Could not get a factory, so try alternatives
1377             if (!StreamableValue.class.isAssignableFrom(clazz) &&
1378                 !CustomValue.class.isAssignableFrom(clazz) &&
1379                 ValueBase.class.isAssignableFrom(clazz)) {
1380                 // use old-style OBV support (helper object)
1381                 BoxedValueHelper helper = Utility.getHelper(clazz, codebase, repId);
1382                 if (helper instanceof ValueHelper)
1383                     return readIDLValueWithHelper((ValueHelper)helper, indirection);
1384                 else
1385                     return helper.read_value(parent);
1386             } else {
1387                 // must be a boxed IDLEntity, so make a reflective call to the
1388                 // helper's static read method...
1389                 return readBoxedIDLEntity(clazz, codebase);
1390             }
1391         }
1392 
1393         // If there was no error in getting the factory, use it.
1394         valueIndirection = indirection;  // for callback
1395         return factory.read_value(parent);
1396     }
1397 
1398     /**
1399      * End tags are only written for chunked valuetypes.
1400      *
1401      * Before Merlin, our ORBs wrote end tags which took into account
1402      * all enclosing valuetypes.  This was changed by an interop resolution
1403      * (see details around chunkedValueNestingLevel) to only include
1404      * enclosing chunked types.
1405      *
1406      * ORB versioning and end tag compaction are handled here.
1407      */
1408     private void readEndTag() {
1409         if (isChunked) {
1410 
1411             // Read the end tag
1412             int anEndTag = read_long();
1413 
1414             // End tags should always be negative, and the outermost
1415             // enclosing chunked valuetype should have a -1 end tag.
1416             //
1417             // handleEndOfValue should have assured that we were
1418             // at the end tag position!
1419             if (anEndTag >= 0) {
1420                 throw wrapper.positiveEndTag( CompletionStatus.COMPLETED_MAYBE,
1421                     new Integer(anEndTag), new Integer( get_offset() - 4 ) ) ;
1422             }
1423 
1424             // If the ORB is null, or if we're sure we're talking to
1425             // a foreign ORB, Merlin, or something more recent, we
1426             // use the updated end tag computation, and are more strenuous
1427             // about the values.
1428             if (orb == null ||
1429                 ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) ||
1430                 ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) {
1431 
1432                 // If the end tag we read was less than what we were expecting,
1433                 // then the sender must think it's sent more enclosing
1434                 // chunked valuetypes than we have.  Throw an exception.
1435                 if (anEndTag < chunkedValueNestingLevel)
1436                     throw wrapper.unexpectedEnclosingValuetype(
1437                         CompletionStatus.COMPLETED_MAYBE, new Integer( anEndTag ),
1438                         new Integer( chunkedValueNestingLevel ) ) ;
1439 
1440                 // If the end tag is bigger than what we expected, but
1441                 // still negative, then the sender has done some end tag
1442                 // compaction.  We back up the stream 4 bytes so that the
1443                 // next time readEndTag is called, it will get down here
1444                 // again.  Even with fragmentation, we'll always be able
1445                 // to do this.
1446                 if (anEndTag != chunkedValueNestingLevel) {
1447                     bbwi.position(bbwi.position() - 4);
1448                  }
1449 
1450             } else {
1451 
1452                 // When talking to Kestrel or Ladybird, we use our old
1453                 // end tag rules and are less strict.  If the end tag
1454                 // isn't what we expected, we back up, assuming
1455                 // compaction.
1456                 if (anEndTag != end_flag) {
1457                     bbwi.position(bbwi.position() - 4);
1458                 }
1459             }
1460 
1461             // This only keeps track of the enclosing chunked
1462             // valuetypes
1463             chunkedValueNestingLevel++;
1464         }
1465 
1466         // This keeps track of all enclosing valuetypes
1467         end_flag++;
1468     }
1469 
1470     protected int get_offset() {
1471         return bbwi.position();
1472     }
1473 
1474     private void start_block() {
1475 
1476         // if (outerValueDone)
1477         if (!isChunked)
1478             return;
1479 
1480         // if called from alignAndCheck, need to reset blockLength
1481         // to avoid an infinite recursion loop on read_long() call
1482         blockLength = maxBlockLength;
1483 
1484         blockLength = read_long();
1485 
1486         // Must remember where we began the chunk to calculate how far
1487         // along we are.  See notes above about chunkBeginPos.
1488 
1489         if (blockLength > 0 && blockLength < maxBlockLength) {
1490             blockLength += get_offset();  // _REVISIT_ unsafe, should use a Java long
1491 
1492             // inBlock = true;
1493         } else {
1494 
1495             // System.out.println("start_block snooped a " + Integer.toHexString(blockLength));
1496 
1497             // not a chunk length field
1498             blockLength = maxBlockLength;
1499 
1500             bbwi.position(bbwi.position() - 4);
1501         }
1502     }
1503 
1504     // Makes sure that if we were reading a chunked value, we end up
1505     // at the right place in the stream, no matter how little the
1506     // unmarshalling code read.
1507     //
1508     // After calling this method, if we are chunking, we should be
1509     // in position to read the end tag.
1510     private void handleEndOfValue() {
1511 
1512         // If we're not chunking, we don't have to worry about
1513         // skipping remaining chunks or finding end tags
1514         if (!isChunked)
1515             return;
1516 
1517         // Skip any remaining chunks
1518         while (blockLength != maxBlockLength) {
1519             end_block();
1520             start_block();
1521         }
1522 
1523         // Now look for the end tag
1524 
1525         // This is a little wasteful since we're reading
1526         // this long up to 3 times in the worst cases (once
1527         // in start_block, once here, and once in readEndTag
1528         //
1529         // Peek next long
1530         int nextLong = read_long();
1531         bbwi.position(bbwi.position() - 4);
1532 
1533         // We did find an end tag, so we're done.  readEndTag
1534         // should take care of making sure it's the correct
1535         // end tag, etc.  Remember that since end tags,
1536         // chunk lengths, and valuetags have non overlapping
1537         // ranges, we can tell by the value what the longs are.
1538         if (nextLong < 0)
1539             return;
1540 
1541         if (nextLong == 0 || nextLong >= maxBlockLength) {
1542 
1543             // A custom marshaled valuetype left extra data
1544             // on the wire, and that data had another
1545             // nested value inside of it.  We've just
1546             // read the value tag or null of that nested value.
1547             //
1548             // In an attempt to get by it, we'll try to call
1549             // read_value() to get the nested value off of
1550             // the wire.  Afterwards, we must call handleEndOfValue
1551             // recursively to read any further chunks that the containing
1552             // valuetype might still have after the nested
1553             // value.
1554             read_value();
1555             handleEndOfValue();
1556         } else {
1557             // This probably means that the code to skip chunks has
1558             // an error, and ended up setting blockLength to something
1559             // other than maxBlockLength even though we weren't
1560             // starting a new chunk.
1561             throw wrapper.couldNotSkipBytes( CompletionStatus.COMPLETED_MAYBE,
1562                 new Integer( nextLong ), new Integer( get_offset() ) ) ;
1563         }
1564     }
1565 
1566     private void end_block() {
1567 
1568         // if in a chunk, check for underflow or overflow
1569         if (blockLength != maxBlockLength) {
1570             if (blockLength == get_offset()) {
1571                 // Chunk ended correctly
1572                 blockLength = maxBlockLength;
1573             } else {
1574                 // Skip over anything left by bad unmarshaling code (ex:
1575                 // a buggy custom unmarshaler).  See handleEndOfValue.
1576                 if (blockLength > get_offset()) {
1577                     skipToOffset(blockLength);
1578                 } else {
1579                     throw wrapper.badChunkLength( new Integer( blockLength ),
1580                         new Integer( get_offset() ) ) ;
1581                 }
1582             }
1583         }
1584     }
1585 
1586     private int readValueTag(){
1587         // outerValueDone = false;
1588         return read_long();
1589     }
1590 
1591     public org.omg.CORBA.ORB orb() {
1592         return orb;
1593     }
1594 
1595     // ------------ End RMI related methods --------------------------
1596 
1597     public final void read_boolean_array(boolean[] value, int offset, int length) {
1598         for(int i=0; i < length; i++) {
1599             value[i+offset] = read_boolean();
1600         }
1601     }
1602 
1603     public final void read_char_array(char[] value, int offset, int length) {
1604         for(int i=0; i < length; i++) {
1605             value[i+offset] = read_char();
1606         }
1607     }
1608 
1609     public final void read_wchar_array(char[] value, int offset, int length) {
1610         for(int i=0; i < length; i++) {
1611             value[i+offset] = read_wchar();
1612         }
1613     }
1614 
1615     public final void read_short_array(short[] value, int offset, int length) {
1616         for(int i=0; i < length; i++) {
1617             value[i+offset] = read_short();
1618         }
1619     }
1620 
1621     public final void read_ushort_array(short[] value, int offset, int length) {
1622         read_short_array(value, offset, length);
1623     }
1624 
1625     public final void read_long_array(int[] value, int offset, int length) {
1626         for(int i=0; i < length; i++) {
1627             value[i+offset] = read_long();
1628         }
1629     }
1630 
1631     public final void read_ulong_array(int[] value, int offset, int length) {
1632         read_long_array(value, offset, length);
1633     }
1634 
1635     public final void read_longlong_array(long[] value, int offset, int length) {
1636         for(int i=0; i < length; i++) {
1637             value[i+offset] = read_longlong();
1638         }
1639     }
1640 
1641     public final void read_ulonglong_array(long[] value, int offset, int length) {
1642         read_longlong_array(value, offset, length);
1643     }
1644 
1645     public final void read_float_array(float[] value, int offset, int length) {
1646         for(int i=0; i < length; i++) {
1647             value[i+offset] = read_float();
1648         }
1649     }
1650 
1651     public final void read_double_array(double[] value, int offset, int length) {
1652         for(int i=0; i < length; i++) {
1653             value[i+offset] = read_double();
1654         }
1655     }
1656 
1657     public final void read_any_array(org.omg.CORBA.Any[] value, int offset, int length) {
1658         for(int i=0; i < length; i++) {
1659             value[i+offset] = read_any();
1660         }
1661     }
1662 
1663     //--------------------------------------------------------------------//
1664     // CDRInputStream state management.
1665     //
1666 
1667     /**
1668      * Are we at the end of the input stream?
1669      */
1670 //     public final boolean isAtEnd() {
1671 //      return bbwi.position() == bbwi.buflen;
1672 //     }
1673 
1674 //     public int available() throws IOException {
1675 //         return bbwi.buflen - bbwi.position();
1676 //     }
1677 
1678     private String read_repositoryIds() {
1679 
1680         // Read # of repository ids
1681         int numRepIds = read_long();
1682         if (numRepIds == 0xffffffff) {
1683             int indirection = read_long() + get_offset() - 4;
1684             if (repositoryIdCache != null && repositoryIdCache.containsOrderedVal(indirection))
1685                 return (String)repositoryIdCache.getKey(indirection);
1686             else
1687                 throw wrapper.unableToLocateRepIdArray( new Integer( indirection ) ) ;
1688         } else {
1689 
1690             // read first array element and store it as an indirection to the whole array
1691             int indirection = get_offset();
1692             String repID = read_repositoryId();
1693             if (repositoryIdCache == null)
1694                 repositoryIdCache = new CacheTable(orb,false);
1695             repositoryIdCache.put(repID, indirection);
1696 
1697             // read and ignore the subsequent array elements, but put them in the
1698             // indirection table in case there are later indirections back to them
1699             for (int i = 1; i < numRepIds; i++) {
1700                 read_repositoryId();
1701             }
1702 
1703             return repID;
1704         }
1705     }
1706 
1707     private final String read_repositoryId()
1708     {
1709         String result = readStringOrIndirection(true);
1710 
1711         if (result == null) { // Indirection
1712             int indirection = read_long() + get_offset() - 4;
1713 
1714             if (repositoryIdCache != null && repositoryIdCache.containsOrderedVal(indirection))
1715                 return (String)repositoryIdCache.getKey(indirection);
1716             else
1717                 throw wrapper.badRepIdIndirection( CompletionStatus.COMPLETED_MAYBE,
1718                     new Integer(bbwi.position()) ) ;
1719         } else {
1720             if (repositoryIdCache == null)
1721                 repositoryIdCache = new CacheTable(orb,false);
1722             repositoryIdCache.put(result, stringIndirection);
1723         }
1724 
1725         return result ;
1726     }
1727 
1728     private final String read_codebase_URL()
1729     {
1730         String result = readStringOrIndirection(true);
1731 
1732         if (result == null) { // Indirection
1733             int indirection = read_long() + get_offset() - 4;
1734 
1735             if (codebaseCache != null && codebaseCache.containsVal(indirection))
1736                 return (String)codebaseCache.getKey(indirection);
1737             else
1738                 throw wrapper.badCodebaseIndirection(
1739                     CompletionStatus.COMPLETED_MAYBE,
1740                     new Integer(bbwi.position()) ) ;
1741         } else {
1742             if (codebaseCache == null)
1743                 codebaseCache = new CacheTable(orb,false);
1744             codebaseCache.put(result, stringIndirection);
1745         }
1746 
1747         return result;
1748     }
1749 
1750     /* DataInputStream methods */
1751 
1752     public java.lang.Object read_Abstract () {
1753         return read_abstract_interface();
1754     }
1755 
1756     public java.io.Serializable read_Value () {
1757         return read_value();
1758     }
1759 
1760     public void read_any_array (org.omg.CORBA.AnySeqHolder seq, int offset, int length) {
1761         read_any_array(seq.value, offset, length);
1762     }
1763 
1764     public void read_boolean_array (org.omg.CORBA.BooleanSeqHolder seq, int offset, int length) {
1765         read_boolean_array(seq.value, offset, length);
1766     }
1767 
1768     public void read_char_array (org.omg.CORBA.CharSeqHolder seq, int offset, int length) {
1769         read_char_array(seq.value, offset, length);
1770     }
1771 
1772     public void read_wchar_array (org.omg.CORBA.WCharSeqHolder seq, int offset, int length) {
1773         read_wchar_array(seq.value, offset, length);
1774     }
1775 
1776     public void read_octet_array (org.omg.CORBA.OctetSeqHolder seq, int offset, int length) {
1777         read_octet_array(seq.value, offset, length);
1778     }
1779 
1780     public void read_short_array (org.omg.CORBA.ShortSeqHolder seq, int offset, int length) {
1781         read_short_array(seq.value, offset, length);
1782     }
1783 
1784     public void read_ushort_array (org.omg.CORBA.UShortSeqHolder seq, int offset, int length) {
1785         read_ushort_array(seq.value, offset, length);
1786     }
1787 
1788     public void read_long_array (org.omg.CORBA.LongSeqHolder seq, int offset, int length) {
1789         read_long_array(seq.value, offset, length);
1790     }
1791 
1792     public void read_ulong_array (org.omg.CORBA.ULongSeqHolder seq, int offset, int length) {
1793         read_ulong_array(seq.value, offset, length);
1794     }
1795 
1796     public void read_ulonglong_array (org.omg.CORBA.ULongLongSeqHolder seq, int offset, int length) {
1797         read_ulonglong_array(seq.value, offset, length);
1798     }
1799 
1800     public void read_longlong_array (org.omg.CORBA.LongLongSeqHolder seq, int offset, int length) {
1801         read_longlong_array(seq.value, offset, length);
1802     }
1803 
1804     public void read_float_array (org.omg.CORBA.FloatSeqHolder seq, int offset, int length) {
1805         read_float_array(seq.value, offset, length);
1806     }
1807 
1808     public void read_double_array (org.omg.CORBA.DoubleSeqHolder seq, int offset, int length) {
1809         read_double_array(seq.value, offset, length);
1810     }
1811 
1812     public java.math.BigDecimal read_fixed(short digits, short scale) {
1813         // digits isn't really needed here
1814         StringBuffer buffer = read_fixed_buffer();
1815         if (digits != buffer.length())
1816             throw wrapper.badFixed( new Integer(digits),
1817                 new Integer(buffer.length()) ) ;
1818         buffer.insert(digits - scale, '.');
1819         return new BigDecimal(buffer.toString());
1820     }
1821 
1822     // This method is unable to yield the correct scale.
1823     public java.math.BigDecimal read_fixed() {
1824         return new BigDecimal(read_fixed_buffer().toString());
1825     }
1826 
1827     // Each octet contains (up to) two decimal digits.
1828     // If the fixed type has an odd number of decimal digits, then the representation
1829     // begins with the first (most significant) digit.
1830     // Otherwise, this first half-octet is all zero, and the first digit
1831     // is in the second half-octet.
1832     // The sign configuration, in the last half-octet of the representation,
1833     // is 0xD for negative numbers and 0xC for positive and zero values.
1834     private StringBuffer read_fixed_buffer() {
1835         StringBuffer buffer = new StringBuffer(64);
1836         byte doubleDigit;
1837         int firstDigit;
1838         int secondDigit;
1839         boolean wroteFirstDigit = false;
1840         boolean more = true;
1841         while (more) {
1842             doubleDigit = this.read_octet();
1843             firstDigit = (int)((doubleDigit & 0xf0) >> 4);
1844             secondDigit = (int)(doubleDigit & 0x0f);
1845             if (wroteFirstDigit || firstDigit != 0) {
1846                 buffer.append(Character.forDigit(firstDigit, 10));
1847                 wroteFirstDigit = true;
1848             }
1849             if (secondDigit == 12) {
1850                 // positive number or zero
1851                 if ( ! wroteFirstDigit) {
1852                     // zero
1853                     return new StringBuffer("0.0");
1854                 } else {
1855                     // positive number
1856                     // done
1857                 }
1858                 more = false;
1859             } else if (secondDigit == 13) {
1860                 // negative number
1861                 buffer.insert(0, '-');
1862                 more = false;
1863             } else {
1864                 buffer.append(Character.forDigit(secondDigit, 10));
1865                 wroteFirstDigit = true;
1866             }
1867         }
1868         return buffer;
1869     }
1870 
1871     private final static String _id = "IDL:omg.org/CORBA/DataInputStream:1.0";
1872     private final static String[] _ids = { _id };
1873 
1874     public String[] _truncatable_ids() {
1875         if (_ids == null)
1876             return null;
1877 
1878         return (String[])_ids.clone();
1879     }
1880 
1881     /* for debugging */
1882 
1883     public void printBuffer() {
1884         CDRInputStream_1_0.printBuffer(this.bbwi);
1885     }
1886 
1887     public static void printBuffer(ByteBufferWithInfo bbwi) {
1888 
1889         System.out.println("----- Input Buffer -----");
1890         System.out.println();
1891         System.out.println("Current position: " + bbwi.position());
1892         System.out.println("Total length : " + bbwi.buflen);
1893         System.out.println();
1894 
1895         try {
1896 
1897             char[] charBuf = new char[16];
1898 
1899             for (int i = 0; i < bbwi.buflen; i += 16) {
1900 
1901                 int j = 0;
1902 
1903                 // For every 16 bytes, there is one line
1904                 // of output.  First, the hex output of
1905                 // the 16 bytes with each byte separated
1906                 // by a space.
1907                 while (j < 16 && j + i < bbwi.buflen) {
1908                     int k = bbwi.byteBuffer.get(i + j);
1909                     if (k < 0)
1910                         k = 256 + k;
1911                     String hex = Integer.toHexString(k);
1912                     if (hex.length() == 1)
1913                         hex = "0" + hex;
1914                     System.out.print(hex + " ");
1915                     j++;
1916                 }
1917 
1918                 // Add any extra spaces to align the
1919                 // text column in case we didn't end
1920                 // at 16
1921                 while (j < 16) {
1922                     System.out.print("   ");
1923                     j++;
1924                 }
1925 
1926                 // Now output the ASCII equivalents.  Non-ASCII
1927                 // characters are shown as periods.
1928                 int x = 0;
1929                 while (x < 16 && x + i < bbwi.buflen) {
1930                     if (ORBUtility.isPrintable((char)bbwi.byteBuffer.get(i + x)))
1931                         charBuf[x] = (char)bbwi.byteBuffer.get(i + x);
1932                     else
1933                         charBuf[x] = '.';
1934                     x++;
1935                 }
1936                 System.out.println(new String(charBuf, 0, x));
1937             }
1938 
1939         } catch (Throwable t) {
1940             t.printStackTrace();
1941         }
1942 
1943         System.out.println("------------------------");
1944     }
1945 
1946     public ByteBuffer getByteBuffer() {
1947         ByteBuffer result = null;
1948         if (bbwi != null) {
1949             result = bbwi.byteBuffer;
1950         }
1951         return result;
1952     }
1953 
1954     public int getBufferLength() {
1955         return bbwi.buflen;
1956     }
1957 
1958     public void setBufferLength(int value) {
1959         bbwi.buflen = value;
1960         bbwi.byteBuffer.limit(bbwi.buflen);
1961     }
1962 
1963     public void setByteBufferWithInfo(ByteBufferWithInfo bbwi) {
1964         this.bbwi = bbwi;
1965     }
1966 
1967     public void setByteBuffer(ByteBuffer byteBuffer) {
1968         bbwi.byteBuffer = byteBuffer;
1969     }
1970 
1971     public int getIndex() {
1972         return bbwi.position();
1973     }
1974 
1975     public void setIndex(int value) {
1976         bbwi.position(value);
1977     }
1978 
1979     public boolean isLittleEndian() {
1980         return littleEndian;
1981     }
1982 
1983     public void orb(org.omg.CORBA.ORB orb) {
1984         this.orb = (ORB)orb;
1985     }
1986 
1987     public BufferManagerRead getBufferManager() {
1988         return bufferManagerRead;
1989     }
1990 
1991     private void skipToOffset(int offset) {
1992 
1993         // Number of bytes to skip
1994         int len = offset - get_offset();
1995 
1996         int n = 0;
1997 
1998         while (n < len) {
1999             int avail;
2000             int bytes;
2001             int wanted;
2002 
2003             avail = bbwi.buflen - bbwi.position();
2004             if (avail <= 0) {
2005                 grow(1, 1);
2006                 avail = bbwi.buflen - bbwi.position();
2007             }
2008 
2009             wanted = len - n;
2010             bytes = (wanted < avail) ? wanted : avail;
2011             bbwi.position(bbwi.position() + bytes);
2012             n += bytes;
2013         }
2014     }
2015 
2016 
2017     // Mark and reset -------------------------------------------------
2018 
2019     protected MarkAndResetHandler markAndResetHandler = null;
2020 
2021     protected class StreamMemento
2022     {
2023         // These are the fields that may change after marking
2024         // the stream position, so we need to save them.
2025         private int blockLength_;
2026         private int end_flag_;
2027         private int chunkedValueNestingLevel_;
2028         private int valueIndirection_;
2029         private int stringIndirection_;
2030         private boolean isChunked_;
2031         private javax.rmi.CORBA.ValueHandler valueHandler_;
2032         private ByteBufferWithInfo bbwi_;
2033         private boolean specialNoOptionalDataState_;
2034 
2035         public StreamMemento()
2036         {
2037             blockLength_ = blockLength;
2038             end_flag_ = end_flag;
2039             chunkedValueNestingLevel_ = chunkedValueNestingLevel;
2040             valueIndirection_ = valueIndirection;
2041             stringIndirection_ = stringIndirection;
2042             isChunked_ = isChunked;
2043             valueHandler_ = valueHandler;
2044             specialNoOptionalDataState_ = specialNoOptionalDataState;
2045             bbwi_ = new ByteBufferWithInfo(bbwi);
2046         }
2047     }
2048 
2049     public java.lang.Object createStreamMemento() {
2050         return new StreamMemento();
2051     }
2052 
2053     public void restoreInternalState(java.lang.Object streamMemento) {
2054 
2055         StreamMemento mem = (StreamMemento)streamMemento;
2056 
2057         blockLength = mem.blockLength_;
2058         end_flag = mem.end_flag_;
2059         chunkedValueNestingLevel = mem.chunkedValueNestingLevel_;
2060         valueIndirection = mem.valueIndirection_;
2061         stringIndirection = mem.stringIndirection_;
2062         isChunked = mem.isChunked_;
2063         valueHandler = mem.valueHandler_;
2064         specialNoOptionalDataState = mem.specialNoOptionalDataState_;
2065         bbwi = mem.bbwi_;
2066     }
2067 
2068     public int getPosition() {
2069         return get_offset();
2070     }
2071 
2072     public void mark(int readlimit) {
2073         markAndResetHandler.mark(this);
2074     }
2075 
2076     public void reset() {
2077         markAndResetHandler.reset();
2078     }
2079 
2080     // ---------------------------------- end Mark and Reset
2081 
2082     // Provides a hook so subclasses of CDRInputStream can provide
2083     // a CodeBase.  This ultimately allows us to grab a Connection
2084     // instance in IIOPInputStream, the only subclass where this
2085     // is actually used.
2086     CodeBase getCodeBase() {
2087         return parent.getCodeBase();
2088     }
2089 
2090     /**
2091      * Attempts to find the class described by the given
2092      * repository ID string and expected type.  The first
2093      * attempt is to find the class locally, falling back
2094      * on the URL that came with the value.  The second
2095      * attempt is to use a URL from the remote CodeBase.
2096      */
2097     private Class getClassFromString(String repositoryIDString,
2098                                      String codebaseURL,
2099                                      Class expectedType)
2100     {
2101         RepositoryIdInterface repositoryID
2102             = repIdStrs.getFromString(repositoryIDString);
2103 
2104         try {
2105             try {
2106                 // First try to load the class locally, then use
2107                 // the provided URL (if it isn't null)
2108                 return repositoryID.getClassFromType(expectedType,
2109                                                      codebaseURL);
2110             } catch (ClassNotFoundException cnfeOuter) {
2111 
2112                 try {
2113 
2114                     if (getCodeBase() == null) {
2115                         return null; // class cannot be loaded remotely.
2116                     }
2117 
2118                     // Get a URL from the remote CodeBase and retry
2119                     codebaseURL = getCodeBase().implementation(repositoryIDString);
2120 
2121                     // Don't bother trying to find it locally again if
2122                     // we got a null URL
2123                     if (codebaseURL == null)
2124                         return null;
2125 
2126                     return repositoryID.getClassFromType(expectedType,
2127                                                          codebaseURL);
2128                 } catch (ClassNotFoundException cnfeInner) {
2129                     dprintThrowable(cnfeInner);
2130                     // Failed to load the class
2131                     return null;
2132                 }
2133             }
2134         } catch (MalformedURLException mue) {
2135             // Always report a bad URL
2136             throw wrapper.malformedUrl( CompletionStatus.COMPLETED_MAYBE,
2137                 mue, repositoryIDString, codebaseURL ) ;
2138         }
2139     }
2140 
2141     /**
2142      * Attempts to find the class described by the given
2143      * repository ID string.  At most, three attempts are made:
2144      * Try to find it locally, through the provided URL, and
2145      * finally, via a URL from the remote CodeBase.
2146      */
2147     private Class getClassFromString(String repositoryIDString,
2148                                      String codebaseURL)
2149     {
2150         RepositoryIdInterface repositoryID
2151             = repIdStrs.getFromString(repositoryIDString);
2152 
2153         for (int i = 0; i < 3; i++) {
2154 
2155             try {
2156 
2157                 switch (i)
2158                 {
2159                     case 0:
2160                         // First try to load the class locally
2161                         return repositoryID.getClassFromType();
2162                     case 1:
2163                         // Try to load the class using the provided
2164                         // codebase URL (falls out below)
2165                         break;
2166                     case 2:
2167                         // Try to load the class using a URL from the
2168                         // remote CodeBase
2169                         codebaseURL = getCodeBase().implementation(repositoryIDString);
2170                         break;
2171                 }
2172 
2173                 // Don't bother if the codebaseURL is null
2174                 if (codebaseURL == null)
2175                     continue;
2176 
2177                 return repositoryID.getClassFromType(codebaseURL);
2178 
2179             } catch(ClassNotFoundException cnfe) {
2180                 // Will ultimately return null if all three
2181                 // attempts fail, but don't do anything here.
2182             } catch (MalformedURLException mue) {
2183                 throw wrapper.malformedUrl( CompletionStatus.COMPLETED_MAYBE,
2184                     mue, repositoryIDString, codebaseURL ) ;
2185             }
2186         }
2187 
2188         // If we get here, we have failed to load the class
2189         dprint("getClassFromString failed with rep id "
2190                + repositoryIDString
2191                + " and codebase "
2192                + codebaseURL);
2193 
2194         return null;
2195     }
2196 
2197     // Utility method used to get chars from bytes
2198     char[] getConvertedChars(int numBytes,
2199                              CodeSetConversion.BTCConverter converter) {
2200 
2201         // REVISIT - Look at CodeSetConversion.BTCConverter to see
2202         //           if it can work with an NIO ByteBuffer. We should
2203         //           avoid getting the bytes into an array if possible.
2204 
2205         // To be honest, I doubt this saves much real time
2206         if (bbwi.buflen - bbwi.position() >= numBytes) {
2207             // If the entire string is in this buffer,
2208             // just convert directly from the bbwi rather than
2209             // allocating and copying.
2210             byte[] tmpBuf;
2211             if (bbwi.byteBuffer.hasArray())
2212             {
2213                 tmpBuf = bbwi.byteBuffer.array();
2214             }
2215             else
2216             {
2217                  tmpBuf = new byte[bbwi.buflen];
2218                  // Microbenchmarks are showing a loop of ByteBuffer.get(int)
2219                  // being faster than ByteBuffer.get(byte[], int, int).
2220                  for (int i = 0; i < bbwi.buflen; i++)
2221                      tmpBuf[i] = bbwi.byteBuffer.get(i);
2222             }
2223             char[] result = converter.getChars(tmpBuf,bbwi.position(),numBytes);
2224 
2225             bbwi.position(bbwi.position() + numBytes);
2226             return result;
2227         } else {
2228             // Stretches across buffers.  Unless we provide an
2229             // incremental conversion interface, allocate and
2230             // copy the bytes.
2231             byte[] bytes = new byte[numBytes];
2232             read_octet_array(bytes, 0, bytes.length);
2233 
2234             return converter.getChars(bytes, 0, numBytes);
2235         }
2236     }
2237 
2238     protected CodeSetConversion.BTCConverter getCharConverter() {
2239         if (charConverter == null)
2240             charConverter = parent.createCharBTCConverter();
2241 
2242         return charConverter;
2243     }
2244 
2245     protected CodeSetConversion.BTCConverter getWCharConverter() {
2246         if (wcharConverter == null)
2247             wcharConverter = parent.createWCharBTCConverter();
2248 
2249         return wcharConverter;
2250     }
2251 
2252     protected void dprintThrowable(Throwable t) {
2253         if (debug && t != null)
2254             t.printStackTrace();
2255     }
2256 
2257     protected void dprint(String msg) {
2258         if (debug) {
2259             ORBUtility.dprint(this, msg);
2260         }
2261     }
2262 
2263     /**
2264      * Aligns the current position on the given octet boundary
2265      * if there are enough bytes available to do so.  Otherwise,
2266      * it just returns.  This is used for some (but not all)
2267      * GIOP 1.2 message headers.
2268      */
2269 
2270     void alignOnBoundary(int octetBoundary) {
2271         int needed = computeAlignment(bbwi.position(), octetBoundary);
2272 
2273         if (bbwi.position() + needed <= bbwi.buflen)
2274         {
2275             bbwi.position(bbwi.position() + needed);
2276         }
2277     }
2278 
2279     public void resetCodeSetConverters() {
2280         charConverter = null;
2281         wcharConverter = null;
2282     }
2283 
2284     public void start_value() {
2285         // Read value tag
2286         int vType = readValueTag();
2287 
2288         if (vType == 0) {
2289             // Stream needs to go into a state where it
2290             // throws standard exception until end_value
2291             // is called.  This means the sender didn't
2292             // send any custom data.  If the reader here
2293             // tries to read more, we need to throw an
2294             // exception before reading beyond where
2295             // we're supposed to
2296             specialNoOptionalDataState = true;
2297 
2298             return;
2299         }
2300 
2301         if (vType == 0xffffffff) {
2302             // One should never indirect to a custom wrapper
2303             throw wrapper.customWrapperIndirection(
2304                 CompletionStatus.COMPLETED_MAYBE);
2305         }
2306 
2307         if (repIdUtil.isCodeBasePresent(vType)) {
2308             throw wrapper.customWrapperWithCodebase(
2309                 CompletionStatus.COMPLETED_MAYBE);
2310         }
2311 
2312         if (repIdUtil.getTypeInfo(vType)
2313             != RepositoryIdUtility.SINGLE_REP_TYPE_INFO) {
2314             throw wrapper.customWrapperNotSingleRepid(
2315                 CompletionStatus.COMPLETED_MAYBE);
2316         }
2317 
2318 
2319         // REVISIT - Could verify repository ID even though
2320         // it isn't used elsewhere
2321         read_repositoryId();
2322 
2323         // Note: isChunked should be true here.  Should have
2324         // been set to true in the containing value's read_value
2325         // method.
2326 
2327         start_block();
2328         end_flag--;
2329         chunkedValueNestingLevel--;
2330     }
2331 
2332     public void end_value() {
2333 
2334         if (specialNoOptionalDataState) {
2335             specialNoOptionalDataState = false;
2336             return;
2337         }
2338 
2339         handleEndOfValue();
2340         readEndTag();
2341 
2342         // Note that isChunked should still be true here.
2343         // If the containing valuetype is the highest
2344         // chunked value, it will get set to false
2345         // at the end of read_value.
2346 
2347         // allow for possible continuation chunk
2348         start_block();
2349     }
2350 
2351     public void close() throws IOException
2352     {
2353 
2354         // tell BufferManagerRead to release any ByteBuffers
2355         getBufferManager().close(bbwi);
2356 
2357         // It's possible bbwi.byteBuffer is shared between
2358         // this InputStream and an OutputStream. Thus, we check
2359         // if the Input/Output streams are using the same ByteBuffer.
2360         // If they sharing the same ByteBuffer we need to ensure only
2361         // one of those ByteBuffers are released to the ByteBufferPool.
2362 
2363         if (bbwi != null && getByteBuffer() != null)
2364         {
2365             MessageMediator messageMediator = parent.getMessageMediator();
2366             if (messageMediator != null)
2367             {
2368                 CDROutputObject outputObj =
2369                              (CDROutputObject)messageMediator.getOutputObject();
2370                 if (outputObj != null)
2371                 {
2372                     if (outputObj.isSharing(getByteBuffer()))
2373                     {
2374                         // Set OutputStream's ByteBuffer and bbwi to null
2375                         // so its ByteBuffer cannot be released to the pool
2376                         outputObj.setByteBuffer(null);
2377                         outputObj.setByteBufferWithInfo(null);
2378                     }
2379                 }
2380             }
2381 
2382             // release this stream's ByteBuffer to the pool
2383             ByteBufferPool byteBufferPool = orb.getByteBufferPool();
2384             if (debug)
2385             {
2386                 // print address of ByteBuffer being released
2387                 int bbAddress = System.identityHashCode(bbwi.byteBuffer);
2388                 StringBuffer sb = new StringBuffer(80);
2389                 sb.append(".close - releasing ByteBuffer id (");
2390                 sb.append(bbAddress).append(") to ByteBufferPool.");
2391                 String msg = sb.toString();
2392                 dprint(msg);
2393             }
2394             byteBufferPool.releaseByteBuffer(bbwi.byteBuffer);
2395             bbwi.byteBuffer = null;
2396             bbwi = null;
2397         }
2398     }
2399 }