cdroutputstream_1_0.java

来自「JAVA 所有包」· Java 代码 · 共 1,932 行 · 第 1/4 页

JAVA
1,932
字号
        if (orb == null ||            ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) ||            ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) {            write_long(chunkedValueNestingLevel);        } else {            write_long(end_flag);        }    }    private void writeClass(String repository_id, Class clz) {        if (repository_id == null)            repository_id = repIdStrs.getClassDescValueRepId();        // Write value_tag        int indirection = writeValueTag(mustChunk, true, null);        updateIndirectionTable(indirection, clz, clz);            			        write_repositoryId(repository_id);        if (mustChunk) {	    // Write Value chunk	    start_block();	    end_flag--;            chunkedValueNestingLevel--;        } else            end_flag--;        writeClassBody(clz);        if (mustChunk)	    end_block();			        // Write end tag        writeEndTag(mustChunk);    }    // Pre-Merlin/J2EE 1.3 ORBs wrote the repository ID    // and codebase strings in the wrong order.  This handles    // backwards compatibility.    private void writeClassBody(Class clz) {        if (orb == null ||            ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) ||            ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) {	    write_value(Util.getCodebase(clz));	    write_value(repIdStrs.createForAnyType(clz));        } else {	    write_value(repIdStrs.createForAnyType(clz));	    write_value(Util.getCodebase(clz));        }    }    // Casts and returns an Object as a Serializable    // This is required for JDK 1.1 only to avoid VerifyErrors when    // passing arrays as Serializable    // private java.io.Serializable make_serializable(java.lang.Object object)    // {    //	return (java.io.Serializable)object;    // }    private boolean shouldWriteAsIDLEntity(Serializable object)    {	return ((object instanceof IDLEntity) && (!(object instanceof ValueBase)) &&		(!(object instanceof org.omg.CORBA.Object)));			    }	    private void writeIDLEntity(IDLEntity object) {	// _REVISIT_ could check to see whether chunking really needed 	mustChunk = true;	String repository_id = repIdStrs.createForJavaType(object);	Class clazz = object.getClass();	String codebase = Util.getCodebase(clazz); 			// Write value_tag	int indirection = writeValueTag(true, true, codebase);	updateIndirectionTable(indirection, object, object);			// Write rep. id	write_repositoryId(repository_id);			// Write Value chunk	end_flag--;        chunkedValueNestingLevel--;	start_block();	// Write the IDLEntity using reflection 	try {            ClassLoader clazzLoader = (clazz == null ? null : clazz.getClassLoader());	    final Class helperClass = Utility.loadClassForClass(clazz.getName()+"Helper", codebase,                                                   clazzLoader, clazz, clazzLoader);	    final Class argTypes[] = {org.omg.CORBA.portable.OutputStream.class, clazz};            // getDeclaredMethod requires RuntimePermission accessDeclaredMembers            // if a different class loader is used (even though the javadoc says otherwise)            Method writeMethod = null;            try {                writeMethod = (Method)AccessController.doPrivileged(                    new PrivilegedExceptionAction() {                        public java.lang.Object run() throws NoSuchMethodException {                            return helperClass.getDeclaredMethod(kWriteMethod, argTypes);                        }                    }                );            } catch (PrivilegedActionException pae) {                // this gets caught below                throw (NoSuchMethodException)pae.getException();            }	    java.lang.Object args[] = {parent, object};	    writeMethod.invoke(null, args);	} catch (ClassNotFoundException cnfe) {	    throw wrapper.errorInvokingHelperWrite( CompletionStatus.COMPLETED_MAYBE, cnfe ) ;	} catch(NoSuchMethodException nsme) {	    throw wrapper.errorInvokingHelperWrite( CompletionStatus.COMPLETED_MAYBE, nsme ) ;	} catch(IllegalAccessException iae) {	    throw wrapper.errorInvokingHelperWrite( CompletionStatus.COMPLETED_MAYBE, iae ) ;	} catch(InvocationTargetException ite) {	    throw wrapper.errorInvokingHelperWrite( CompletionStatus.COMPLETED_MAYBE, ite ) ;	}	end_block();			// Write end tag	writeEndTag(true);    }        /* DataOutputStream methods */    public void write_Abstract (java.lang.Object value) {        write_abstract_interface(value);    }    public void write_Value (java.io.Serializable value) {        write_value(value);    }    // This will stay a custom add-on until the java-rtf issue is resolved.    // Then it should be declared in org.omg.CORBA.portable.OutputStream.    //    // Pads the string representation of bigDecimal with zeros to fit the given    // digits and scale before it gets written to the stream.    public void write_fixed(java.math.BigDecimal bigDecimal, short digits, short scale) {        String string = bigDecimal.toString();        String integerPart;        String fractionPart;        StringBuffer stringBuffer;        // Get rid of the sign        if (string.charAt(0) == '-' || string.charAt(0) == '+') {            string = string.substring(1);        }        // Determine integer and fraction parts        int dotIndex = string.indexOf('.');        if (dotIndex == -1) {            integerPart = string;            fractionPart = null;        } else if (dotIndex == 0 ) {            integerPart = null;            fractionPart = string;        } else {            integerPart = string.substring(0, dotIndex);            fractionPart = string.substring(dotIndex + 1);        }        // Pad both parts with zeros as necessary        stringBuffer = new StringBuffer(digits);        if (fractionPart != null) {            stringBuffer.append(fractionPart);        }        while (stringBuffer.length() < scale) {            stringBuffer.append('0');        }        if (integerPart != null) {            stringBuffer.insert(0, integerPart);        }        while (stringBuffer.length() < digits) {            stringBuffer.insert(0, '0');        }        // This string contains no sign or dot        this.write_fixed(stringBuffer.toString(), bigDecimal.signum());    }    // This method should be remove by the java-rtf issue.    // Right now the scale and digits information of the type code is lost.    public void write_fixed(java.math.BigDecimal bigDecimal) {        // This string might contain sign and/or dot        this.write_fixed(bigDecimal.toString(), bigDecimal.signum());    }    // The string may contain a sign and dot    public void write_fixed(String string, int signum) {        int stringLength = string.length();        // Each octet contains (up to) two decimal digits        byte doubleDigit = 0;        char ch;        byte digit;        // First calculate the length of the string without optional sign and dot        int numDigits = 0;        for (int i=0; i<stringLength; i++) {            ch = string.charAt(i);            if (ch == '-' || ch == '+' || ch == '.')                continue;            numDigits++;        }        for (int i=0; i<stringLength; i++) {            ch = string.charAt(i);            if (ch == '-' || ch == '+' || ch == '.')                continue;            digit = (byte)Character.digit(ch, 10);            if (digit == -1) {		throw wrapper.badDigitInFixed( CompletionStatus.COMPLETED_MAYBE ) ;            }            // If the fixed type has an odd number of decimal digits,            // then the representation begins with the first (most significant) digit.            // Otherwise, this first half-octet is all zero, and the first digit            // is in the second half-octet.            if (numDigits % 2 == 0) {                doubleDigit |= digit;                this.write_octet(doubleDigit);                doubleDigit = 0;            } else {                doubleDigit |= (digit << 4);            }            numDigits--;        }        // The sign configuration, in the last half-octet of the representation,        // is 0xD for negative numbers and 0xC for positive and zero values        if (signum == -1) {            doubleDigit |= 0xd;        } else {            doubleDigit |= 0xc;        }        this.write_octet(doubleDigit);    }    private final static String _id = "IDL:omg.org/CORBA/DataOutputStream:1.0";    private final static String[] _ids = { _id };    public String[] _truncatable_ids() {        if (_ids == null)            return null;        return (String[])_ids.clone();    }    /* for debugging */    public void printBuffer() {        CDROutputStream_1_0.printBuffer(this.bbwi);    }    public static void printBuffer(ByteBufferWithInfo bbwi) {        System.out.println("+++++++ Output Buffer ++++++++");        System.out.println();        System.out.println("Current position: " + bbwi.position());        System.out.println("Total length : " + bbwi.buflen);        System.out.println();        char[] charBuf = new char[16];        try {            for (int i = 0; i < bbwi.position(); i += 16) {                                int j = 0;                                // For every 16 bytes, there is one line                // of output.  First, the hex output of                // the 16 bytes with each byte separated                // by a space.                while (j < 16 && j + i < bbwi.position()) {                    int k = bbwi.byteBuffer.get(i + j);                    if (k < 0)                        k = 256 + k;                    String hex = Integer.toHexString(k);                    if (hex.length() == 1)                        hex = "0" + hex;                    System.out.print(hex + " ");                    j++;                }                                // Add any extra spaces to align the                // text column in case we didn't end                // at 16                while (j < 16) {                    System.out.print("   ");                    j++;                }                                // Now output the ASCII equivalents.  Non-ASCII                // characters are shown as periods.                int x = 0;                while (x < 16 && x + i < bbwi.position()) {                    if (ORBUtility.isPrintable((char)bbwi.byteBuffer.get(i + x)))                        charBuf[x] = (char)bbwi.byteBuffer.get(i + x);                    else                        charBuf[x] = '.';                    x++;                }                System.out.println(new String(charBuf, 0, x));            }        } catch (Throwable t) {            t.printStackTrace();        }        System.out.println("++++++++++++++++++++++++++++++");    }    public void writeIndirection(int tag, int posIndirectedTo)    {        // Must ensure that there are no chunks between the tag        // and the actual indirection value.  This isn't talked about        // in the spec, but seems to cause headaches in our code.        // At the very least, this method isolates the indirection code        // that was duplicated so often.        handleSpecialChunkBegin(computeAlignment(4) + 8);        // write indirection tag        write_long(tag);        // write indirection        // Use parent.getRealIndex() so that it can be overridden by TypeCodeOutputStreams/*        System.out.println("CDROutputStream_1_0 writing indirection pos " + posIndirectedTo +                           " - real index " + parent.getRealIndex(get_offset()) + " = " +                           (posIndirectedTo - parent.getRealIndex(get_offset())));*/        write_long(posIndirectedTo - parent.getRealIndex(get_offset()));        handleSpecialChunkEnd();    }    protected CodeSetConversion.CTBConverter getCharConverter() {        if (charConverter == null)            charConverter = parent.createCharCTBConverter();                return charConverter;    }    protected CodeSetConversion.CTBConverter getWCharConverter() {        if (wcharConverter == null)            wcharConverter = parent.createWCharCTBConverter();            return wcharConverter;    }    protected void dprint(String msg) {        if (debug)            ORBUtility.dprint(this, msg);    }    void alignOnBoundary(int octetBoundary) {        alignAndReserve(octetBoundary, 0);    }    public void start_value(String rep_id) {        if (debug) {            dprint("start_value w/ rep id "		   + rep_id		   + " called at pos "		   + get_offset() 		   + " position "		   + bbwi.position());	}	if (inBlock)	    end_block();                // Write value_tag        writeValueTag(true, true, null);				        // Write rep. id        write_repositoryId(rep_id);				        // Write Value chunk        end_flag--;        chunkedValueNestingLevel--;        // Make sure to chunk the custom data        start_block();    }    public void end_value() {        if (debug) {            dprint("end_value called at pos "		   + get_offset()		   + " position "		   + bbwi.position());	}        end_block();        writeEndTag(true);	// Check to see if we need to start another block for a	// possible outer value.  Since we're in the stream        // format 2 custom type contained by another custom        // type, mustChunk should always be true.        //        // Here's why we need to open a continuation chunk:        //        // We need to enclose the default data of the        // next subclass down in chunks.  There won't be        // an end tag separating the superclass optional        // data and the subclass's default data.        if (debug) {            dprint("mustChunk is " + mustChunk);	}	if (mustChunk) {	    start_block();        }    }    public void close() throws IOException    {        // tell BufferManagerWrite to release any ByteBuffers        getBufferManager().close();        // It's possible bbwi.byteBuffer is shared between        // this OutputStream and an InputStream. Thus, we check        // if the Input/Output streams are using the same ByteBuffer.        // If they sharing the same ByteBuffer we need to ensure only        // one of those ByteBuffers are released to the ByteBufferPool.        if (getByteBufferWithInfo() != null && getByteBuffer() != null)        {            int bbHash = System.identityHashCode(bbwi.byteBuffer);            MessageMediator messageMediator = parent.getMessageMediator();            if (messageMediator != null)            {                CDRInputObject inputObj =                                (CDRInputObject)messageMediator.getInputObject();                if (inputObj != null)                {                    ByteBuffer inputBb = inputObj.getByteBuffer();                    int iBbHash = 0;                    if (inputBb != null)                    {                        iBbHash = System.identityHashCode(inputBb);                        if (bbHash == iBbHash)  // shared?                        {                            // Set InputStream's ByteBuffer and bbwi to null                            // so its ByteBuffer cannot be released to the pool                            inputObj.setByteBuffer(null);                            inputObj.setByteBufferWithInfo(null);                        }                    }                }            }            // release this stream's ByteBuffer to the pool            ByteBufferPool byteBufferPool = orb.getByteBufferPool();            if (debug)            {                // print address of ByteBuffer being released                int bbAddress = System.identityHashCode(bbwi.byteBuffer);                StringBuffer sb = new StringBuffer(80);                sb.append(".close - releasing ByteBuffer id (");                sb.append(bbAddress).append(") to ByteBufferPool.");                String msg = sb.toString();                dprint(msg);             }             byteBufferPool.releaseByteBuffer(getByteBuffer());             bbwi.byteBuffer = null;             bbwi = null;        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?